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