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