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