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