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