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