LoopVectorizer: Add a check that the backedge taken count + 1 does not overflow
[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   // Count holds the overall loop count (N).
1991   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1992                                    BypassBlock->getTerminator());
1993
1994   // The loop index does not have to start at Zero. Find the original start
1995   // value from the induction PHI node. If we don't have an induction variable
1996   // then we know that it starts at zero.
1997   Builder.SetInsertPoint(BypassBlock->getTerminator());
1998   Value *StartIdx = ExtendedIdx = OldInduction ?
1999     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2000                        IdxTy):
2001     ConstantInt::get(IdxTy, 0);
2002
2003   LoopBypassBlocks.push_back(BypassBlock);
2004
2005   // Split the single block loop into the two loop structure described above.
2006   BasicBlock *VectorPH =
2007   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2008   BasicBlock *VecBody =
2009   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2010   BasicBlock *MiddleBlock =
2011   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2012   BasicBlock *ScalarPH =
2013   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2014
2015   // Create and register the new vector loop.
2016   Loop* Lp = new Loop();
2017   Loop *ParentLoop = OrigLoop->getParentLoop();
2018
2019   // Insert the new loop into the loop nest and register the new basic blocks
2020   // before calling any utilities such as SCEV that require valid LoopInfo.
2021   if (ParentLoop) {
2022     ParentLoop->addChildLoop(Lp);
2023     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2024     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2025     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2026   } else {
2027     LI->addTopLevelLoop(Lp);
2028   }
2029   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2030
2031   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2032   // inside the loop.
2033   Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2034
2035   // Generate the induction variable.
2036   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2037   Induction = Builder.CreatePHI(IdxTy, 2, "index");
2038   // The loop step is equal to the vectorization factor (num of SIMD elements)
2039   // times the unroll factor (num of SIMD instructions).
2040   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2041
2042   // This is the IR builder that we use to add all of the logic for bypassing
2043   // the new vector loop.
2044   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2045   setDebugLocFromInst(BypassBuilder,
2046                       getDebugLocFromInstOrOperands(OldInduction));
2047
2048   // We may need to extend the index in case there is a type mismatch.
2049   // We know that the count starts at zero and does not overflow.
2050   if (Count->getType() != IdxTy) {
2051     // The exit count can be of pointer type. Convert it to the correct
2052     // integer type.
2053     if (ExitCount->getType()->isPointerTy())
2054       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2055     else
2056       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2057   }
2058
2059   // Add the start index to the loop count to get the new end index.
2060   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2061
2062   // Now we need to generate the expression for N - (N % VF), which is
2063   // the part that the vectorized body will execute.
2064   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2065   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2066   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2067                                                      "end.idx.rnd.down");
2068
2069   // Now, compare the new count to zero. If it is zero skip the vector loop and
2070   // jump to the scalar loop.
2071   Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
2072                                           "cmp.zero");
2073
2074   BasicBlock *LastBypassBlock = BypassBlock;
2075
2076   // Generate code to check that the loops trip count that we computed by adding
2077   // one to the backedge-taken count will not overflow.
2078   {
2079     auto PastOverflowCheck = std::next(BasicBlock::iterator(CheckBCOverflow));
2080     BasicBlock *CheckBlock =
2081         LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2082     if (ParentLoop)
2083       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2084     LoopBypassBlocks.push_back(CheckBlock);
2085     Instruction *OldTerm = LastBypassBlock->getTerminator();
2086     BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2087     OldTerm->eraseFromParent();
2088     LastBypassBlock = CheckBlock;
2089   }
2090
2091   // Generate the code to check that the strides we assumed to be one are really
2092   // one. We want the new basic block to start at the first instruction in a
2093   // sequence of instructions that form a check.
2094   Instruction *StrideCheck;
2095   Instruction *FirstCheckInst;
2096   std::tie(FirstCheckInst, StrideCheck) =
2097       addStrideCheck(LastBypassBlock->getTerminator());
2098   if (StrideCheck) {
2099     // Create a new block containing the stride check.
2100     BasicBlock *CheckBlock =
2101         LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2102     if (ParentLoop)
2103       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2104     LoopBypassBlocks.push_back(CheckBlock);
2105
2106     // Replace the branch into the memory check block with a conditional branch
2107     // for the "few elements case".
2108     Instruction *OldTerm = LastBypassBlock->getTerminator();
2109     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2110     OldTerm->eraseFromParent();
2111
2112     Cmp = StrideCheck;
2113     LastBypassBlock = CheckBlock;
2114   }
2115
2116   // Generate the code that checks in runtime if arrays overlap. We put the
2117   // checks into a separate block to make the more common case of few elements
2118   // faster.
2119   Instruction *MemRuntimeCheck;
2120   std::tie(FirstCheckInst, MemRuntimeCheck) =
2121       addRuntimeCheck(LastBypassBlock->getTerminator());
2122   if (MemRuntimeCheck) {
2123     // Create a new block containing the memory check.
2124     BasicBlock *CheckBlock =
2125         LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2126     if (ParentLoop)
2127       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2128     LoopBypassBlocks.push_back(CheckBlock);
2129
2130     // Replace the branch into the memory check block with a conditional branch
2131     // for the "few elements case".
2132     Instruction *OldTerm = LastBypassBlock->getTerminator();
2133     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2134     OldTerm->eraseFromParent();
2135
2136     Cmp = MemRuntimeCheck;
2137     LastBypassBlock = CheckBlock;
2138   }
2139
2140   LastBypassBlock->getTerminator()->eraseFromParent();
2141   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2142                      LastBypassBlock);
2143
2144   // We are going to resume the execution of the scalar loop.
2145   // Go over all of the induction variables that we found and fix the
2146   // PHIs that are left in the scalar version of the loop.
2147   // The starting values of PHI nodes depend on the counter of the last
2148   // iteration in the vectorized loop.
2149   // If we come from a bypass edge then we need to start from the original
2150   // start value.
2151
2152   // This variable saves the new starting index for the scalar loop.
2153   PHINode *ResumeIndex = nullptr;
2154   LoopVectorizationLegality::InductionList::iterator I, E;
2155   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2156   // Set builder to point to last bypass block.
2157   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2158   for (I = List->begin(), E = List->end(); I != E; ++I) {
2159     PHINode *OrigPhi = I->first;
2160     LoopVectorizationLegality::InductionInfo II = I->second;
2161
2162     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2163     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2164                                          MiddleBlock->getTerminator());
2165     // We might have extended the type of the induction variable but we need a
2166     // truncated version for the scalar loop.
2167     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2168       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2169                       MiddleBlock->getTerminator()) : nullptr;
2170
2171     // Create phi nodes to merge from the  backedge-taken check block.
2172     PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2173                                            ScalarPH->getTerminator());
2174     BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2175
2176     PHINode *BCTruncResumeVal = nullptr;
2177     if (OrigPhi == OldInduction) {
2178       BCTruncResumeVal =
2179           PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2180                           ScalarPH->getTerminator());
2181       BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2182     }
2183
2184     Value *EndValue = nullptr;
2185     switch (II.IK) {
2186     case LoopVectorizationLegality::IK_NoInduction:
2187       llvm_unreachable("Unknown induction");
2188     case LoopVectorizationLegality::IK_IntInduction: {
2189       // Handle the integer induction counter.
2190       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2191
2192       // We have the canonical induction variable.
2193       if (OrigPhi == OldInduction) {
2194         // Create a truncated version of the resume value for the scalar loop,
2195         // we might have promoted the type to a larger width.
2196         EndValue =
2197           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2198         // The new PHI merges the original incoming value, in case of a bypass,
2199         // or the value at the end of the vectorized loop.
2200         for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2201           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2202         TruncResumeVal->addIncoming(EndValue, VecBody);
2203
2204         BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2205
2206         // We know what the end value is.
2207         EndValue = IdxEndRoundDown;
2208         // We also know which PHI node holds it.
2209         ResumeIndex = ResumeVal;
2210         break;
2211       }
2212
2213       // Not the canonical induction variable - add the vector loop count to the
2214       // start value.
2215       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2216                                                    II.StartValue->getType(),
2217                                                    "cast.crd");
2218       EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2219       break;
2220     }
2221     case LoopVectorizationLegality::IK_ReverseIntInduction: {
2222       // Convert the CountRoundDown variable to the PHI size.
2223       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2224                                                    II.StartValue->getType(),
2225                                                    "cast.crd");
2226       // Handle reverse integer induction counter.
2227       EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2228       break;
2229     }
2230     case LoopVectorizationLegality::IK_PtrInduction: {
2231       // For pointer induction variables, calculate the offset using
2232       // the end index.
2233       EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2234                                          "ptr.ind.end");
2235       break;
2236     }
2237     case LoopVectorizationLegality::IK_ReversePtrInduction: {
2238       // The value at the end of the loop for the reverse pointer is calculated
2239       // by creating a GEP with a negative index starting from the start value.
2240       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2241       Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2242                                               "rev.ind.end");
2243       EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2244                                          "rev.ptr.ind.end");
2245       break;
2246     }
2247     }// end of case
2248
2249     // The new PHI merges the original incoming value, in case of a bypass,
2250     // or the value at the end of the vectorized loop.
2251     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2252       if (OrigPhi == OldInduction)
2253         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2254       else
2255         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2256     }
2257     ResumeVal->addIncoming(EndValue, VecBody);
2258
2259     // Fix the scalar body counter (PHI node).
2260     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2261
2262     // The old induction's phi node in the scalar body needs the truncated
2263     // value.
2264     if (OrigPhi == OldInduction) {
2265       BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2266       OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2267     } else {
2268       BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2269       OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2270     }
2271   }
2272
2273   // If we are generating a new induction variable then we also need to
2274   // generate the code that calculates the exit value. This value is not
2275   // simply the end of the counter because we may skip the vectorized body
2276   // in case of a runtime check.
2277   if (!OldInduction){
2278     assert(!ResumeIndex && "Unexpected resume value found");
2279     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2280                                   MiddleBlock->getTerminator());
2281     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2282       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2283     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2284   }
2285
2286   // Make sure that we found the index where scalar loop needs to continue.
2287   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2288          "Invalid resume Index");
2289
2290   // Add a check in the middle block to see if we have completed
2291   // all of the iterations in the first vector loop.
2292   // If (N - N%VF) == N, then we *don't* need to run the remainder.
2293   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2294                                 ResumeIndex, "cmp.n",
2295                                 MiddleBlock->getTerminator());
2296
2297   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2298   // Remove the old terminator.
2299   MiddleBlock->getTerminator()->eraseFromParent();
2300
2301   // Create i+1 and fill the PHINode.
2302   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2303   Induction->addIncoming(StartIdx, VectorPH);
2304   Induction->addIncoming(NextIdx, VecBody);
2305   // Create the compare.
2306   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2307   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2308
2309   // Now we have two terminators. Remove the old one from the block.
2310   VecBody->getTerminator()->eraseFromParent();
2311
2312   // Get ready to start creating new instructions into the vectorized body.
2313   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2314
2315   // Save the state.
2316   LoopVectorPreHeader = VectorPH;
2317   LoopScalarPreHeader = ScalarPH;
2318   LoopMiddleBlock = MiddleBlock;
2319   LoopExitBlock = ExitBlock;
2320   LoopVectorBody.push_back(VecBody);
2321   LoopScalarBody = OldBasicBlock;
2322
2323   LoopVectorizeHints Hints(Lp, true);
2324   Hints.setAlreadyVectorized(Lp);
2325 }
2326
2327 /// This function returns the identity element (or neutral element) for
2328 /// the operation K.
2329 Constant*
2330 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2331   switch (K) {
2332   case RK_IntegerXor:
2333   case RK_IntegerAdd:
2334   case RK_IntegerOr:
2335     // Adding, Xoring, Oring zero to a number does not change it.
2336     return ConstantInt::get(Tp, 0);
2337   case RK_IntegerMult:
2338     // Multiplying a number by 1 does not change it.
2339     return ConstantInt::get(Tp, 1);
2340   case RK_IntegerAnd:
2341     // AND-ing a number with an all-1 value does not change it.
2342     return ConstantInt::get(Tp, -1, true);
2343   case  RK_FloatMult:
2344     // Multiplying a number by 1 does not change it.
2345     return ConstantFP::get(Tp, 1.0L);
2346   case  RK_FloatAdd:
2347     // Adding zero to a number does not change it.
2348     return ConstantFP::get(Tp, 0.0L);
2349   default:
2350     llvm_unreachable("Unknown reduction kind");
2351   }
2352 }
2353
2354 /// This function translates the reduction kind to an LLVM binary operator.
2355 static unsigned
2356 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2357   switch (Kind) {
2358     case LoopVectorizationLegality::RK_IntegerAdd:
2359       return Instruction::Add;
2360     case LoopVectorizationLegality::RK_IntegerMult:
2361       return Instruction::Mul;
2362     case LoopVectorizationLegality::RK_IntegerOr:
2363       return Instruction::Or;
2364     case LoopVectorizationLegality::RK_IntegerAnd:
2365       return Instruction::And;
2366     case LoopVectorizationLegality::RK_IntegerXor:
2367       return Instruction::Xor;
2368     case LoopVectorizationLegality::RK_FloatMult:
2369       return Instruction::FMul;
2370     case LoopVectorizationLegality::RK_FloatAdd:
2371       return Instruction::FAdd;
2372     case LoopVectorizationLegality::RK_IntegerMinMax:
2373       return Instruction::ICmp;
2374     case LoopVectorizationLegality::RK_FloatMinMax:
2375       return Instruction::FCmp;
2376     default:
2377       llvm_unreachable("Unknown reduction operation");
2378   }
2379 }
2380
2381 Value *createMinMaxOp(IRBuilder<> &Builder,
2382                       LoopVectorizationLegality::MinMaxReductionKind RK,
2383                       Value *Left,
2384                       Value *Right) {
2385   CmpInst::Predicate P = CmpInst::ICMP_NE;
2386   switch (RK) {
2387   default:
2388     llvm_unreachable("Unknown min/max reduction kind");
2389   case LoopVectorizationLegality::MRK_UIntMin:
2390     P = CmpInst::ICMP_ULT;
2391     break;
2392   case LoopVectorizationLegality::MRK_UIntMax:
2393     P = CmpInst::ICMP_UGT;
2394     break;
2395   case LoopVectorizationLegality::MRK_SIntMin:
2396     P = CmpInst::ICMP_SLT;
2397     break;
2398   case LoopVectorizationLegality::MRK_SIntMax:
2399     P = CmpInst::ICMP_SGT;
2400     break;
2401   case LoopVectorizationLegality::MRK_FloatMin:
2402     P = CmpInst::FCMP_OLT;
2403     break;
2404   case LoopVectorizationLegality::MRK_FloatMax:
2405     P = CmpInst::FCMP_OGT;
2406     break;
2407   }
2408
2409   Value *Cmp;
2410   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2411       RK == LoopVectorizationLegality::MRK_FloatMax)
2412     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2413   else
2414     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2415
2416   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2417   return Select;
2418 }
2419
2420 namespace {
2421 struct CSEDenseMapInfo {
2422   static bool canHandle(Instruction *I) {
2423     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2424            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2425   }
2426   static inline Instruction *getEmptyKey() {
2427     return DenseMapInfo<Instruction *>::getEmptyKey();
2428   }
2429   static inline Instruction *getTombstoneKey() {
2430     return DenseMapInfo<Instruction *>::getTombstoneKey();
2431   }
2432   static unsigned getHashValue(Instruction *I) {
2433     assert(canHandle(I) && "Unknown instruction!");
2434     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2435                                                            I->value_op_end()));
2436   }
2437   static bool isEqual(Instruction *LHS, Instruction *RHS) {
2438     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2439         LHS == getTombstoneKey() || RHS == getTombstoneKey())
2440       return LHS == RHS;
2441     return LHS->isIdenticalTo(RHS);
2442   }
2443 };
2444 }
2445
2446 /// \brief Check whether this block is a predicated block.
2447 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2448 /// = ...;  " blocks. We start with one vectorized basic block. For every
2449 /// conditional block we split this vectorized block. Therefore, every second
2450 /// block will be a predicated one.
2451 static bool isPredicatedBlock(unsigned BlockNum) {
2452   return BlockNum % 2;
2453 }
2454
2455 ///\brief Perform cse of induction variable instructions.
2456 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2457   // Perform simple cse.
2458   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2459   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2460     BasicBlock *BB = BBs[i];
2461     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2462       Instruction *In = I++;
2463
2464       if (!CSEDenseMapInfo::canHandle(In))
2465         continue;
2466
2467       // Check if we can replace this instruction with any of the
2468       // visited instructions.
2469       if (Instruction *V = CSEMap.lookup(In)) {
2470         In->replaceAllUsesWith(V);
2471         In->eraseFromParent();
2472         continue;
2473       }
2474       // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2475       // ...;" blocks for predicated stores. Every second block is a predicated
2476       // block.
2477       if (isPredicatedBlock(i))
2478         continue;
2479
2480       CSEMap[In] = In;
2481     }
2482   }
2483 }
2484
2485 /// \brief Adds a 'fast' flag to floating point operations.
2486 static Value *addFastMathFlag(Value *V) {
2487   if (isa<FPMathOperator>(V)){
2488     FastMathFlags Flags;
2489     Flags.setUnsafeAlgebra();
2490     cast<Instruction>(V)->setFastMathFlags(Flags);
2491   }
2492   return V;
2493 }
2494
2495 void InnerLoopVectorizer::vectorizeLoop() {
2496   //===------------------------------------------------===//
2497   //
2498   // Notice: any optimization or new instruction that go
2499   // into the code below should be also be implemented in
2500   // the cost-model.
2501   //
2502   //===------------------------------------------------===//
2503   Constant *Zero = Builder.getInt32(0);
2504
2505   // In order to support reduction variables we need to be able to vectorize
2506   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2507   // stages. First, we create a new vector PHI node with no incoming edges.
2508   // We use this value when we vectorize all of the instructions that use the
2509   // PHI. Next, after all of the instructions in the block are complete we
2510   // add the new incoming edges to the PHI. At this point all of the
2511   // instructions in the basic block are vectorized, so we can use them to
2512   // construct the PHI.
2513   PhiVector RdxPHIsToFix;
2514
2515   // Scan the loop in a topological order to ensure that defs are vectorized
2516   // before users.
2517   LoopBlocksDFS DFS(OrigLoop);
2518   DFS.perform(LI);
2519
2520   // Vectorize all of the blocks in the original loop.
2521   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2522        be = DFS.endRPO(); bb != be; ++bb)
2523     vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2524
2525   // At this point every instruction in the original loop is widened to
2526   // a vector form. We are almost done. Now, we need to fix the PHI nodes
2527   // that we vectorized. The PHI nodes are currently empty because we did
2528   // not want to introduce cycles. Notice that the remaining PHI nodes
2529   // that we need to fix are reduction variables.
2530
2531   // Create the 'reduced' values for each of the induction vars.
2532   // The reduced values are the vector values that we scalarize and combine
2533   // after the loop is finished.
2534   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2535        it != e; ++it) {
2536     PHINode *RdxPhi = *it;
2537     assert(RdxPhi && "Unable to recover vectorized PHI");
2538
2539     // Find the reduction variable descriptor.
2540     assert(Legal->getReductionVars()->count(RdxPhi) &&
2541            "Unable to find the reduction variable");
2542     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2543     (*Legal->getReductionVars())[RdxPhi];
2544
2545     setDebugLocFromInst(Builder, RdxDesc.StartValue);
2546
2547     // We need to generate a reduction vector from the incoming scalar.
2548     // To do so, we need to generate the 'identity' vector and override
2549     // one of the elements with the incoming scalar reduction. We need
2550     // to do it in the vector-loop preheader.
2551     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2552
2553     // This is the vector-clone of the value that leaves the loop.
2554     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2555     Type *VecTy = VectorExit[0]->getType();
2556
2557     // Find the reduction identity variable. Zero for addition, or, xor,
2558     // one for multiplication, -1 for And.
2559     Value *Identity;
2560     Value *VectorStart;
2561     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2562         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2563       // MinMax reduction have the start value as their identify.
2564       if (VF == 1) {
2565         VectorStart = Identity = RdxDesc.StartValue;
2566       } else {
2567         VectorStart = Identity = Builder.CreateVectorSplat(VF,
2568                                                            RdxDesc.StartValue,
2569                                                            "minmax.ident");
2570       }
2571     } else {
2572       // Handle other reduction kinds:
2573       Constant *Iden =
2574       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2575                                                       VecTy->getScalarType());
2576       if (VF == 1) {
2577         Identity = Iden;
2578         // This vector is the Identity vector where the first element is the
2579         // incoming scalar reduction.
2580         VectorStart = RdxDesc.StartValue;
2581       } else {
2582         Identity = ConstantVector::getSplat(VF, Iden);
2583
2584         // This vector is the Identity vector where the first element is the
2585         // incoming scalar reduction.
2586         VectorStart = Builder.CreateInsertElement(Identity,
2587                                                   RdxDesc.StartValue, Zero);
2588       }
2589     }
2590
2591     // Fix the vector-loop phi.
2592     // We created the induction variable so we know that the
2593     // preheader is the first entry.
2594     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2595
2596     // Reductions do not have to start at zero. They can start with
2597     // any loop invariant values.
2598     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2599     BasicBlock *Latch = OrigLoop->getLoopLatch();
2600     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2601     VectorParts &Val = getVectorValue(LoopVal);
2602     for (unsigned part = 0; part < UF; ++part) {
2603       // Make sure to add the reduction stat value only to the
2604       // first unroll part.
2605       Value *StartVal = (part == 0) ? VectorStart : Identity;
2606       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2607       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2608                                                   LoopVectorBody.back());
2609     }
2610
2611     // Before each round, move the insertion point right between
2612     // the PHIs and the values we are going to write.
2613     // This allows us to write both PHINodes and the extractelement
2614     // instructions.
2615     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2616
2617     VectorParts RdxParts;
2618     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2619     for (unsigned part = 0; part < UF; ++part) {
2620       // This PHINode contains the vectorized reduction variable, or
2621       // the initial value vector, if we bypass the vector loop.
2622       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2623       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2624       Value *StartVal = (part == 0) ? VectorStart : Identity;
2625       for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2626         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2627       NewPhi->addIncoming(RdxExitVal[part],
2628                           LoopVectorBody.back());
2629       RdxParts.push_back(NewPhi);
2630     }
2631
2632     // Reduce all of the unrolled parts into a single vector.
2633     Value *ReducedPartRdx = RdxParts[0];
2634     unsigned Op = getReductionBinOp(RdxDesc.Kind);
2635     setDebugLocFromInst(Builder, ReducedPartRdx);
2636     for (unsigned part = 1; part < UF; ++part) {
2637       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2638         // Floating point operations had to be 'fast' to enable the reduction.
2639         ReducedPartRdx = addFastMathFlag(
2640             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2641                                 ReducedPartRdx, "bin.rdx"));
2642       else
2643         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2644                                         ReducedPartRdx, RdxParts[part]);
2645     }
2646
2647     if (VF > 1) {
2648       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2649       // and vector ops, reducing the set of values being computed by half each
2650       // round.
2651       assert(isPowerOf2_32(VF) &&
2652              "Reduction emission only supported for pow2 vectors!");
2653       Value *TmpVec = ReducedPartRdx;
2654       SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2655       for (unsigned i = VF; i != 1; i >>= 1) {
2656         // Move the upper half of the vector to the lower half.
2657         for (unsigned j = 0; j != i/2; ++j)
2658           ShuffleMask[j] = Builder.getInt32(i/2 + j);
2659
2660         // Fill the rest of the mask with undef.
2661         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2662                   UndefValue::get(Builder.getInt32Ty()));
2663
2664         Value *Shuf =
2665         Builder.CreateShuffleVector(TmpVec,
2666                                     UndefValue::get(TmpVec->getType()),
2667                                     ConstantVector::get(ShuffleMask),
2668                                     "rdx.shuf");
2669
2670         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2671           // Floating point operations had to be 'fast' to enable the reduction.
2672           TmpVec = addFastMathFlag(Builder.CreateBinOp(
2673               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2674         else
2675           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2676       }
2677
2678       // The result is in the first element of the vector.
2679       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2680                                                     Builder.getInt32(0));
2681     }
2682
2683     // Create a phi node that merges control-flow from the backedge-taken check
2684     // block and the middle block.
2685     PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2686                                           LoopScalarPreHeader->getTerminator());
2687     BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2688     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2689
2690     // Now, we need to fix the users of the reduction variable
2691     // inside and outside of the scalar remainder loop.
2692     // We know that the loop is in LCSSA form. We need to update the
2693     // PHI nodes in the exit blocks.
2694     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2695          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2696       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2697       if (!LCSSAPhi) break;
2698
2699       // All PHINodes need to have a single entry edge, or two if
2700       // we already fixed them.
2701       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2702
2703       // We found our reduction value exit-PHI. Update it with the
2704       // incoming bypass edge.
2705       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2706         // Add an edge coming from the bypass.
2707         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2708         break;
2709       }
2710     }// end of the LCSSA phi scan.
2711
2712     // Fix the scalar loop reduction variable with the incoming reduction sum
2713     // from the vector body and from the backedge value.
2714     int IncomingEdgeBlockIdx =
2715     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2716     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2717     // Pick the other block.
2718     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2719     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2720     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2721   }// end of for each redux variable.
2722
2723   fixLCSSAPHIs();
2724
2725   // Remove redundant induction instructions.
2726   cse(LoopVectorBody);
2727 }
2728
2729 void InnerLoopVectorizer::fixLCSSAPHIs() {
2730   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2731        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2732     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2733     if (!LCSSAPhi) break;
2734     if (LCSSAPhi->getNumIncomingValues() == 1)
2735       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2736                             LoopMiddleBlock);
2737   }
2738
2739
2740 InnerLoopVectorizer::VectorParts
2741 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2742   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2743          "Invalid edge");
2744
2745   // Look for cached value.
2746   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2747   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2748   if (ECEntryIt != MaskCache.end())
2749     return ECEntryIt->second;
2750
2751   VectorParts SrcMask = createBlockInMask(Src);
2752
2753   // The terminator has to be a branch inst!
2754   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2755   assert(BI && "Unexpected terminator found");
2756
2757   if (BI->isConditional()) {
2758     VectorParts EdgeMask = getVectorValue(BI->getCondition());
2759
2760     if (BI->getSuccessor(0) != Dst)
2761       for (unsigned part = 0; part < UF; ++part)
2762         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2763
2764     for (unsigned part = 0; part < UF; ++part)
2765       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2766
2767     MaskCache[Edge] = EdgeMask;
2768     return EdgeMask;
2769   }
2770
2771   MaskCache[Edge] = SrcMask;
2772   return SrcMask;
2773 }
2774
2775 InnerLoopVectorizer::VectorParts
2776 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2777   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2778
2779   // Loop incoming mask is all-one.
2780   if (OrigLoop->getHeader() == BB) {
2781     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2782     return getVectorValue(C);
2783   }
2784
2785   // This is the block mask. We OR all incoming edges, and with zero.
2786   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2787   VectorParts BlockMask = getVectorValue(Zero);
2788
2789   // For each pred:
2790   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2791     VectorParts EM = createEdgeMask(*it, BB);
2792     for (unsigned part = 0; part < UF; ++part)
2793       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2794   }
2795
2796   return BlockMask;
2797 }
2798
2799 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2800                                               InnerLoopVectorizer::VectorParts &Entry,
2801                                               unsigned UF, unsigned VF, PhiVector *PV) {
2802   PHINode* P = cast<PHINode>(PN);
2803   // Handle reduction variables:
2804   if (Legal->getReductionVars()->count(P)) {
2805     for (unsigned part = 0; part < UF; ++part) {
2806       // This is phase one of vectorizing PHIs.
2807       Type *VecTy = (VF == 1) ? PN->getType() :
2808       VectorType::get(PN->getType(), VF);
2809       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2810                                     LoopVectorBody.back()-> getFirstInsertionPt());
2811     }
2812     PV->push_back(P);
2813     return;
2814   }
2815
2816   setDebugLocFromInst(Builder, P);
2817   // Check for PHI nodes that are lowered to vector selects.
2818   if (P->getParent() != OrigLoop->getHeader()) {
2819     // We know that all PHIs in non-header blocks are converted into
2820     // selects, so we don't have to worry about the insertion order and we
2821     // can just use the builder.
2822     // At this point we generate the predication tree. There may be
2823     // duplications since this is a simple recursive scan, but future
2824     // optimizations will clean it up.
2825
2826     unsigned NumIncoming = P->getNumIncomingValues();
2827
2828     // Generate a sequence of selects of the form:
2829     // SELECT(Mask3, In3,
2830     //      SELECT(Mask2, In2,
2831     //                   ( ...)))
2832     for (unsigned In = 0; In < NumIncoming; In++) {
2833       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2834                                         P->getParent());
2835       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2836
2837       for (unsigned part = 0; part < UF; ++part) {
2838         // We might have single edge PHIs (blocks) - use an identity
2839         // 'select' for the first PHI operand.
2840         if (In == 0)
2841           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2842                                              In0[part]);
2843         else
2844           // Select between the current value and the previous incoming edge
2845           // based on the incoming mask.
2846           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2847                                              Entry[part], "predphi");
2848       }
2849     }
2850     return;
2851   }
2852
2853   // This PHINode must be an induction variable.
2854   // Make sure that we know about it.
2855   assert(Legal->getInductionVars()->count(P) &&
2856          "Not an induction variable");
2857
2858   LoopVectorizationLegality::InductionInfo II =
2859   Legal->getInductionVars()->lookup(P);
2860
2861   switch (II.IK) {
2862     case LoopVectorizationLegality::IK_NoInduction:
2863       llvm_unreachable("Unknown induction");
2864     case LoopVectorizationLegality::IK_IntInduction: {
2865       assert(P->getType() == II.StartValue->getType() && "Types must match");
2866       Type *PhiTy = P->getType();
2867       Value *Broadcasted;
2868       if (P == OldInduction) {
2869         // Handle the canonical induction variable. We might have had to
2870         // extend the type.
2871         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2872       } else {
2873         // Handle other induction variables that are now based on the
2874         // canonical one.
2875         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2876                                                  "normalized.idx");
2877         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2878         Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2879                                         "offset.idx");
2880       }
2881       Broadcasted = getBroadcastInstrs(Broadcasted);
2882       // After broadcasting the induction variable we need to make the vector
2883       // consecutive by adding 0, 1, 2, etc.
2884       for (unsigned part = 0; part < UF; ++part)
2885         Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2886       return;
2887     }
2888     case LoopVectorizationLegality::IK_ReverseIntInduction:
2889     case LoopVectorizationLegality::IK_PtrInduction:
2890     case LoopVectorizationLegality::IK_ReversePtrInduction:
2891       // Handle reverse integer and pointer inductions.
2892       Value *StartIdx = ExtendedIdx;
2893       // This is the normalized GEP that starts counting at zero.
2894       Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2895                                                "normalized.idx");
2896
2897       // Handle the reverse integer induction variable case.
2898       if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2899         IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2900         Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2901                                                "resize.norm.idx");
2902         Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
2903                                                "reverse.idx");
2904
2905         // This is a new value so do not hoist it out.
2906         Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2907         // After broadcasting the induction variable we need to make the
2908         // vector consecutive by adding  ... -3, -2, -1, 0.
2909         for (unsigned part = 0; part < UF; ++part)
2910           Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2911                                              true);
2912         return;
2913       }
2914
2915       // Handle the pointer induction variable case.
2916       assert(P->getType()->isPointerTy() && "Unexpected type.");
2917
2918       // Is this a reverse induction ptr or a consecutive induction ptr.
2919       bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2920                       II.IK);
2921
2922       // This is the vector of results. Notice that we don't generate
2923       // vector geps because scalar geps result in better code.
2924       for (unsigned part = 0; part < UF; ++part) {
2925         if (VF == 1) {
2926           int EltIndex = (part) * (Reverse ? -1 : 1);
2927           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2928           Value *GlobalIdx;
2929           if (Reverse)
2930             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2931           else
2932             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2933
2934           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2935                                              "next.gep");
2936           Entry[part] = SclrGep;
2937           continue;
2938         }
2939
2940         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2941         for (unsigned int i = 0; i < VF; ++i) {
2942           int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2943           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2944           Value *GlobalIdx;
2945           if (!Reverse)
2946             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2947           else
2948             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2949
2950           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2951                                              "next.gep");
2952           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2953                                                Builder.getInt32(i),
2954                                                "insert.gep");
2955         }
2956         Entry[part] = VecVal;
2957       }
2958       return;
2959   }
2960 }
2961
2962 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2963   // For each instruction in the old loop.
2964   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2965     VectorParts &Entry = WidenMap.get(it);
2966     switch (it->getOpcode()) {
2967     case Instruction::Br:
2968       // Nothing to do for PHIs and BR, since we already took care of the
2969       // loop control flow instructions.
2970       continue;
2971     case Instruction::PHI:{
2972       // Vectorize PHINodes.
2973       widenPHIInstruction(it, Entry, UF, VF, PV);
2974       continue;
2975     }// End of PHI.
2976
2977     case Instruction::Add:
2978     case Instruction::FAdd:
2979     case Instruction::Sub:
2980     case Instruction::FSub:
2981     case Instruction::Mul:
2982     case Instruction::FMul:
2983     case Instruction::UDiv:
2984     case Instruction::SDiv:
2985     case Instruction::FDiv:
2986     case Instruction::URem:
2987     case Instruction::SRem:
2988     case Instruction::FRem:
2989     case Instruction::Shl:
2990     case Instruction::LShr:
2991     case Instruction::AShr:
2992     case Instruction::And:
2993     case Instruction::Or:
2994     case Instruction::Xor: {
2995       // Just widen binops.
2996       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2997       setDebugLocFromInst(Builder, BinOp);
2998       VectorParts &A = getVectorValue(it->getOperand(0));
2999       VectorParts &B = getVectorValue(it->getOperand(1));
3000
3001       // Use this vector value for all users of the original instruction.
3002       for (unsigned Part = 0; Part < UF; ++Part) {
3003         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3004
3005         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
3006         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
3007         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
3008           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
3009           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
3010         }
3011         if (VecOp && isa<PossiblyExactOperator>(VecOp))
3012           VecOp->setIsExact(BinOp->isExact());
3013
3014         // Copy the fast-math flags.
3015         if (VecOp && isa<FPMathOperator>(V))
3016           VecOp->setFastMathFlags(it->getFastMathFlags());
3017
3018         Entry[Part] = V;
3019       }
3020       break;
3021     }
3022     case Instruction::Select: {
3023       // Widen selects.
3024       // If the selector is loop invariant we can create a select
3025       // instruction with a scalar condition. Otherwise, use vector-select.
3026       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3027                                                OrigLoop);
3028       setDebugLocFromInst(Builder, it);
3029
3030       // The condition can be loop invariant  but still defined inside the
3031       // loop. This means that we can't just use the original 'cond' value.
3032       // We have to take the 'vectorized' value and pick the first lane.
3033       // Instcombine will make this a no-op.
3034       VectorParts &Cond = getVectorValue(it->getOperand(0));
3035       VectorParts &Op0  = getVectorValue(it->getOperand(1));
3036       VectorParts &Op1  = getVectorValue(it->getOperand(2));
3037
3038       Value *ScalarCond = (VF == 1) ? Cond[0] :
3039         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3040
3041       for (unsigned Part = 0; Part < UF; ++Part) {
3042         Entry[Part] = Builder.CreateSelect(
3043           InvariantCond ? ScalarCond : Cond[Part],
3044           Op0[Part],
3045           Op1[Part]);
3046       }
3047       break;
3048     }
3049
3050     case Instruction::ICmp:
3051     case Instruction::FCmp: {
3052       // Widen compares. Generate vector compares.
3053       bool FCmp = (it->getOpcode() == Instruction::FCmp);
3054       CmpInst *Cmp = dyn_cast<CmpInst>(it);
3055       setDebugLocFromInst(Builder, it);
3056       VectorParts &A = getVectorValue(it->getOperand(0));
3057       VectorParts &B = getVectorValue(it->getOperand(1));
3058       for (unsigned Part = 0; Part < UF; ++Part) {
3059         Value *C = nullptr;
3060         if (FCmp)
3061           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3062         else
3063           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3064         Entry[Part] = C;
3065       }
3066       break;
3067     }
3068
3069     case Instruction::Store:
3070     case Instruction::Load:
3071       vectorizeMemoryInstruction(it);
3072         break;
3073     case Instruction::ZExt:
3074     case Instruction::SExt:
3075     case Instruction::FPToUI:
3076     case Instruction::FPToSI:
3077     case Instruction::FPExt:
3078     case Instruction::PtrToInt:
3079     case Instruction::IntToPtr:
3080     case Instruction::SIToFP:
3081     case Instruction::UIToFP:
3082     case Instruction::Trunc:
3083     case Instruction::FPTrunc:
3084     case Instruction::BitCast: {
3085       CastInst *CI = dyn_cast<CastInst>(it);
3086       setDebugLocFromInst(Builder, it);
3087       /// Optimize the special case where the source is the induction
3088       /// variable. Notice that we can only optimize the 'trunc' case
3089       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3090       /// c. other casts depend on pointer size.
3091       if (CI->getOperand(0) == OldInduction &&
3092           it->getOpcode() == Instruction::Trunc) {
3093         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3094                                                CI->getType());
3095         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3096         for (unsigned Part = 0; Part < UF; ++Part)
3097           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3098         break;
3099       }
3100       /// Vectorize casts.
3101       Type *DestTy = (VF == 1) ? CI->getType() :
3102                                  VectorType::get(CI->getType(), VF);
3103
3104       VectorParts &A = getVectorValue(it->getOperand(0));
3105       for (unsigned Part = 0; Part < UF; ++Part)
3106         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3107       break;
3108     }
3109
3110     case Instruction::Call: {
3111       // Ignore dbg intrinsics.
3112       if (isa<DbgInfoIntrinsic>(it))
3113         break;
3114       setDebugLocFromInst(Builder, it);
3115
3116       Module *M = BB->getParent()->getParent();
3117       CallInst *CI = cast<CallInst>(it);
3118       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3119       assert(ID && "Not an intrinsic call!");
3120       switch (ID) {
3121       case Intrinsic::lifetime_end:
3122       case Intrinsic::lifetime_start:
3123         scalarizeInstruction(it);
3124         break;
3125       default:
3126         for (unsigned Part = 0; Part < UF; ++Part) {
3127           SmallVector<Value *, 4> Args;
3128           for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3129             VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3130             Args.push_back(Arg[Part]);
3131           }
3132           Type *Tys[] = {CI->getType()};
3133           if (VF > 1)
3134             Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3135
3136           Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3137           Entry[Part] = Builder.CreateCall(F, Args);
3138         }
3139         break;
3140       }
3141       break;
3142     }
3143
3144     default:
3145       // All other instructions are unsupported. Scalarize them.
3146       scalarizeInstruction(it);
3147       break;
3148     }// end of switch.
3149   }// end of for_each instr.
3150 }
3151
3152 void InnerLoopVectorizer::updateAnalysis() {
3153   // Forget the original basic block.
3154   SE->forgetLoop(OrigLoop);
3155
3156   // Update the dominator tree information.
3157   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3158          "Entry does not dominate exit.");
3159
3160   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3161     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3162   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3163
3164   // Due to if predication of stores we might create a sequence of "if(pred)
3165   // a[i] = ...;  " blocks.
3166   for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3167     if (i == 0)
3168       DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3169     else if (isPredicatedBlock(i)) {
3170       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3171     } else {
3172       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3173     }
3174   }
3175
3176   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3177   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3178   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3179   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3180
3181   DEBUG(DT->verifyDomTree());
3182 }
3183
3184 /// \brief Check whether it is safe to if-convert this phi node.
3185 ///
3186 /// Phi nodes with constant expressions that can trap are not safe to if
3187 /// convert.
3188 static bool canIfConvertPHINodes(BasicBlock *BB) {
3189   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3190     PHINode *Phi = dyn_cast<PHINode>(I);
3191     if (!Phi)
3192       return true;
3193     for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3194       if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3195         if (C->canTrap())
3196           return false;
3197   }
3198   return true;
3199 }
3200
3201 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3202   if (!EnableIfConversion)
3203     return false;
3204
3205   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3206
3207   // A list of pointers that we can safely read and write to.
3208   SmallPtrSet<Value *, 8> SafePointes;
3209
3210   // Collect safe addresses.
3211   for (Loop::block_iterator BI = TheLoop->block_begin(),
3212          BE = TheLoop->block_end(); BI != BE; ++BI) {
3213     BasicBlock *BB = *BI;
3214
3215     if (blockNeedsPredication(BB))
3216       continue;
3217
3218     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3219       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3220         SafePointes.insert(LI->getPointerOperand());
3221       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3222         SafePointes.insert(SI->getPointerOperand());
3223     }
3224   }
3225
3226   // Collect the blocks that need predication.
3227   BasicBlock *Header = TheLoop->getHeader();
3228   for (Loop::block_iterator BI = TheLoop->block_begin(),
3229          BE = TheLoop->block_end(); BI != BE; ++BI) {
3230     BasicBlock *BB = *BI;
3231
3232     // We don't support switch statements inside loops.
3233     if (!isa<BranchInst>(BB->getTerminator()))
3234       return false;
3235
3236     // We must be able to predicate all blocks that need to be predicated.
3237     if (blockNeedsPredication(BB)) {
3238       if (!blockCanBePredicated(BB, SafePointes))
3239         return false;
3240     } else if (BB != Header && !canIfConvertPHINodes(BB))
3241       return false;
3242
3243   }
3244
3245   // We can if-convert this loop.
3246   return true;
3247 }
3248
3249 bool LoopVectorizationLegality::canVectorize() {
3250   // We must have a loop in canonical form. Loops with indirectbr in them cannot
3251   // be canonicalized.
3252   if (!TheLoop->getLoopPreheader())
3253     return false;
3254
3255   // We can only vectorize innermost loops.
3256   if (TheLoop->getSubLoopsVector().size())
3257     return false;
3258
3259   // We must have a single backedge.
3260   if (TheLoop->getNumBackEdges() != 1)
3261     return false;
3262
3263   // We must have a single exiting block.
3264   if (!TheLoop->getExitingBlock())
3265     return false;
3266
3267   // We need to have a loop header.
3268   DEBUG(dbgs() << "LV: Found a loop: " <<
3269         TheLoop->getHeader()->getName() << '\n');
3270
3271   // Check if we can if-convert non-single-bb loops.
3272   unsigned NumBlocks = TheLoop->getNumBlocks();
3273   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3274     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3275     return false;
3276   }
3277
3278   // ScalarEvolution needs to be able to find the exit count.
3279   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3280   if (ExitCount == SE->getCouldNotCompute()) {
3281     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3282     return false;
3283   }
3284
3285   // Check if we can vectorize the instructions and CFG in this loop.
3286   if (!canVectorizeInstrs()) {
3287     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3288     return false;
3289   }
3290
3291   // Go over each instruction and look at memory deps.
3292   if (!canVectorizeMemory()) {
3293     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3294     return false;
3295   }
3296
3297   // Collect all of the variables that remain uniform after vectorization.
3298   collectLoopUniforms();
3299
3300   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3301         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3302         <<"!\n");
3303
3304   // Okay! We can vectorize. At this point we don't have any other mem analysis
3305   // which may limit our maximum vectorization factor, so just return true with
3306   // no restrictions.
3307   return true;
3308 }
3309
3310 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3311   if (Ty->isPointerTy())
3312     return DL.getIntPtrType(Ty);
3313
3314   // It is possible that char's or short's overflow when we ask for the loop's
3315   // trip count, work around this by changing the type size.
3316   if (Ty->getScalarSizeInBits() < 32)
3317     return Type::getInt32Ty(Ty->getContext());
3318
3319   return Ty;
3320 }
3321
3322 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3323   Ty0 = convertPointerToIntegerType(DL, Ty0);
3324   Ty1 = convertPointerToIntegerType(DL, Ty1);
3325   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3326     return Ty0;
3327   return Ty1;
3328 }
3329
3330 /// \brief Check that the instruction has outside loop users and is not an
3331 /// identified reduction variable.
3332 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3333                                SmallPtrSet<Value *, 4> &Reductions) {
3334   // Reduction instructions are allowed to have exit users. All other
3335   // instructions must not have external users.
3336   if (!Reductions.count(Inst))
3337     //Check that all of the users of the loop are inside the BB.
3338     for (User *U : Inst->users()) {
3339       Instruction *UI = cast<Instruction>(U);
3340       // This user may be a reduction exit value.
3341       if (!TheLoop->contains(UI)) {
3342         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3343         return true;
3344       }
3345     }
3346   return false;
3347 }
3348
3349 bool LoopVectorizationLegality::canVectorizeInstrs() {
3350   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3351   BasicBlock *Header = TheLoop->getHeader();
3352
3353   // Look for the attribute signaling the absence of NaNs.
3354   Function &F = *Header->getParent();
3355   if (F.hasFnAttribute("no-nans-fp-math"))
3356     HasFunNoNaNAttr = F.getAttributes().getAttribute(
3357       AttributeSet::FunctionIndex,
3358       "no-nans-fp-math").getValueAsString() == "true";
3359
3360   // For each block in the loop.
3361   for (Loop::block_iterator bb = TheLoop->block_begin(),
3362        be = TheLoop->block_end(); bb != be; ++bb) {
3363
3364     // Scan the instructions in the block and look for hazards.
3365     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3366          ++it) {
3367
3368       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3369         Type *PhiTy = Phi->getType();
3370         // Check that this PHI type is allowed.
3371         if (!PhiTy->isIntegerTy() &&
3372             !PhiTy->isFloatingPointTy() &&
3373             !PhiTy->isPointerTy()) {
3374           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3375           return false;
3376         }
3377
3378         // If this PHINode is not in the header block, then we know that we
3379         // can convert it to select during if-conversion. No need to check if
3380         // the PHIs in this block are induction or reduction variables.
3381         if (*bb != Header) {
3382           // Check that this instruction has no outside users or is an
3383           // identified reduction value with an outside user.
3384           if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3385             continue;
3386           return false;
3387         }
3388
3389         // We only allow if-converted PHIs with more than two incoming values.
3390         if (Phi->getNumIncomingValues() != 2) {
3391           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3392           return false;
3393         }
3394
3395         // This is the value coming from the preheader.
3396         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3397         // Check if this is an induction variable.
3398         InductionKind IK = isInductionVariable(Phi);
3399
3400         if (IK_NoInduction != IK) {
3401           // Get the widest type.
3402           if (!WidestIndTy)
3403             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3404           else
3405             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3406
3407           // Int inductions are special because we only allow one IV.
3408           if (IK == IK_IntInduction) {
3409             // Use the phi node with the widest type as induction. Use the last
3410             // one if there are multiple (no good reason for doing this other
3411             // than it is expedient).
3412             if (!Induction || PhiTy == WidestIndTy)
3413               Induction = Phi;
3414           }
3415
3416           DEBUG(dbgs() << "LV: Found an induction variable.\n");
3417           Inductions[Phi] = InductionInfo(StartValue, IK);
3418
3419           // Until we explicitly handle the case of an induction variable with
3420           // an outside loop user we have to give up vectorizing this loop.
3421           if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3422             return false;
3423
3424           continue;
3425         }
3426
3427         if (AddReductionVar(Phi, RK_IntegerAdd)) {
3428           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3429           continue;
3430         }
3431         if (AddReductionVar(Phi, RK_IntegerMult)) {
3432           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3433           continue;
3434         }
3435         if (AddReductionVar(Phi, RK_IntegerOr)) {
3436           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3437           continue;
3438         }
3439         if (AddReductionVar(Phi, RK_IntegerAnd)) {
3440           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3441           continue;
3442         }
3443         if (AddReductionVar(Phi, RK_IntegerXor)) {
3444           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3445           continue;
3446         }
3447         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3448           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3449           continue;
3450         }
3451         if (AddReductionVar(Phi, RK_FloatMult)) {
3452           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3453           continue;
3454         }
3455         if (AddReductionVar(Phi, RK_FloatAdd)) {
3456           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3457           continue;
3458         }
3459         if (AddReductionVar(Phi, RK_FloatMinMax)) {
3460           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3461                 "\n");
3462           continue;
3463         }
3464
3465         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3466         return false;
3467       }// end of PHI handling
3468
3469       // We still don't handle functions. However, we can ignore dbg intrinsic
3470       // calls and we do handle certain intrinsic and libm functions.
3471       CallInst *CI = dyn_cast<CallInst>(it);
3472       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3473         DEBUG(dbgs() << "LV: Found a call site.\n");
3474         return false;
3475       }
3476
3477       // Check that the instruction return type is vectorizable.
3478       // Also, we can't vectorize extractelement instructions.
3479       if ((!VectorType::isValidElementType(it->getType()) &&
3480            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3481         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3482         return false;
3483       }
3484
3485       // Check that the stored type is vectorizable.
3486       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3487         Type *T = ST->getValueOperand()->getType();
3488         if (!VectorType::isValidElementType(T))
3489           return false;
3490         if (EnableMemAccessVersioning)
3491           collectStridedAcccess(ST);
3492       }
3493
3494       if (EnableMemAccessVersioning)
3495         if (LoadInst *LI = dyn_cast<LoadInst>(it))
3496           collectStridedAcccess(LI);
3497
3498       // Reduction instructions are allowed to have exit users.
3499       // All other instructions must not have external users.
3500       if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3501         return false;
3502
3503     } // next instr.
3504
3505   }
3506
3507   if (!Induction) {
3508     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3509     if (Inductions.empty())
3510       return false;
3511   }
3512
3513   return true;
3514 }
3515
3516 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3517 /// return the induction operand of the gep pointer.
3518 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3519                                  const DataLayout *DL, Loop *Lp) {
3520   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3521   if (!GEP)
3522     return Ptr;
3523
3524   unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3525
3526   // Check that all of the gep indices are uniform except for our induction
3527   // operand.
3528   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3529     if (i != InductionOperand &&
3530         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3531       return Ptr;
3532   return GEP->getOperand(InductionOperand);
3533 }
3534
3535 ///\brief Look for a cast use of the passed value.
3536 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3537   Value *UniqueCast = nullptr;
3538   for (User *U : Ptr->users()) {
3539     CastInst *CI = dyn_cast<CastInst>(U);
3540     if (CI && CI->getType() == Ty) {
3541       if (!UniqueCast)
3542         UniqueCast = CI;
3543       else
3544         return nullptr;
3545     }
3546   }
3547   return UniqueCast;
3548 }
3549
3550 ///\brief Get the stride of a pointer access in a loop.
3551 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3552 /// pointer to the Value, or null otherwise.
3553 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3554                                    const DataLayout *DL, Loop *Lp) {
3555   const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3556   if (!PtrTy || PtrTy->isAggregateType())
3557     return nullptr;
3558
3559   // Try to remove a gep instruction to make the pointer (actually index at this
3560   // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3561   // pointer, otherwise, we are analyzing the index.
3562   Value *OrigPtr = Ptr;
3563
3564   // The size of the pointer access.
3565   int64_t PtrAccessSize = 1;
3566
3567   Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3568   const SCEV *V = SE->getSCEV(Ptr);
3569
3570   if (Ptr != OrigPtr)
3571     // Strip off casts.
3572     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3573       V = C->getOperand();
3574
3575   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3576   if (!S)
3577     return nullptr;
3578
3579   V = S->getStepRecurrence(*SE);
3580   if (!V)
3581     return nullptr;
3582
3583   // Strip off the size of access multiplication if we are still analyzing the
3584   // pointer.
3585   if (OrigPtr == Ptr) {
3586     DL->getTypeAllocSize(PtrTy->getElementType());
3587     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3588       if (M->getOperand(0)->getSCEVType() != scConstant)
3589         return nullptr;
3590
3591       const APInt &APStepVal =
3592           cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3593
3594       // Huge step value - give up.
3595       if (APStepVal.getBitWidth() > 64)
3596         return nullptr;
3597
3598       int64_t StepVal = APStepVal.getSExtValue();
3599       if (PtrAccessSize != StepVal)
3600         return nullptr;
3601       V = M->getOperand(1);
3602     }
3603   }
3604
3605   // Strip off casts.
3606   Type *StripedOffRecurrenceCast = nullptr;
3607   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3608     StripedOffRecurrenceCast = C->getType();
3609     V = C->getOperand();
3610   }
3611
3612   // Look for the loop invariant symbolic value.
3613   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3614   if (!U)
3615     return nullptr;
3616
3617   Value *Stride = U->getValue();
3618   if (!Lp->isLoopInvariant(Stride))
3619     return nullptr;
3620
3621   // If we have stripped off the recurrence cast we have to make sure that we
3622   // return the value that is used in this loop so that we can replace it later.
3623   if (StripedOffRecurrenceCast)
3624     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3625
3626   return Stride;
3627 }
3628
3629 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3630   Value *Ptr = nullptr;
3631   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3632     Ptr = LI->getPointerOperand();
3633   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3634     Ptr = SI->getPointerOperand();
3635   else
3636     return;
3637
3638   Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3639   if (!Stride)
3640     return;
3641
3642   DEBUG(dbgs() << "LV: Found a strided access that we can version");
3643   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3644   Strides[Ptr] = Stride;
3645   StrideSet.insert(Stride);
3646 }
3647
3648 void LoopVectorizationLegality::collectLoopUniforms() {
3649   // We now know that the loop is vectorizable!
3650   // Collect variables that will remain uniform after vectorization.
3651   std::vector<Value*> Worklist;
3652   BasicBlock *Latch = TheLoop->getLoopLatch();
3653
3654   // Start with the conditional branch and walk up the block.
3655   Worklist.push_back(Latch->getTerminator()->getOperand(0));
3656
3657   // Also add all consecutive pointer values; these values will be uniform
3658   // after vectorization (and subsequent cleanup) and, until revectorization is
3659   // supported, all dependencies must also be uniform.
3660   for (Loop::block_iterator B = TheLoop->block_begin(),
3661        BE = TheLoop->block_end(); B != BE; ++B)
3662     for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3663          I != IE; ++I)
3664       if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3665         Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3666
3667   while (Worklist.size()) {
3668     Instruction *I = dyn_cast<Instruction>(Worklist.back());
3669     Worklist.pop_back();
3670
3671     // Look at instructions inside this loop.
3672     // Stop when reaching PHI nodes.
3673     // TODO: we need to follow values all over the loop, not only in this block.
3674     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3675       continue;
3676
3677     // This is a known uniform.
3678     Uniforms.insert(I);
3679
3680     // Insert all operands.
3681     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3682   }
3683 }
3684
3685 namespace {
3686 /// \brief Analyses memory accesses in a loop.
3687 ///
3688 /// Checks whether run time pointer checks are needed and builds sets for data
3689 /// dependence checking.
3690 class AccessAnalysis {
3691 public:
3692   /// \brief Read or write access location.
3693   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3694   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3695
3696   /// \brief Set of potential dependent memory accesses.
3697   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3698
3699   AccessAnalysis(const DataLayout *Dl, DepCandidates &DA) :
3700     DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3701     AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3702
3703   /// \brief Register a load  and whether it is only read from.
3704   void addLoad(Value *Ptr, bool IsReadOnly) {
3705     Accesses.insert(MemAccessInfo(Ptr, false));
3706     if (IsReadOnly)
3707       ReadOnlyPtr.insert(Ptr);
3708   }
3709
3710   /// \brief Register a store.
3711   void addStore(Value *Ptr) {
3712     Accesses.insert(MemAccessInfo(Ptr, true));
3713   }
3714
3715   /// \brief Check whether we can check the pointers at runtime for
3716   /// non-intersection.
3717   bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3718                        unsigned &NumComparisons, ScalarEvolution *SE,
3719                        Loop *TheLoop, ValueToValueMap &Strides,
3720                        bool ShouldCheckStride = false);
3721
3722   /// \brief Goes over all memory accesses, checks whether a RT check is needed
3723   /// and builds sets of dependent accesses.
3724   void buildDependenceSets() {
3725     // Process read-write pointers first.
3726     processMemAccesses(false);
3727     // Next, process read pointers.
3728     processMemAccesses(true);
3729   }
3730
3731   bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3732
3733   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3734   void resetDepChecks() { CheckDeps.clear(); }
3735
3736   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3737
3738 private:
3739   typedef SetVector<MemAccessInfo> PtrAccessSet;
3740   typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3741
3742   /// \brief Go over all memory access or only the deferred ones if
3743   /// \p UseDeferred is true and check whether runtime pointer checks are needed
3744   /// and build sets of dependency check candidates.
3745   void processMemAccesses(bool UseDeferred);
3746
3747   /// Set of all accesses.
3748   PtrAccessSet Accesses;
3749
3750   /// Set of access to check after all writes have been processed.
3751   PtrAccessSet DeferredAccesses;
3752
3753   /// Map of pointers to last access encountered.
3754   UnderlyingObjToAccessMap ObjToLastAccess;
3755
3756   /// Set of accesses that need a further dependence check.
3757   MemAccessInfoSet CheckDeps;
3758
3759   /// Set of pointers that are read only.
3760   SmallPtrSet<Value*, 16> ReadOnlyPtr;
3761
3762   /// Set of underlying objects already written to.
3763   SmallPtrSet<Value*, 16> WriteObjects;
3764
3765   const DataLayout *DL;
3766
3767   /// Sets of potentially dependent accesses - members of one set share an
3768   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3769   /// dependence check.
3770   DepCandidates &DepCands;
3771
3772   bool AreAllWritesIdentified;
3773   bool AreAllReadsIdentified;
3774   bool IsRTCheckNeeded;
3775 };
3776
3777 } // end anonymous namespace
3778
3779 /// \brief Check whether a pointer can participate in a runtime bounds check.
3780 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3781                                 Value *Ptr) {
3782   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3783   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3784   if (!AR)
3785     return false;
3786
3787   return AR->isAffine();
3788 }
3789
3790 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3791 /// the address space.
3792 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
3793                         const Loop *Lp, ValueToValueMap &StridesMap);
3794
3795 bool AccessAnalysis::canCheckPtrAtRT(
3796     LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3797     unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3798     ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3799   // Find pointers with computable bounds. We are going to use this information
3800   // to place a runtime bound check.
3801   unsigned NumReadPtrChecks = 0;
3802   unsigned NumWritePtrChecks = 0;
3803   bool CanDoRT = true;
3804
3805   bool IsDepCheckNeeded = isDependencyCheckNeeded();
3806   // We assign consecutive id to access from different dependence sets.
3807   // Accesses within the same set don't need a runtime check.
3808   unsigned RunningDepId = 1;
3809   DenseMap<Value *, unsigned> DepSetId;
3810
3811   for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3812        AI != AE; ++AI) {
3813     const MemAccessInfo &Access = *AI;
3814     Value *Ptr = Access.getPointer();
3815     bool IsWrite = Access.getInt();
3816
3817     // Just add write checks if we have both.
3818     if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3819       continue;
3820
3821     if (IsWrite)
3822       ++NumWritePtrChecks;
3823     else
3824       ++NumReadPtrChecks;
3825
3826     if (hasComputableBounds(SE, StridesMap, Ptr) &&
3827         // When we run after a failing dependency check we have to make sure we
3828         // don't have wrapping pointers.
3829         (!ShouldCheckStride ||
3830          isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3831       // The id of the dependence set.
3832       unsigned DepId;
3833
3834       if (IsDepCheckNeeded) {
3835         Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3836         unsigned &LeaderId = DepSetId[Leader];
3837         if (!LeaderId)
3838           LeaderId = RunningDepId++;
3839         DepId = LeaderId;
3840       } else
3841         // Each access has its own dependence set.
3842         DepId = RunningDepId++;
3843
3844       RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3845
3846       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3847     } else {
3848       CanDoRT = false;
3849     }
3850   }
3851
3852   if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3853     NumComparisons = 0; // Only one dependence set.
3854   else {
3855     NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3856                                            NumWritePtrChecks - 1));
3857   }
3858
3859   // If the pointers that we would use for the bounds comparison have different
3860   // address spaces, assume the values aren't directly comparable, so we can't
3861   // use them for the runtime check. We also have to assume they could
3862   // overlap. In the future there should be metadata for whether address spaces
3863   // are disjoint.
3864   unsigned NumPointers = RtCheck.Pointers.size();
3865   for (unsigned i = 0; i < NumPointers; ++i) {
3866     for (unsigned j = i + 1; j < NumPointers; ++j) {
3867       // Only need to check pointers between two different dependency sets.
3868       if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3869        continue;
3870
3871       Value *PtrI = RtCheck.Pointers[i];
3872       Value *PtrJ = RtCheck.Pointers[j];
3873
3874       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3875       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3876       if (ASi != ASj) {
3877         DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3878                        " different address spaces\n");
3879         return false;
3880       }
3881     }
3882   }
3883
3884   return CanDoRT;
3885 }
3886
3887 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3888   return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3889 }
3890
3891 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3892   // We process the set twice: first we process read-write pointers, last we
3893   // process read-only pointers. This allows us to skip dependence tests for
3894   // read-only pointers.
3895
3896   PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3897   for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3898     const MemAccessInfo &Access = *AI;
3899     Value *Ptr = Access.getPointer();
3900     bool IsWrite = Access.getInt();
3901
3902     DepCands.insert(Access);
3903
3904     // Memorize read-only pointers for later processing and skip them in the
3905     // first round (they need to be checked after we have seen all write
3906     // pointers). Note: we also mark pointer that are not consecutive as
3907     // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3908     // second check for "!IsWrite".
3909     bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3910     if (!UseDeferred && IsReadOnlyPtr) {
3911       DeferredAccesses.insert(Access);
3912       continue;
3913     }
3914
3915     bool NeedDepCheck = false;
3916     // Check whether there is the possibility of dependency because of
3917     // underlying objects being the same.
3918     typedef SmallVector<Value*, 16> ValueVector;
3919     ValueVector TempObjects;
3920     GetUnderlyingObjects(Ptr, TempObjects, DL);
3921     for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3922          UI != UE; ++UI) {
3923       Value *UnderlyingObj = *UI;
3924
3925       // If this is a write then it needs to be an identified object.  If this a
3926       // read and all writes (so far) are identified function scope objects we
3927       // don't need an identified underlying object but only an Argument (the
3928       // next write is going to invalidate this assumption if it is
3929       // unidentified).
3930       // This is a micro-optimization for the case where all writes are
3931       // identified and we have one argument pointer.
3932       // Otherwise, we do need a runtime check.
3933       if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3934           (!IsWrite && (!AreAllWritesIdentified ||
3935                         !isa<Argument>(UnderlyingObj)) &&
3936            !isIdentifiedObject(UnderlyingObj))) {
3937         DEBUG(dbgs() << "LV: Found an unidentified " <<
3938               (IsWrite ?  "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3939               "\n");
3940         IsRTCheckNeeded = (IsRTCheckNeeded ||
3941                            !isIdentifiedObject(UnderlyingObj) ||
3942                            !AreAllReadsIdentified);
3943
3944         if (IsWrite)
3945           AreAllWritesIdentified = false;
3946         if (!IsWrite)
3947           AreAllReadsIdentified = false;
3948       }
3949
3950       // If this is a write - check other reads and writes for conflicts.  If
3951       // this is a read only check other writes for conflicts (but only if there
3952       // is no other write to the ptr - this is an optimization to catch "a[i] =
3953       // a[i] + " without having to do a dependence check).
3954       if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3955         NeedDepCheck = true;
3956
3957       if (IsWrite)
3958         WriteObjects.insert(UnderlyingObj);
3959
3960       // Create sets of pointers connected by shared underlying objects.
3961       UnderlyingObjToAccessMap::iterator Prev =
3962         ObjToLastAccess.find(UnderlyingObj);
3963       if (Prev != ObjToLastAccess.end())
3964         DepCands.unionSets(Access, Prev->second);
3965
3966       ObjToLastAccess[UnderlyingObj] = Access;
3967     }
3968
3969     if (NeedDepCheck)
3970       CheckDeps.insert(Access);
3971   }
3972 }
3973
3974 namespace {
3975 /// \brief Checks memory dependences among accesses to the same underlying
3976 /// object to determine whether there vectorization is legal or not (and at
3977 /// which vectorization factor).
3978 ///
3979 /// This class works under the assumption that we already checked that memory
3980 /// locations with different underlying pointers are "must-not alias".
3981 /// We use the ScalarEvolution framework to symbolically evalutate access
3982 /// functions pairs. Since we currently don't restructure the loop we can rely
3983 /// on the program order of memory accesses to determine their safety.
3984 /// At the moment we will only deem accesses as safe for:
3985 ///  * A negative constant distance assuming program order.
3986 ///
3987 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
3988 ///            a[i] = tmp;                y = a[i];
3989 ///
3990 ///   The latter case is safe because later checks guarantuee that there can't
3991 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
3992 ///   the same variable: a header phi can only be an induction or a reduction, a
3993 ///   reduction can't have a memory sink, an induction can't have a memory
3994 ///   source). This is important and must not be violated (or we have to
3995 ///   resort to checking for cycles through memory).
3996 ///
3997 ///  * A positive constant distance assuming program order that is bigger
3998 ///    than the biggest memory access.
3999 ///
4000 ///     tmp = a[i]        OR              b[i] = x
4001 ///     a[i+2] = tmp                      y = b[i+2];
4002 ///
4003 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
4004 ///
4005 ///  * Zero distances and all accesses have the same size.
4006 ///
4007 class MemoryDepChecker {
4008 public:
4009   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4010   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4011
4012   MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
4013       : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
4014         ShouldRetryWithRuntimeCheck(false) {}
4015
4016   /// \brief Register the location (instructions are given increasing numbers)
4017   /// of a write access.
4018   void addAccess(StoreInst *SI) {
4019     Value *Ptr = SI->getPointerOperand();
4020     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
4021     InstMap.push_back(SI);
4022     ++AccessIdx;
4023   }
4024
4025   /// \brief Register the location (instructions are given increasing numbers)
4026   /// of a write access.
4027   void addAccess(LoadInst *LI) {
4028     Value *Ptr = LI->getPointerOperand();
4029     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4030     InstMap.push_back(LI);
4031     ++AccessIdx;
4032   }
4033
4034   /// \brief Check whether the dependencies between the accesses are safe.
4035   ///
4036   /// Only checks sets with elements in \p CheckDeps.
4037   bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4038                    MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4039
4040   /// \brief The maximum number of bytes of a vector register we can vectorize
4041   /// the accesses safely with.
4042   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4043
4044   /// \brief In same cases when the dependency check fails we can still
4045   /// vectorize the loop with a dynamic array access check.
4046   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4047
4048 private:
4049   ScalarEvolution *SE;
4050   const DataLayout *DL;
4051   const Loop *InnermostLoop;
4052
4053   /// \brief Maps access locations (ptr, read/write) to program order.
4054   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4055
4056   /// \brief Memory access instructions in program order.
4057   SmallVector<Instruction *, 16> InstMap;
4058
4059   /// \brief The program order index to be used for the next instruction.
4060   unsigned AccessIdx;
4061
4062   // We can access this many bytes in parallel safely.
4063   unsigned MaxSafeDepDistBytes;
4064
4065   /// \brief If we see a non-constant dependence distance we can still try to
4066   /// vectorize this loop with runtime checks.
4067   bool ShouldRetryWithRuntimeCheck;
4068
4069   /// \brief Check whether there is a plausible dependence between the two
4070   /// accesses.
4071   ///
4072   /// Access \p A must happen before \p B in program order. The two indices
4073   /// identify the index into the program order map.
4074   ///
4075   /// This function checks  whether there is a plausible dependence (or the
4076   /// absence of such can't be proved) between the two accesses. If there is a
4077   /// plausible dependence but the dependence distance is bigger than one
4078   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4079   /// distance is smaller than any other distance encountered so far).
4080   /// Otherwise, this function returns true signaling a possible dependence.
4081   bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4082                    const MemAccessInfo &B, unsigned BIdx,
4083                    ValueToValueMap &Strides);
4084
4085   /// \brief Check whether the data dependence could prevent store-load
4086   /// forwarding.
4087   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4088 };
4089
4090 } // end anonymous namespace
4091
4092 static bool isInBoundsGep(Value *Ptr) {
4093   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4094     return GEP->isInBounds();
4095   return false;
4096 }
4097
4098 /// \brief Check whether the access through \p Ptr has a constant stride.
4099 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4100                         const Loop *Lp, ValueToValueMap &StridesMap) {
4101   const Type *Ty = Ptr->getType();
4102   assert(Ty->isPointerTy() && "Unexpected non-ptr");
4103
4104   // Make sure that the pointer does not point to aggregate types.
4105   const PointerType *PtrTy = cast<PointerType>(Ty);
4106   if (PtrTy->getElementType()->isAggregateType()) {
4107     DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4108           "\n");
4109     return 0;
4110   }
4111
4112   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4113
4114   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4115   if (!AR) {
4116     DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4117           << *Ptr << " SCEV: " << *PtrScev << "\n");
4118     return 0;
4119   }
4120
4121   // The accesss function must stride over the innermost loop.
4122   if (Lp != AR->getLoop()) {
4123     DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4124           *Ptr << " SCEV: " << *PtrScev << "\n");
4125   }
4126
4127   // The address calculation must not wrap. Otherwise, a dependence could be
4128   // inverted.
4129   // An inbounds getelementptr that is a AddRec with a unit stride
4130   // cannot wrap per definition. The unit stride requirement is checked later.
4131   // An getelementptr without an inbounds attribute and unit stride would have
4132   // to access the pointer value "0" which is undefined behavior in address
4133   // space 0, therefore we can also vectorize this case.
4134   bool IsInBoundsGEP = isInBoundsGep(Ptr);
4135   bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4136   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4137   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4138     DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4139           << *Ptr << " SCEV: " << *PtrScev << "\n");
4140     return 0;
4141   }
4142
4143   // Check the step is constant.
4144   const SCEV *Step = AR->getStepRecurrence(*SE);
4145
4146   // Calculate the pointer stride and check if it is consecutive.
4147   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4148   if (!C) {
4149     DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4150           " SCEV: " << *PtrScev << "\n");
4151     return 0;
4152   }
4153
4154   int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4155   const APInt &APStepVal = C->getValue()->getValue();
4156
4157   // Huge step value - give up.
4158   if (APStepVal.getBitWidth() > 64)
4159     return 0;
4160
4161   int64_t StepVal = APStepVal.getSExtValue();
4162
4163   // Strided access.
4164   int64_t Stride = StepVal / Size;
4165   int64_t Rem = StepVal % Size;
4166   if (Rem)
4167     return 0;
4168
4169   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4170   // know we can't "wrap around the address space". In case of address space
4171   // zero we know that this won't happen without triggering undefined behavior.
4172   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4173       Stride != 1 && Stride != -1)
4174     return 0;
4175
4176   return Stride;
4177 }
4178
4179 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4180                                                     unsigned TypeByteSize) {
4181   // If loads occur at a distance that is not a multiple of a feasible vector
4182   // factor store-load forwarding does not take place.
4183   // Positive dependences might cause troubles because vectorizing them might
4184   // prevent store-load forwarding making vectorized code run a lot slower.
4185   //   a[i] = a[i-3] ^ a[i-8];
4186   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4187   //   hence on your typical architecture store-load forwarding does not take
4188   //   place. Vectorizing in such cases does not make sense.
4189   // Store-load forwarding distance.
4190   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4191   // Maximum vector factor.
4192   unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4193   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4194     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4195
4196   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4197        vf *= 2) {
4198     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4199       MaxVFWithoutSLForwardIssues = (vf >>=1);
4200       break;
4201     }
4202   }
4203
4204   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4205     DEBUG(dbgs() << "LV: Distance " << Distance <<
4206           " that could cause a store-load forwarding conflict\n");
4207     return true;
4208   }
4209
4210   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4211       MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4212     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4213   return false;
4214 }
4215
4216 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4217                                    const MemAccessInfo &B, unsigned BIdx,
4218                                    ValueToValueMap &Strides) {
4219   assert (AIdx < BIdx && "Must pass arguments in program order");
4220
4221   Value *APtr = A.getPointer();
4222   Value *BPtr = B.getPointer();
4223   bool AIsWrite = A.getInt();
4224   bool BIsWrite = B.getInt();
4225
4226   // Two reads are independent.
4227   if (!AIsWrite && !BIsWrite)
4228     return false;
4229
4230   const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4231   const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4232
4233   int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4234   int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4235
4236   const SCEV *Src = AScev;
4237   const SCEV *Sink = BScev;
4238
4239   // If the induction step is negative we have to invert source and sink of the
4240   // dependence.
4241   if (StrideAPtr < 0) {
4242     //Src = BScev;
4243     //Sink = AScev;
4244     std::swap(APtr, BPtr);
4245     std::swap(Src, Sink);
4246     std::swap(AIsWrite, BIsWrite);
4247     std::swap(AIdx, BIdx);
4248     std::swap(StrideAPtr, StrideBPtr);
4249   }
4250
4251   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4252
4253   DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4254         << "(Induction step: " << StrideAPtr <<  ")\n");
4255   DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4256         << *InstMap[BIdx] << ": " << *Dist << "\n");
4257
4258   // Need consecutive accesses. We don't want to vectorize
4259   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4260   // the address space.
4261   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4262     DEBUG(dbgs() << "Non-consecutive pointer access\n");
4263     return true;
4264   }
4265
4266   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4267   if (!C) {
4268     DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4269     ShouldRetryWithRuntimeCheck = true;
4270     return true;
4271   }
4272
4273   Type *ATy = APtr->getType()->getPointerElementType();
4274   Type *BTy = BPtr->getType()->getPointerElementType();
4275   unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4276
4277   // Negative distances are not plausible dependencies.
4278   const APInt &Val = C->getValue()->getValue();
4279   if (Val.isNegative()) {
4280     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4281     if (IsTrueDataDependence &&
4282         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4283          ATy != BTy))
4284       return true;
4285
4286     DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4287     return false;
4288   }
4289
4290   // Write to the same location with the same size.
4291   // Could be improved to assert type sizes are the same (i32 == float, etc).
4292   if (Val == 0) {
4293     if (ATy == BTy)
4294       return false;
4295     DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4296     return true;
4297   }
4298
4299   assert(Val.isStrictlyPositive() && "Expect a positive value");
4300
4301   // Positive distance bigger than max vectorization factor.
4302   if (ATy != BTy) {
4303     DEBUG(dbgs() <<
4304           "LV: ReadWrite-Write positive dependency with different types\n");
4305     return false;
4306   }
4307
4308   unsigned Distance = (unsigned) Val.getZExtValue();
4309
4310   // Bail out early if passed-in parameters make vectorization not feasible.
4311   unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4312   unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4313
4314   // The distance must be bigger than the size needed for a vectorized version
4315   // of the operation and the size of the vectorized operation must not be
4316   // bigger than the currrent maximum size.
4317   if (Distance < 2*TypeByteSize ||
4318       2*TypeByteSize > MaxSafeDepDistBytes ||
4319       Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4320     DEBUG(dbgs() << "LV: Failure because of Positive distance "
4321         << Val.getSExtValue() << '\n');
4322     return true;
4323   }
4324
4325   MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4326     Distance : MaxSafeDepDistBytes;
4327
4328   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4329   if (IsTrueDataDependence &&
4330       couldPreventStoreLoadForward(Distance, TypeByteSize))
4331      return true;
4332
4333   DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4334         " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4335
4336   return false;
4337 }
4338
4339 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4340                                    MemAccessInfoSet &CheckDeps,
4341                                    ValueToValueMap &Strides) {
4342
4343   MaxSafeDepDistBytes = -1U;
4344   while (!CheckDeps.empty()) {
4345     MemAccessInfo CurAccess = *CheckDeps.begin();
4346
4347     // Get the relevant memory access set.
4348     EquivalenceClasses<MemAccessInfo>::iterator I =
4349       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4350
4351     // Check accesses within this set.
4352     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4353     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4354
4355     // Check every access pair.
4356     while (AI != AE) {
4357       CheckDeps.erase(*AI);
4358       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4359       while (OI != AE) {
4360         // Check every accessing instruction pair in program order.
4361         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4362              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4363           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4364                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4365             if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4366               return false;
4367             if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4368               return false;
4369           }
4370         ++OI;
4371       }
4372       AI++;
4373     }
4374   }
4375   return true;
4376 }
4377
4378 bool LoopVectorizationLegality::canVectorizeMemory() {
4379
4380   typedef SmallVector<Value*, 16> ValueVector;
4381   typedef SmallPtrSet<Value*, 16> ValueSet;
4382
4383   // Holds the Load and Store *instructions*.
4384   ValueVector Loads;
4385   ValueVector Stores;
4386
4387   // Holds all the different accesses in the loop.
4388   unsigned NumReads = 0;
4389   unsigned NumReadWrites = 0;
4390
4391   PtrRtCheck.Pointers.clear();
4392   PtrRtCheck.Need = false;
4393
4394   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4395   MemoryDepChecker DepChecker(SE, DL, TheLoop);
4396
4397   // For each block.
4398   for (Loop::block_iterator bb = TheLoop->block_begin(),
4399        be = TheLoop->block_end(); bb != be; ++bb) {
4400
4401     // Scan the BB and collect legal loads and stores.
4402     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4403          ++it) {
4404
4405       // If this is a load, save it. If this instruction can read from memory
4406       // but is not a load, then we quit. Notice that we don't handle function
4407       // calls that read or write.
4408       if (it->mayReadFromMemory()) {
4409         // Many math library functions read the rounding mode. We will only
4410         // vectorize a loop if it contains known function calls that don't set
4411         // the flag. Therefore, it is safe to ignore this read from memory.
4412         CallInst *Call = dyn_cast<CallInst>(it);
4413         if (Call && getIntrinsicIDForCall(Call, TLI))
4414           continue;
4415
4416         LoadInst *Ld = dyn_cast<LoadInst>(it);
4417         if (!Ld) return false;
4418         if (!Ld->isSimple() && !IsAnnotatedParallel) {
4419           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4420           return false;
4421         }
4422         NumLoads++;
4423         Loads.push_back(Ld);
4424         DepChecker.addAccess(Ld);
4425         continue;
4426       }
4427
4428       // Save 'store' instructions. Abort if other instructions write to memory.
4429       if (it->mayWriteToMemory()) {
4430         StoreInst *St = dyn_cast<StoreInst>(it);
4431         if (!St) return false;
4432         if (!St->isSimple() && !IsAnnotatedParallel) {
4433           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4434           return false;
4435         }
4436         NumStores++;
4437         Stores.push_back(St);
4438         DepChecker.addAccess(St);
4439       }
4440     } // Next instr.
4441   } // Next block.
4442
4443   // Now we have two lists that hold the loads and the stores.
4444   // Next, we find the pointers that they use.
4445
4446   // Check if we see any stores. If there are no stores, then we don't
4447   // care if the pointers are *restrict*.
4448   if (!Stores.size()) {
4449     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4450     return true;
4451   }
4452
4453   AccessAnalysis::DepCandidates DependentAccesses;
4454   AccessAnalysis Accesses(DL, DependentAccesses);
4455
4456   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4457   // multiple times on the same object. If the ptr is accessed twice, once
4458   // for read and once for write, it will only appear once (on the write
4459   // list). This is okay, since we are going to check for conflicts between
4460   // writes and between reads and writes, but not between reads and reads.
4461   ValueSet Seen;
4462
4463   ValueVector::iterator I, IE;
4464   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4465     StoreInst *ST = cast<StoreInst>(*I);
4466     Value* Ptr = ST->getPointerOperand();
4467
4468     if (isUniform(Ptr)) {
4469       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4470       return false;
4471     }
4472
4473     // If we did *not* see this pointer before, insert it to  the read-write
4474     // list. At this phase it is only a 'write' list.
4475     if (Seen.insert(Ptr)) {
4476       ++NumReadWrites;
4477       Accesses.addStore(Ptr);
4478     }
4479   }
4480
4481   if (IsAnnotatedParallel) {
4482     DEBUG(dbgs()
4483           << "LV: A loop annotated parallel, ignore memory dependency "
4484           << "checks.\n");
4485     return true;
4486   }
4487
4488   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4489     LoadInst *LD = cast<LoadInst>(*I);
4490     Value* Ptr = LD->getPointerOperand();
4491     // If we did *not* see this pointer before, insert it to the
4492     // read list. If we *did* see it before, then it is already in
4493     // the read-write list. This allows us to vectorize expressions
4494     // such as A[i] += x;  Because the address of A[i] is a read-write
4495     // pointer. This only works if the index of A[i] is consecutive.
4496     // If the address of i is unknown (for example A[B[i]]) then we may
4497     // read a few words, modify, and write a few words, and some of the
4498     // words may be written to the same address.
4499     bool IsReadOnlyPtr = false;
4500     if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4501       ++NumReads;
4502       IsReadOnlyPtr = true;
4503     }
4504     Accesses.addLoad(Ptr, IsReadOnlyPtr);
4505   }
4506
4507   // If we write (or read-write) to a single destination and there are no
4508   // other reads in this loop then is it safe to vectorize.
4509   if (NumReadWrites == 1 && NumReads == 0) {
4510     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4511     return true;
4512   }
4513
4514   // Build dependence sets and check whether we need a runtime pointer bounds
4515   // check.
4516   Accesses.buildDependenceSets();
4517   bool NeedRTCheck = Accesses.isRTCheckNeeded();
4518
4519   // Find pointers with computable bounds. We are going to use this information
4520   // to place a runtime bound check.
4521   unsigned NumComparisons = 0;
4522   bool CanDoRT = false;
4523   if (NeedRTCheck)
4524     CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4525                                        Strides);
4526
4527   DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4528         " pointer comparisons.\n");
4529
4530   // If we only have one set of dependences to check pointers among we don't
4531   // need a runtime check.
4532   if (NumComparisons == 0 && NeedRTCheck)
4533     NeedRTCheck = false;
4534
4535   // Check that we did not collect too many pointers or found an unsizeable
4536   // pointer.
4537   if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4538     PtrRtCheck.reset();
4539     CanDoRT = false;
4540   }
4541
4542   if (CanDoRT) {
4543     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4544   }
4545
4546   if (NeedRTCheck && !CanDoRT) {
4547     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4548           "the array bounds.\n");
4549     PtrRtCheck.reset();
4550     return false;
4551   }
4552
4553   PtrRtCheck.Need = NeedRTCheck;
4554
4555   bool CanVecMem = true;
4556   if (Accesses.isDependencyCheckNeeded()) {
4557     DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4558     CanVecMem = DepChecker.areDepsSafe(
4559         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4560     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4561
4562     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4563       DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4564       NeedRTCheck = true;
4565
4566       // Clear the dependency checks. We assume they are not needed.
4567       Accesses.resetDepChecks();
4568
4569       PtrRtCheck.reset();
4570       PtrRtCheck.Need = true;
4571
4572       CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4573                                          TheLoop, Strides, true);
4574       // Check that we did not collect too many pointers or found an unsizeable
4575       // pointer.
4576       if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4577         DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4578         PtrRtCheck.reset();
4579         return false;
4580       }
4581
4582       CanVecMem = true;
4583     }
4584   }
4585
4586   DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4587         " need a runtime memory check.\n");
4588
4589   return CanVecMem;
4590 }
4591
4592 static bool hasMultipleUsesOf(Instruction *I,
4593                               SmallPtrSet<Instruction *, 8> &Insts) {
4594   unsigned NumUses = 0;
4595   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4596     if (Insts.count(dyn_cast<Instruction>(*Use)))
4597       ++NumUses;
4598     if (NumUses > 1)
4599       return true;
4600   }
4601
4602   return false;
4603 }
4604
4605 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4606   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4607     if (!Set.count(dyn_cast<Instruction>(*Use)))
4608       return false;
4609   return true;
4610 }
4611
4612 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4613                                                 ReductionKind Kind) {
4614   if (Phi->getNumIncomingValues() != 2)
4615     return false;
4616
4617   // Reduction variables are only found in the loop header block.
4618   if (Phi->getParent() != TheLoop->getHeader())
4619     return false;
4620
4621   // Obtain the reduction start value from the value that comes from the loop
4622   // preheader.
4623   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4624
4625   // ExitInstruction is the single value which is used outside the loop.
4626   // We only allow for a single reduction value to be used outside the loop.
4627   // This includes users of the reduction, variables (which form a cycle
4628   // which ends in the phi node).
4629   Instruction *ExitInstruction = nullptr;
4630   // Indicates that we found a reduction operation in our scan.
4631   bool FoundReduxOp = false;
4632
4633   // We start with the PHI node and scan for all of the users of this
4634   // instruction. All users must be instructions that can be used as reduction
4635   // variables (such as ADD). We must have a single out-of-block user. The cycle
4636   // must include the original PHI.
4637   bool FoundStartPHI = false;
4638
4639   // To recognize min/max patterns formed by a icmp select sequence, we store
4640   // the number of instruction we saw from the recognized min/max pattern,
4641   //  to make sure we only see exactly the two instructions.
4642   unsigned NumCmpSelectPatternInst = 0;
4643   ReductionInstDesc ReduxDesc(false, nullptr);
4644
4645   SmallPtrSet<Instruction *, 8> VisitedInsts;
4646   SmallVector<Instruction *, 8> Worklist;
4647   Worklist.push_back(Phi);
4648   VisitedInsts.insert(Phi);
4649
4650   // A value in the reduction can be used:
4651   //  - By the reduction:
4652   //      - Reduction operation:
4653   //        - One use of reduction value (safe).
4654   //        - Multiple use of reduction value (not safe).
4655   //      - PHI:
4656   //        - All uses of the PHI must be the reduction (safe).
4657   //        - Otherwise, not safe.
4658   //  - By one instruction outside of the loop (safe).
4659   //  - By further instructions outside of the loop (not safe).
4660   //  - By an instruction that is not part of the reduction (not safe).
4661   //    This is either:
4662   //      * An instruction type other than PHI or the reduction operation.
4663   //      * A PHI in the header other than the initial PHI.
4664   while (!Worklist.empty()) {
4665     Instruction *Cur = Worklist.back();
4666     Worklist.pop_back();
4667
4668     // No Users.
4669     // If the instruction has no users then this is a broken chain and can't be
4670     // a reduction variable.
4671     if (Cur->use_empty())
4672       return false;
4673
4674     bool IsAPhi = isa<PHINode>(Cur);
4675
4676     // A header PHI use other than the original PHI.
4677     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4678       return false;
4679
4680     // Reductions of instructions such as Div, and Sub is only possible if the
4681     // LHS is the reduction variable.
4682     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4683         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4684         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4685       return false;
4686
4687     // Any reduction instruction must be of one of the allowed kinds.
4688     ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4689     if (!ReduxDesc.IsReduction)
4690       return false;
4691
4692     // A reduction operation must only have one use of the reduction value.
4693     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4694         hasMultipleUsesOf(Cur, VisitedInsts))
4695       return false;
4696
4697     // All inputs to a PHI node must be a reduction value.
4698     if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4699       return false;
4700
4701     if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4702                                      isa<SelectInst>(Cur)))
4703       ++NumCmpSelectPatternInst;
4704     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4705                                    isa<SelectInst>(Cur)))
4706       ++NumCmpSelectPatternInst;
4707
4708     // Check  whether we found a reduction operator.
4709     FoundReduxOp |= !IsAPhi;
4710
4711     // Process users of current instruction. Push non-PHI nodes after PHI nodes
4712     // onto the stack. This way we are going to have seen all inputs to PHI
4713     // nodes once we get to them.
4714     SmallVector<Instruction *, 8> NonPHIs;
4715     SmallVector<Instruction *, 8> PHIs;
4716     for (User *U : Cur->users()) {
4717       Instruction *UI = cast<Instruction>(U);
4718
4719       // Check if we found the exit user.
4720       BasicBlock *Parent = UI->getParent();
4721       if (!TheLoop->contains(Parent)) {
4722         // Exit if you find multiple outside users or if the header phi node is
4723         // being used. In this case the user uses the value of the previous
4724         // iteration, in which case we would loose "VF-1" iterations of the
4725         // reduction operation if we vectorize.
4726         if (ExitInstruction != nullptr || Cur == Phi)
4727           return false;
4728
4729         // The instruction used by an outside user must be the last instruction
4730         // before we feed back to the reduction phi. Otherwise, we loose VF-1
4731         // operations on the value.
4732         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4733          return false;
4734
4735         ExitInstruction = Cur;
4736         continue;
4737       }
4738
4739       // Process instructions only once (termination). Each reduction cycle
4740       // value must only be used once, except by phi nodes and min/max
4741       // reductions which are represented as a cmp followed by a select.
4742       ReductionInstDesc IgnoredVal(false, nullptr);
4743       if (VisitedInsts.insert(UI)) {
4744         if (isa<PHINode>(UI))
4745           PHIs.push_back(UI);
4746         else
4747           NonPHIs.push_back(UI);
4748       } else if (!isa<PHINode>(UI) &&
4749                  ((!isa<FCmpInst>(UI) &&
4750                    !isa<ICmpInst>(UI) &&
4751                    !isa<SelectInst>(UI)) ||
4752                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4753         return false;
4754
4755       // Remember that we completed the cycle.
4756       if (UI == Phi)
4757         FoundStartPHI = true;
4758     }
4759     Worklist.append(PHIs.begin(), PHIs.end());
4760     Worklist.append(NonPHIs.begin(), NonPHIs.end());
4761   }
4762
4763   // This means we have seen one but not the other instruction of the
4764   // pattern or more than just a select and cmp.
4765   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4766       NumCmpSelectPatternInst != 2)
4767     return false;
4768
4769   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4770     return false;
4771
4772   // We found a reduction var if we have reached the original phi node and we
4773   // only have a single instruction with out-of-loop users.
4774
4775   // This instruction is allowed to have out-of-loop users.
4776   AllowedExit.insert(ExitInstruction);
4777
4778   // Save the description of this reduction variable.
4779   ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4780                          ReduxDesc.MinMaxKind);
4781   Reductions[Phi] = RD;
4782   // We've ended the cycle. This is a reduction variable if we have an
4783   // outside user and it has a binary op.
4784
4785   return true;
4786 }
4787
4788 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4789 /// pattern corresponding to a min(X, Y) or max(X, Y).
4790 LoopVectorizationLegality::ReductionInstDesc
4791 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4792                                                     ReductionInstDesc &Prev) {
4793
4794   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4795          "Expect a select instruction");
4796   Instruction *Cmp = nullptr;
4797   SelectInst *Select = nullptr;
4798
4799   // We must handle the select(cmp()) as a single instruction. Advance to the
4800   // select.
4801   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4802     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4803       return ReductionInstDesc(false, I);
4804     return ReductionInstDesc(Select, Prev.MinMaxKind);
4805   }
4806
4807   // Only handle single use cases for now.
4808   if (!(Select = dyn_cast<SelectInst>(I)))
4809     return ReductionInstDesc(false, I);
4810   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4811       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4812     return ReductionInstDesc(false, I);
4813   if (!Cmp->hasOneUse())
4814     return ReductionInstDesc(false, I);
4815
4816   Value *CmpLeft;
4817   Value *CmpRight;
4818
4819   // Look for a min/max pattern.
4820   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4821     return ReductionInstDesc(Select, MRK_UIntMin);
4822   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4823     return ReductionInstDesc(Select, MRK_UIntMax);
4824   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4825     return ReductionInstDesc(Select, MRK_SIntMax);
4826   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4827     return ReductionInstDesc(Select, MRK_SIntMin);
4828   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4829     return ReductionInstDesc(Select, MRK_FloatMin);
4830   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4831     return ReductionInstDesc(Select, MRK_FloatMax);
4832   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4833     return ReductionInstDesc(Select, MRK_FloatMin);
4834   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4835     return ReductionInstDesc(Select, MRK_FloatMax);
4836
4837   return ReductionInstDesc(false, I);
4838 }
4839
4840 LoopVectorizationLegality::ReductionInstDesc
4841 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4842                                             ReductionKind Kind,
4843                                             ReductionInstDesc &Prev) {
4844   bool FP = I->getType()->isFloatingPointTy();
4845   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4846   switch (I->getOpcode()) {
4847   default:
4848     return ReductionInstDesc(false, I);
4849   case Instruction::PHI:
4850       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4851                  Kind != RK_FloatMinMax))
4852         return ReductionInstDesc(false, I);
4853     return ReductionInstDesc(I, Prev.MinMaxKind);
4854   case Instruction::Sub:
4855   case Instruction::Add:
4856     return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4857   case Instruction::Mul:
4858     return ReductionInstDesc(Kind == RK_IntegerMult, I);
4859   case Instruction::And:
4860     return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4861   case Instruction::Or:
4862     return ReductionInstDesc(Kind == RK_IntegerOr, I);
4863   case Instruction::Xor:
4864     return ReductionInstDesc(Kind == RK_IntegerXor, I);
4865   case Instruction::FMul:
4866     return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4867   case Instruction::FAdd:
4868     return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4869   case Instruction::FCmp:
4870   case Instruction::ICmp:
4871   case Instruction::Select:
4872     if (Kind != RK_IntegerMinMax &&
4873         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4874       return ReductionInstDesc(false, I);
4875     return isMinMaxSelectCmpPattern(I, Prev);
4876   }
4877 }
4878
4879 LoopVectorizationLegality::InductionKind
4880 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4881   Type *PhiTy = Phi->getType();
4882   // We only handle integer and pointer inductions variables.
4883   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4884     return IK_NoInduction;
4885
4886   // Check that the PHI is consecutive.
4887   const SCEV *PhiScev = SE->getSCEV(Phi);
4888   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4889   if (!AR) {
4890     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4891     return IK_NoInduction;
4892   }
4893   const SCEV *Step = AR->getStepRecurrence(*SE);
4894
4895   // Integer inductions need to have a stride of one.
4896   if (PhiTy->isIntegerTy()) {
4897     if (Step->isOne())
4898       return IK_IntInduction;
4899     if (Step->isAllOnesValue())
4900       return IK_ReverseIntInduction;
4901     return IK_NoInduction;
4902   }
4903
4904   // Calculate the pointer stride and check if it is consecutive.
4905   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4906   if (!C)
4907     return IK_NoInduction;
4908
4909   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4910   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4911   if (C->getValue()->equalsInt(Size))
4912     return IK_PtrInduction;
4913   else if (C->getValue()->equalsInt(0 - Size))
4914     return IK_ReversePtrInduction;
4915
4916   return IK_NoInduction;
4917 }
4918
4919 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4920   Value *In0 = const_cast<Value*>(V);
4921   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4922   if (!PN)
4923     return false;
4924
4925   return Inductions.count(PN);
4926 }
4927
4928 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
4929   assert(TheLoop->contains(BB) && "Unknown block used");
4930
4931   // Blocks that do not dominate the latch need predication.
4932   BasicBlock* Latch = TheLoop->getLoopLatch();
4933   return !DT->dominates(BB, Latch);
4934 }
4935
4936 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4937                                             SmallPtrSet<Value *, 8>& SafePtrs) {
4938   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4939     // We might be able to hoist the load.
4940     if (it->mayReadFromMemory()) {
4941       LoadInst *LI = dyn_cast<LoadInst>(it);
4942       if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4943         return false;
4944     }
4945
4946     // We don't predicate stores at the moment.
4947     if (it->mayWriteToMemory()) {
4948       StoreInst *SI = dyn_cast<StoreInst>(it);
4949       // We only support predication of stores in basic blocks with one
4950       // predecessor.
4951       if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
4952           !SafePtrs.count(SI->getPointerOperand()) ||
4953           !SI->getParent()->getSinglePredecessor())
4954         return false;
4955     }
4956     if (it->mayThrow())
4957       return false;
4958
4959     // Check that we don't have a constant expression that can trap as operand.
4960     for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4961          OI != OE; ++OI) {
4962       if (Constant *C = dyn_cast<Constant>(*OI))
4963         if (C->canTrap())
4964           return false;
4965     }
4966
4967     // The instructions below can trap.
4968     switch (it->getOpcode()) {
4969     default: continue;
4970     case Instruction::UDiv:
4971     case Instruction::SDiv:
4972     case Instruction::URem:
4973     case Instruction::SRem:
4974              return false;
4975     }
4976   }
4977
4978   return true;
4979 }
4980
4981 LoopVectorizationCostModel::VectorizationFactor
4982 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4983                                                       unsigned UserVF,
4984                                                       bool ForceVectorization) {
4985   // Width 1 means no vectorize
4986   VectorizationFactor Factor = { 1U, 0U };
4987   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4988     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4989     return Factor;
4990   }
4991
4992   if (!EnableCondStoresVectorization && Legal->NumPredStores) {
4993     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4994     return Factor;
4995   }
4996
4997   // Find the trip count.
4998   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4999   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5000
5001   unsigned WidestType = getWidestType();
5002   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5003   unsigned MaxSafeDepDist = -1U;
5004   if (Legal->getMaxSafeDepDistBytes() != -1U)
5005     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5006   WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
5007                     WidestRegister : MaxSafeDepDist);
5008   unsigned MaxVectorSize = WidestRegister / WidestType;
5009   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
5010   DEBUG(dbgs() << "LV: The Widest register is: "
5011           << WidestRegister << " bits.\n");
5012
5013   if (MaxVectorSize == 0) {
5014     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5015     MaxVectorSize = 1;
5016   }
5017
5018   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
5019          " into one vector!");
5020
5021   unsigned VF = MaxVectorSize;
5022
5023   // If we optimize the program for size, avoid creating the tail loop.
5024   if (OptForSize) {
5025     // If we are unable to calculate the trip count then don't try to vectorize.
5026     if (TC < 2) {
5027       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5028       return Factor;
5029     }
5030
5031     // Find the maximum SIMD width that can fit within the trip count.
5032     VF = TC % MaxVectorSize;
5033
5034     if (VF == 0)
5035       VF = MaxVectorSize;
5036
5037     // If the trip count that we found modulo the vectorization factor is not
5038     // zero then we require a tail.
5039     if (VF < 2) {
5040       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5041       return Factor;
5042     }
5043   }
5044
5045   if (UserVF != 0) {
5046     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5047     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5048
5049     Factor.Width = UserVF;
5050     return Factor;
5051   }
5052
5053   float Cost = expectedCost(1);
5054 #ifndef NDEBUG
5055   const float ScalarCost = Cost;
5056 #endif /* NDEBUG */
5057   unsigned Width = 1;
5058   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5059
5060   // Ignore scalar width, because the user explicitly wants vectorization.
5061   if (ForceVectorization && VF > 1) {
5062     Width = 2;
5063     Cost = expectedCost(Width) / (float)Width;
5064   }
5065
5066   for (unsigned i=2; i <= VF; i*=2) {
5067     // Notice that the vector loop needs to be executed less times, so
5068     // we need to divide the cost of the vector loops by the width of
5069     // the vector elements.
5070     float VectorCost = expectedCost(i) / (float)i;
5071     DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5072           (int)VectorCost << ".\n");
5073     if (VectorCost < Cost) {
5074       Cost = VectorCost;
5075       Width = i;
5076     }
5077   }
5078
5079   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5080         << "LV: Vectorization seems to be not beneficial, "
5081         << "but was forced by a user.\n");
5082   DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5083   Factor.Width = Width;
5084   Factor.Cost = Width * Cost;
5085   return Factor;
5086 }
5087
5088 unsigned LoopVectorizationCostModel::getWidestType() {
5089   unsigned MaxWidth = 8;
5090
5091   // For each block.
5092   for (Loop::block_iterator bb = TheLoop->block_begin(),
5093        be = TheLoop->block_end(); bb != be; ++bb) {
5094     BasicBlock *BB = *bb;
5095
5096     // For each instruction in the loop.
5097     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5098       Type *T = it->getType();
5099
5100       // Only examine Loads, Stores and PHINodes.
5101       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5102         continue;
5103
5104       // Examine PHI nodes that are reduction variables.
5105       if (PHINode *PN = dyn_cast<PHINode>(it))
5106         if (!Legal->getReductionVars()->count(PN))
5107           continue;
5108
5109       // Examine the stored values.
5110       if (StoreInst *ST = dyn_cast<StoreInst>(it))
5111         T = ST->getValueOperand()->getType();
5112
5113       // Ignore loaded pointer types and stored pointer types that are not
5114       // consecutive. However, we do want to take consecutive stores/loads of
5115       // pointer vectors into account.
5116       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5117         continue;
5118
5119       MaxWidth = std::max(MaxWidth,
5120                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5121     }
5122   }
5123
5124   return MaxWidth;
5125 }
5126
5127 unsigned
5128 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5129                                                unsigned UserUF,
5130                                                unsigned VF,
5131                                                unsigned LoopCost) {
5132
5133   // -- The unroll heuristics --
5134   // We unroll the loop in order to expose ILP and reduce the loop overhead.
5135   // There are many micro-architectural considerations that we can't predict
5136   // at this level. For example frontend pressure (on decode or fetch) due to
5137   // code size, or the number and capabilities of the execution ports.
5138   //
5139   // We use the following heuristics to select the unroll factor:
5140   // 1. If the code has reductions the we unroll in order to break the cross
5141   // iteration dependency.
5142   // 2. If the loop is really small then we unroll in order to reduce the loop
5143   // overhead.
5144   // 3. We don't unroll if we think that we will spill registers to memory due
5145   // to the increased register pressure.
5146
5147   // Use the user preference, unless 'auto' is selected.
5148   if (UserUF != 0)
5149     return UserUF;
5150
5151   // When we optimize for size we don't unroll.
5152   if (OptForSize)
5153     return 1;
5154
5155   // We used the distance for the unroll factor.
5156   if (Legal->getMaxSafeDepDistBytes() != -1U)
5157     return 1;
5158
5159   // Do not unroll loops with a relatively small trip count.
5160   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5161                                               TheLoop->getLoopLatch());
5162   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5163     return 1;
5164
5165   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5166   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5167         " registers\n");
5168
5169   if (VF == 1) {
5170     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5171       TargetNumRegisters = ForceTargetNumScalarRegs;
5172   } else {
5173     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5174       TargetNumRegisters = ForceTargetNumVectorRegs;
5175   }
5176
5177   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5178   // We divide by these constants so assume that we have at least one
5179   // instruction that uses at least one register.
5180   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5181   R.NumInstructions = std::max(R.NumInstructions, 1U);
5182
5183   // We calculate the unroll factor using the following formula.
5184   // Subtract the number of loop invariants from the number of available
5185   // registers. These registers are used by all of the unrolled instances.
5186   // Next, divide the remaining registers by the number of registers that is
5187   // required by the loop, in order to estimate how many parallel instances
5188   // fit without causing spills. All of this is rounded down if necessary to be
5189   // a power of two. We want power of two unroll factors to simplify any
5190   // addressing operations or alignment considerations.
5191   unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5192                               R.MaxLocalUsers);
5193
5194   // Don't count the induction variable as unrolled.
5195   if (EnableIndVarRegisterHeur)
5196     UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5197                        std::max(1U, (R.MaxLocalUsers - 1)));
5198
5199   // Clamp the unroll factor ranges to reasonable factors.
5200   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5201
5202   // Check if the user has overridden the unroll max.
5203   if (VF == 1) {
5204     if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5205       MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5206   } else {
5207     if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5208       MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5209   }
5210
5211   // If we did not calculate the cost for VF (because the user selected the VF)
5212   // then we calculate the cost of VF here.
5213   if (LoopCost == 0)
5214     LoopCost = expectedCost(VF);
5215
5216   // Clamp the calculated UF to be between the 1 and the max unroll factor
5217   // that the target allows.
5218   if (UF > MaxUnrollSize)
5219     UF = MaxUnrollSize;
5220   else if (UF < 1)
5221     UF = 1;
5222
5223   // Unroll if we vectorized this loop and there is a reduction that could
5224   // benefit from unrolling.
5225   if (VF > 1 && Legal->getReductionVars()->size()) {
5226     DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5227     return UF;
5228   }
5229
5230   // Note that if we've already vectorized the loop we will have done the
5231   // runtime check and so unrolling won't require further checks.
5232   bool UnrollingRequiresRuntimePointerCheck =
5233       (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5234
5235   // We want to unroll small loops in order to reduce the loop overhead and
5236   // potentially expose ILP opportunities.
5237   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5238   if (!UnrollingRequiresRuntimePointerCheck &&
5239       LoopCost < SmallLoopCost) {
5240     // We assume that the cost overhead is 1 and we use the cost model
5241     // to estimate the cost of the loop and unroll until the cost of the
5242     // loop overhead is about 5% of the cost of the loop.
5243     unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5244
5245     // Unroll until store/load ports (estimated by max unroll factor) are
5246     // saturated.
5247     unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5248     unsigned LoadsUF = UF /  (Legal->NumLoads ? Legal->NumLoads : 1);
5249
5250     if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5251       DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5252       return std::max(StoresUF, LoadsUF);
5253     }
5254
5255     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5256     return SmallUF;
5257   }
5258
5259   DEBUG(dbgs() << "LV: Not Unrolling.\n");
5260   return 1;
5261 }
5262
5263 LoopVectorizationCostModel::RegisterUsage
5264 LoopVectorizationCostModel::calculateRegisterUsage() {
5265   // This function calculates the register usage by measuring the highest number
5266   // of values that are alive at a single location. Obviously, this is a very
5267   // rough estimation. We scan the loop in a topological order in order and
5268   // assign a number to each instruction. We use RPO to ensure that defs are
5269   // met before their users. We assume that each instruction that has in-loop
5270   // users starts an interval. We record every time that an in-loop value is
5271   // used, so we have a list of the first and last occurrences of each
5272   // instruction. Next, we transpose this data structure into a multi map that
5273   // holds the list of intervals that *end* at a specific location. This multi
5274   // map allows us to perform a linear search. We scan the instructions linearly
5275   // and record each time that a new interval starts, by placing it in a set.
5276   // If we find this value in the multi-map then we remove it from the set.
5277   // The max register usage is the maximum size of the set.
5278   // We also search for instructions that are defined outside the loop, but are
5279   // used inside the loop. We need this number separately from the max-interval
5280   // usage number because when we unroll, loop-invariant values do not take
5281   // more register.
5282   LoopBlocksDFS DFS(TheLoop);
5283   DFS.perform(LI);
5284
5285   RegisterUsage R;
5286   R.NumInstructions = 0;
5287
5288   // Each 'key' in the map opens a new interval. The values
5289   // of the map are the index of the 'last seen' usage of the
5290   // instruction that is the key.
5291   typedef DenseMap<Instruction*, unsigned> IntervalMap;
5292   // Maps instruction to its index.
5293   DenseMap<unsigned, Instruction*> IdxToInstr;
5294   // Marks the end of each interval.
5295   IntervalMap EndPoint;
5296   // Saves the list of instruction indices that are used in the loop.
5297   SmallSet<Instruction*, 8> Ends;
5298   // Saves the list of values that are used in the loop but are
5299   // defined outside the loop, such as arguments and constants.
5300   SmallPtrSet<Value*, 8> LoopInvariants;
5301
5302   unsigned Index = 0;
5303   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5304        be = DFS.endRPO(); bb != be; ++bb) {
5305     R.NumInstructions += (*bb)->size();
5306     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5307          ++it) {
5308       Instruction *I = it;
5309       IdxToInstr[Index++] = I;
5310
5311       // Save the end location of each USE.
5312       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5313         Value *U = I->getOperand(i);
5314         Instruction *Instr = dyn_cast<Instruction>(U);
5315
5316         // Ignore non-instruction values such as arguments, constants, etc.
5317         if (!Instr) continue;
5318
5319         // If this instruction is outside the loop then record it and continue.
5320         if (!TheLoop->contains(Instr)) {
5321           LoopInvariants.insert(Instr);
5322           continue;
5323         }
5324
5325         // Overwrite previous end points.
5326         EndPoint[Instr] = Index;
5327         Ends.insert(Instr);
5328       }
5329     }
5330   }
5331
5332   // Saves the list of intervals that end with the index in 'key'.
5333   typedef SmallVector<Instruction*, 2> InstrList;
5334   DenseMap<unsigned, InstrList> TransposeEnds;
5335
5336   // Transpose the EndPoints to a list of values that end at each index.
5337   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5338        it != e; ++it)
5339     TransposeEnds[it->second].push_back(it->first);
5340
5341   SmallSet<Instruction*, 8> OpenIntervals;
5342   unsigned MaxUsage = 0;
5343
5344
5345   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5346   for (unsigned int i = 0; i < Index; ++i) {
5347     Instruction *I = IdxToInstr[i];
5348     // Ignore instructions that are never used within the loop.
5349     if (!Ends.count(I)) continue;
5350
5351     // Remove all of the instructions that end at this location.
5352     InstrList &List = TransposeEnds[i];
5353     for (unsigned int j=0, e = List.size(); j < e; ++j)
5354       OpenIntervals.erase(List[j]);
5355
5356     // Count the number of live interals.
5357     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5358
5359     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5360           OpenIntervals.size() << '\n');
5361
5362     // Add the current instruction to the list of open intervals.
5363     OpenIntervals.insert(I);
5364   }
5365
5366   unsigned Invariant = LoopInvariants.size();
5367   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5368   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5369   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5370
5371   R.LoopInvariantRegs = Invariant;
5372   R.MaxLocalUsers = MaxUsage;
5373   return R;
5374 }
5375
5376 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5377   unsigned Cost = 0;
5378
5379   // For each block.
5380   for (Loop::block_iterator bb = TheLoop->block_begin(),
5381        be = TheLoop->block_end(); bb != be; ++bb) {
5382     unsigned BlockCost = 0;
5383     BasicBlock *BB = *bb;
5384
5385     // For each instruction in the old loop.
5386     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5387       // Skip dbg intrinsics.
5388       if (isa<DbgInfoIntrinsic>(it))
5389         continue;
5390
5391       unsigned C = getInstructionCost(it, VF);
5392
5393       // Check if we should override the cost.
5394       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5395         C = ForceTargetInstructionCost;
5396
5397       BlockCost += C;
5398       DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5399             VF << " For instruction: " << *it << '\n');
5400     }
5401
5402     // We assume that if-converted blocks have a 50% chance of being executed.
5403     // When the code is scalar then some of the blocks are avoided due to CF.
5404     // When the code is vectorized we execute all code paths.
5405     if (VF == 1 && Legal->blockNeedsPredication(*bb))
5406       BlockCost /= 2;
5407
5408     Cost += BlockCost;
5409   }
5410
5411   return Cost;
5412 }
5413
5414 /// \brief Check whether the address computation for a non-consecutive memory
5415 /// access looks like an unlikely candidate for being merged into the indexing
5416 /// mode.
5417 ///
5418 /// We look for a GEP which has one index that is an induction variable and all
5419 /// other indices are loop invariant. If the stride of this access is also
5420 /// within a small bound we decide that this address computation can likely be
5421 /// merged into the addressing mode.
5422 /// In all other cases, we identify the address computation as complex.
5423 static bool isLikelyComplexAddressComputation(Value *Ptr,
5424                                               LoopVectorizationLegality *Legal,
5425                                               ScalarEvolution *SE,
5426                                               const Loop *TheLoop) {
5427   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5428   if (!Gep)
5429     return true;
5430
5431   // We are looking for a gep with all loop invariant indices except for one
5432   // which should be an induction variable.
5433   unsigned NumOperands = Gep->getNumOperands();
5434   for (unsigned i = 1; i < NumOperands; ++i) {
5435     Value *Opd = Gep->getOperand(i);
5436     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5437         !Legal->isInductionVariable(Opd))
5438       return true;
5439   }
5440
5441   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5442   // can likely be merged into the address computation.
5443   unsigned MaxMergeDistance = 64;
5444
5445   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5446   if (!AddRec)
5447     return true;
5448
5449   // Check the step is constant.
5450   const SCEV *Step = AddRec->getStepRecurrence(*SE);
5451   // Calculate the pointer stride and check if it is consecutive.
5452   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5453   if (!C)
5454     return true;
5455
5456   const APInt &APStepVal = C->getValue()->getValue();
5457
5458   // Huge step value - give up.
5459   if (APStepVal.getBitWidth() > 64)
5460     return true;
5461
5462   int64_t StepVal = APStepVal.getSExtValue();
5463
5464   return StepVal > MaxMergeDistance;
5465 }
5466
5467 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5468   if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5469     return true;
5470   return false;
5471 }
5472
5473 unsigned
5474 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5475   // If we know that this instruction will remain uniform, check the cost of
5476   // the scalar version.
5477   if (Legal->isUniformAfterVectorization(I))
5478     VF = 1;
5479
5480   Type *RetTy = I->getType();
5481   Type *VectorTy = ToVectorTy(RetTy, VF);
5482
5483   // TODO: We need to estimate the cost of intrinsic calls.
5484   switch (I->getOpcode()) {
5485   case Instruction::GetElementPtr:
5486     // We mark this instruction as zero-cost because the cost of GEPs in
5487     // vectorized code depends on whether the corresponding memory instruction
5488     // is scalarized or not. Therefore, we handle GEPs with the memory
5489     // instruction cost.
5490     return 0;
5491   case Instruction::Br: {
5492     return TTI.getCFInstrCost(I->getOpcode());
5493   }
5494   case Instruction::PHI:
5495     //TODO: IF-converted IFs become selects.
5496     return 0;
5497   case Instruction::Add:
5498   case Instruction::FAdd:
5499   case Instruction::Sub:
5500   case Instruction::FSub:
5501   case Instruction::Mul:
5502   case Instruction::FMul:
5503   case Instruction::UDiv:
5504   case Instruction::SDiv:
5505   case Instruction::FDiv:
5506   case Instruction::URem:
5507   case Instruction::SRem:
5508   case Instruction::FRem:
5509   case Instruction::Shl:
5510   case Instruction::LShr:
5511   case Instruction::AShr:
5512   case Instruction::And:
5513   case Instruction::Or:
5514   case Instruction::Xor: {
5515     // Since we will replace the stride by 1 the multiplication should go away.
5516     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5517       return 0;
5518     // Certain instructions can be cheaper to vectorize if they have a constant
5519     // second vector operand. One example of this are shifts on x86.
5520     TargetTransformInfo::OperandValueKind Op1VK =
5521       TargetTransformInfo::OK_AnyValue;
5522     TargetTransformInfo::OperandValueKind Op2VK =
5523       TargetTransformInfo::OK_AnyValue;
5524     Value *Op2 = I->getOperand(1);
5525
5526     // Check for a splat of a constant or for a non uniform vector of constants.
5527     if (isa<ConstantInt>(Op2))
5528       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5529     else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5530       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5531       if (cast<Constant>(Op2)->getSplatValue() != nullptr)
5532         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5533     }
5534
5535     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5536   }
5537   case Instruction::Select: {
5538     SelectInst *SI = cast<SelectInst>(I);
5539     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5540     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5541     Type *CondTy = SI->getCondition()->getType();
5542     if (!ScalarCond)
5543       CondTy = VectorType::get(CondTy, VF);
5544
5545     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5546   }
5547   case Instruction::ICmp:
5548   case Instruction::FCmp: {
5549     Type *ValTy = I->getOperand(0)->getType();
5550     VectorTy = ToVectorTy(ValTy, VF);
5551     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5552   }
5553   case Instruction::Store:
5554   case Instruction::Load: {
5555     StoreInst *SI = dyn_cast<StoreInst>(I);
5556     LoadInst *LI = dyn_cast<LoadInst>(I);
5557     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5558                    LI->getType());
5559     VectorTy = ToVectorTy(ValTy, VF);
5560
5561     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5562     unsigned AS = SI ? SI->getPointerAddressSpace() :
5563       LI->getPointerAddressSpace();
5564     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5565     // We add the cost of address computation here instead of with the gep
5566     // instruction because only here we know whether the operation is
5567     // scalarized.
5568     if (VF == 1)
5569       return TTI.getAddressComputationCost(VectorTy) +
5570         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5571
5572     // Scalarized loads/stores.
5573     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5574     bool Reverse = ConsecutiveStride < 0;
5575     unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5576     unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5577     if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5578       bool IsComplexComputation =
5579         isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5580       unsigned Cost = 0;
5581       // The cost of extracting from the value vector and pointer vector.
5582       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5583       for (unsigned i = 0; i < VF; ++i) {
5584         //  The cost of extracting the pointer operand.
5585         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5586         // In case of STORE, the cost of ExtractElement from the vector.
5587         // In case of LOAD, the cost of InsertElement into the returned
5588         // vector.
5589         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5590                                             Instruction::InsertElement,
5591                                             VectorTy, i);
5592       }
5593
5594       // The cost of the scalar loads/stores.
5595       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5596       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5597                                        Alignment, AS);
5598       return Cost;
5599     }
5600
5601     // Wide load/stores.
5602     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5603     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5604
5605     if (Reverse)
5606       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5607                                   VectorTy, 0);
5608     return Cost;
5609   }
5610   case Instruction::ZExt:
5611   case Instruction::SExt:
5612   case Instruction::FPToUI:
5613   case Instruction::FPToSI:
5614   case Instruction::FPExt:
5615   case Instruction::PtrToInt:
5616   case Instruction::IntToPtr:
5617   case Instruction::SIToFP:
5618   case Instruction::UIToFP:
5619   case Instruction::Trunc:
5620   case Instruction::FPTrunc:
5621   case Instruction::BitCast: {
5622     // We optimize the truncation of induction variable.
5623     // The cost of these is the same as the scalar operation.
5624     if (I->getOpcode() == Instruction::Trunc &&
5625         Legal->isInductionVariable(I->getOperand(0)))
5626       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5627                                   I->getOperand(0)->getType());
5628
5629     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5630     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5631   }
5632   case Instruction::Call: {
5633     CallInst *CI = cast<CallInst>(I);
5634     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5635     assert(ID && "Not an intrinsic call!");
5636     Type *RetTy = ToVectorTy(CI->getType(), VF);
5637     SmallVector<Type*, 4> Tys;
5638     for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5639       Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5640     return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5641   }
5642   default: {
5643     // We are scalarizing the instruction. Return the cost of the scalar
5644     // instruction, plus the cost of insert and extract into vector
5645     // elements, times the vector width.
5646     unsigned Cost = 0;
5647
5648     if (!RetTy->isVoidTy() && VF != 1) {
5649       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5650                                                 VectorTy);
5651       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5652                                                 VectorTy);
5653
5654       // The cost of inserting the results plus extracting each one of the
5655       // operands.
5656       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5657     }
5658
5659     // The cost of executing VF copies of the scalar instruction. This opcode
5660     // is unknown. Assume that it is the same as 'mul'.
5661     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5662     return Cost;
5663   }
5664   }// end of switch.
5665 }
5666
5667 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5668   if (Scalar->isVoidTy() || VF == 1)
5669     return Scalar;
5670   return VectorType::get(Scalar, VF);
5671 }
5672
5673 char LoopVectorize::ID = 0;
5674 static const char lv_name[] = "Loop Vectorization";
5675 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5676 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5677 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5678 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5679 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5680 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5681 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5682 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5683 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5684
5685 namespace llvm {
5686   Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5687     return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5688   }
5689 }
5690
5691 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5692   // Check for a store.
5693   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5694     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5695
5696   // Check for a load.
5697   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5698     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5699
5700   return false;
5701 }
5702
5703
5704 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5705                                              bool IfPredicateStore) {
5706   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5707   // Holds vector parameters or scalars, in case of uniform vals.
5708   SmallVector<VectorParts, 4> Params;
5709
5710   setDebugLocFromInst(Builder, Instr);
5711
5712   // Find all of the vectorized parameters.
5713   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5714     Value *SrcOp = Instr->getOperand(op);
5715
5716     // If we are accessing the old induction variable, use the new one.
5717     if (SrcOp == OldInduction) {
5718       Params.push_back(getVectorValue(SrcOp));
5719       continue;
5720     }
5721
5722     // Try using previously calculated values.
5723     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5724
5725     // If the src is an instruction that appeared earlier in the basic block
5726     // then it should already be vectorized.
5727     if (SrcInst && OrigLoop->contains(SrcInst)) {
5728       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5729       // The parameter is a vector value from earlier.
5730       Params.push_back(WidenMap.get(SrcInst));
5731     } else {
5732       // The parameter is a scalar from outside the loop. Maybe even a constant.
5733       VectorParts Scalars;
5734       Scalars.append(UF, SrcOp);
5735       Params.push_back(Scalars);
5736     }
5737   }
5738
5739   assert(Params.size() == Instr->getNumOperands() &&
5740          "Invalid number of operands");
5741
5742   // Does this instruction return a value ?
5743   bool IsVoidRetTy = Instr->getType()->isVoidTy();
5744
5745   Value *UndefVec = IsVoidRetTy ? nullptr :
5746   UndefValue::get(Instr->getType());
5747   // Create a new entry in the WidenMap and initialize it to Undef or Null.
5748   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5749
5750   Instruction *InsertPt = Builder.GetInsertPoint();
5751   BasicBlock *IfBlock = Builder.GetInsertBlock();
5752   BasicBlock *CondBlock = nullptr;
5753
5754   VectorParts Cond;
5755   Loop *VectorLp = nullptr;
5756   if (IfPredicateStore) {
5757     assert(Instr->getParent()->getSinglePredecessor() &&
5758            "Only support single predecessor blocks");
5759     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5760                           Instr->getParent());
5761     VectorLp = LI->getLoopFor(IfBlock);
5762     assert(VectorLp && "Must have a loop for this block");
5763   }
5764
5765   // For each vector unroll 'part':
5766   for (unsigned Part = 0; Part < UF; ++Part) {
5767     // For each scalar that we create:
5768
5769     // Start an "if (pred) a[i] = ..." block.
5770     Value *Cmp = nullptr;
5771     if (IfPredicateStore) {
5772       if (Cond[Part]->getType()->isVectorTy())
5773         Cond[Part] =
5774             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5775       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5776                                ConstantInt::get(Cond[Part]->getType(), 1));
5777       CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5778       LoopVectorBody.push_back(CondBlock);
5779       VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
5780       // Update Builder with newly created basic block.
5781       Builder.SetInsertPoint(InsertPt);
5782     }
5783
5784     Instruction *Cloned = Instr->clone();
5785       if (!IsVoidRetTy)
5786         Cloned->setName(Instr->getName() + ".cloned");
5787       // Replace the operands of the cloned instructions with extracted scalars.
5788       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5789         Value *Op = Params[op][Part];
5790         Cloned->setOperand(op, Op);
5791       }
5792
5793       // Place the cloned scalar in the new loop.
5794       Builder.Insert(Cloned);
5795
5796       // If the original scalar returns a value we need to place it in a vector
5797       // so that future users will be able to use it.
5798       if (!IsVoidRetTy)
5799         VecResults[Part] = Cloned;
5800
5801     // End if-block.
5802       if (IfPredicateStore) {
5803         BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5804         LoopVectorBody.push_back(NewIfBlock);
5805         VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
5806         Builder.SetInsertPoint(InsertPt);
5807         Instruction *OldBr = IfBlock->getTerminator();
5808         BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5809         OldBr->eraseFromParent();
5810         IfBlock = NewIfBlock;
5811       }
5812   }
5813 }
5814
5815 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5816   StoreInst *SI = dyn_cast<StoreInst>(Instr);
5817   bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5818
5819   return scalarizeInstruction(Instr, IfPredicateStore);
5820 }
5821
5822 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5823   return Vec;
5824 }
5825
5826 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5827   return V;
5828 }
5829
5830 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5831                                                bool Negate) {
5832   // When unrolling and the VF is 1, we only need to add a simple scalar.
5833   Type *ITy = Val->getType();
5834   assert(!ITy->isVectorTy() && "Val must be a scalar");
5835   Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5836   return Builder.CreateAdd(Val, C, "induction");
5837 }
5838