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