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