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