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