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