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