f3bd96c028c7412ac1d8ca575d2860df90c1e47c
[oota-llvm.git] / lib / Transforms / Vectorize / LoopVectorize.cpp
1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
14 //
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
18 //
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 //    of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 //    widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 //    of vectorization. It decides on the optimal vector width, which
27 //    can be one, if vectorization is not profitable.
28 //
29 //===----------------------------------------------------------------------===//
30 //
31 // The reduction-variable vectorization is based on the paper:
32 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33 //
34 // Variable uniformity checks are inspired by:
35 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
36 //
37 // Other ideas/concepts are from:
38 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39 //
40 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
41 //  Vectorizing Compilers.
42 //
43 //===----------------------------------------------------------------------===//
44
45 #include "llvm/Transforms/Vectorize.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/EquivalenceClasses.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/AliasSetTracker.h"
58 #include "llvm/Analysis/AssumptionTracker.h"
59 #include "llvm/Analysis/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/CodeMetrics.h"
61 #include "llvm/Analysis/LoopInfo.h"
62 #include "llvm/Analysis/LoopIterator.h"
63 #include "llvm/Analysis/LoopPass.h"
64 #include "llvm/Analysis/ScalarEvolution.h"
65 #include "llvm/Analysis/ScalarEvolutionExpander.h"
66 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
67 #include "llvm/Analysis/TargetTransformInfo.h"
68 #include "llvm/Analysis/ValueTracking.h"
69 #include "llvm/IR/Constants.h"
70 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DebugInfo.h"
72 #include "llvm/IR/DerivedTypes.h"
73 #include "llvm/IR/DiagnosticInfo.h"
74 #include "llvm/IR/Dominators.h"
75 #include "llvm/IR/Function.h"
76 #include "llvm/IR/IRBuilder.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/Module.h"
81 #include "llvm/IR/PatternMatch.h"
82 #include "llvm/IR/Type.h"
83 #include "llvm/IR/Value.h"
84 #include "llvm/IR/ValueHandle.h"
85 #include "llvm/IR/Verifier.h"
86 #include "llvm/Pass.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Debug.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Transforms/Scalar.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 #include "llvm/Transforms/Utils/Local.h"
94 #include "llvm/Transforms/Utils/VectorUtils.h"
95 #include <algorithm>
96 #include <map>
97 #include <tuple>
98
99 using namespace llvm;
100 using namespace llvm::PatternMatch;
101
102 #define LV_NAME "loop-vectorize"
103 #define DEBUG_TYPE LV_NAME
104
105 STATISTIC(LoopsVectorized, "Number of loops vectorized");
106 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
107
108 static cl::opt<unsigned>
109 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
110                     cl::desc("Sets the SIMD width. Zero is autoselect."));
111
112 static cl::opt<unsigned>
113 VectorizationInterleave("force-vector-interleave", cl::init(0), cl::Hidden,
114                     cl::desc("Sets the vectorization interleave count. "
115                              "Zero is autoselect."));
116
117 static cl::opt<bool>
118 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
119                    cl::desc("Enable if-conversion during vectorization."));
120
121 /// We don't vectorize loops with a known constant trip count below this number.
122 static cl::opt<unsigned>
123 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
124                              cl::Hidden,
125                              cl::desc("Don't vectorize loops with a constant "
126                                       "trip count that is smaller than this "
127                                       "value."));
128
129 /// This enables versioning on the strides of symbolically striding memory
130 /// accesses in code like the following.
131 ///   for (i = 0; i < N; ++i)
132 ///     A[i * Stride1] += B[i * Stride2] ...
133 ///
134 /// Will be roughly translated to
135 ///    if (Stride1 == 1 && Stride2 == 1) {
136 ///      for (i = 0; i < N; i+=4)
137 ///       A[i:i+3] += ...
138 ///    } else
139 ///      ...
140 static cl::opt<bool> EnableMemAccessVersioning(
141     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
142     cl::desc("Enable symblic stride memory access versioning"));
143
144 /// We don't unroll loops with a known constant trip count below this number.
145 static const unsigned TinyTripCountUnrollThreshold = 128;
146
147 /// When performing memory disambiguation checks at runtime do not make more
148 /// than this number of comparisons.
149 static const unsigned RuntimeMemoryCheckThreshold = 8;
150
151 /// Maximum simd width.
152 static const unsigned MaxVectorWidth = 64;
153
154 static cl::opt<unsigned> ForceTargetNumScalarRegs(
155     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
156     cl::desc("A flag that overrides the target's number of scalar registers."));
157
158 static cl::opt<unsigned> ForceTargetNumVectorRegs(
159     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
160     cl::desc("A flag that overrides the target's number of vector registers."));
161
162 /// Maximum vectorization interleave count.
163 static const unsigned MaxInterleaveFactor = 16;
164
165 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
166     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
167     cl::desc("A flag that overrides the target's max interleave factor for "
168              "scalar loops."));
169
170 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
171     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
172     cl::desc("A flag that overrides the target's max interleave factor for "
173              "vectorized loops."));
174
175 static cl::opt<unsigned> ForceTargetInstructionCost(
176     "force-target-instruction-cost", cl::init(0), cl::Hidden,
177     cl::desc("A flag that overrides the target's expected cost for "
178              "an instruction to a single constant value. Mostly "
179              "useful for getting consistent testing."));
180
181 static cl::opt<unsigned> SmallLoopCost(
182     "small-loop-cost", cl::init(20), cl::Hidden,
183     cl::desc("The cost of a loop that is considered 'small' by the unroller."));
184
185 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
186     "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
187     cl::desc("Enable the use of the block frequency analysis to access PGO "
188              "heuristics minimizing code growth in cold regions and being more "
189              "aggressive in hot regions."));
190
191 // Runtime unroll loops for load/store throughput.
192 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
193     "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
194     cl::desc("Enable runtime unrolling until load/store ports are saturated"));
195
196 /// The number of stores in a loop that are allowed to need predication.
197 static cl::opt<unsigned> NumberOfStoresToPredicate(
198     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
199     cl::desc("Max number of stores to be predicated behind an if."));
200
201 static cl::opt<bool> EnableIndVarRegisterHeur(
202     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
203     cl::desc("Count the induction variable only once when unrolling"));
204
205 static cl::opt<bool> EnableCondStoresVectorization(
206     "enable-cond-stores-vec", cl::init(false), cl::Hidden,
207     cl::desc("Enable if predication of stores during vectorization."));
208
209 static cl::opt<unsigned> MaxNestedScalarReductionUF(
210     "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
211     cl::desc("The maximum unroll factor to use when unrolling a scalar "
212              "reduction in a nested loop."));
213
214 namespace {
215
216 // Forward declarations.
217 class LoopVectorizationLegality;
218 class LoopVectorizationCostModel;
219 class LoopVectorizeHints;
220
221 /// Optimization analysis message produced during vectorization. Messages inform
222 /// the user why vectorization did not occur.
223 class Report {
224   std::string Message;
225   raw_string_ostream Out;
226   Instruction *Instr;
227
228 public:
229   Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
230     Out << "loop not vectorized: ";
231   }
232
233   template <typename A> Report &operator<<(const A &Value) {
234     Out << Value;
235     return *this;
236   }
237
238   Instruction *getInstr() { return Instr; }
239
240   std::string &str() { return Out.str(); }
241   operator Twine() { return Out.str(); }
242 };
243
244 /// InnerLoopVectorizer vectorizes loops which contain only one basic
245 /// block to a specified vectorization factor (VF).
246 /// This class performs the widening of scalars into vectors, or multiple
247 /// scalars. This class also implements the following features:
248 /// * It inserts an epilogue loop for handling loops that don't have iteration
249 ///   counts that are known to be a multiple of the vectorization factor.
250 /// * It handles the code generation for reduction variables.
251 /// * Scalarization (implementation using scalars) of un-vectorizable
252 ///   instructions.
253 /// InnerLoopVectorizer does not perform any vectorization-legality
254 /// checks, and relies on the caller to check for the different legality
255 /// aspects. The InnerLoopVectorizer relies on the
256 /// LoopVectorizationLegality class to provide information about the induction
257 /// and reduction variables that were found to a given vectorization factor.
258 class InnerLoopVectorizer {
259 public:
260   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
261                       DominatorTree *DT, const DataLayout *DL,
262                       const TargetLibraryInfo *TLI, unsigned VecWidth,
263                       unsigned UnrollFactor)
264       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
265         VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
266         Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
267         Legal(nullptr) {}
268
269   // Perform the actual loop widening (vectorization).
270   void vectorize(LoopVectorizationLegality *L) {
271     Legal = L;
272     // Create a new empty loop. Unlink the old loop and connect the new one.
273     createEmptyLoop();
274     // Widen each instruction in the old loop to a new one in the new loop.
275     // Use the Legality module to find the induction and reduction variables.
276     vectorizeLoop();
277     // Register the new loop and update the analysis passes.
278     updateAnalysis();
279   }
280
281   virtual ~InnerLoopVectorizer() {}
282
283 protected:
284   /// A small list of PHINodes.
285   typedef SmallVector<PHINode*, 4> PhiVector;
286   /// When we unroll loops we have multiple vector values for each scalar.
287   /// This data structure holds the unrolled and vectorized values that
288   /// originated from one scalar instruction.
289   typedef SmallVector<Value*, 2> VectorParts;
290
291   // When we if-convert we need create edge masks. We have to cache values so
292   // that we don't end up with exponential recursion/IR.
293   typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
294                    VectorParts> EdgeMaskCache;
295
296   /// \brief Add code that checks at runtime if the accessed arrays overlap.
297   ///
298   /// Returns a pair of instructions where the first element is the first
299   /// instruction generated in possibly a sequence of instructions and the
300   /// second value is the final comparator value or NULL if no check is needed.
301   std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
302
303   /// \brief Add checks for strides that where assumed to be 1.
304   ///
305   /// Returns the last check instruction and the first check instruction in the
306   /// pair as (first, last).
307   std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
308
309   /// Create an empty loop, based on the loop ranges of the old loop.
310   void createEmptyLoop();
311   /// Copy and widen the instructions from the old loop.
312   virtual void vectorizeLoop();
313
314   /// \brief The Loop exit block may have single value PHI nodes where the
315   /// incoming value is 'Undef'. While vectorizing we only handled real values
316   /// that were defined inside the loop. Here we fix the 'undef case'.
317   /// See PR14725.
318   void fixLCSSAPHIs();
319
320   /// A helper function that computes the predicate of the block BB, assuming
321   /// that the header block of the loop is set to True. It returns the *entry*
322   /// mask for the block BB.
323   VectorParts createBlockInMask(BasicBlock *BB);
324   /// A helper function that computes the predicate of the edge between SRC
325   /// and DST.
326   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
327
328   /// A helper function to vectorize a single BB within the innermost loop.
329   void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
330
331   /// Vectorize a single PHINode in a block. This method handles the induction
332   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
333   /// arbitrary length vectors.
334   void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
335                            unsigned UF, unsigned VF, PhiVector *PV);
336
337   /// Insert the new loop to the loop hierarchy and pass manager
338   /// and update the analysis passes.
339   void updateAnalysis();
340
341   /// This instruction is un-vectorizable. Implement it as a sequence
342   /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
343   /// scalarized instruction behind an if block predicated on the control
344   /// dependence of the instruction.
345   virtual void scalarizeInstruction(Instruction *Instr,
346                                     bool IfPredicateStore=false);
347
348   /// Vectorize Load and Store instructions,
349   virtual void vectorizeMemoryInstruction(Instruction *Instr);
350
351   /// Create a broadcast instruction. This method generates a broadcast
352   /// instruction (shuffle) for loop invariant values and for the induction
353   /// value. If this is the induction variable then we extend it to N, N+1, ...
354   /// this is needed because each iteration in the loop corresponds to a SIMD
355   /// element.
356   virtual Value *getBroadcastInstrs(Value *V);
357
358   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
359   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
360   /// The sequence starts at StartIndex.
361   virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
362
363   /// When we go over instructions in the basic block we rely on previous
364   /// values within the current basic block or on loop invariant values.
365   /// When we widen (vectorize) values we place them in the map. If the values
366   /// are not within the map, they have to be loop invariant, so we simply
367   /// broadcast them into a vector.
368   VectorParts &getVectorValue(Value *V);
369
370   /// Generate a shuffle sequence that will reverse the vector Vec.
371   virtual Value *reverseVector(Value *Vec);
372
373   /// This is a helper class that holds the vectorizer state. It maps scalar
374   /// instructions to vector instructions. When the code is 'unrolled' then
375   /// then a single scalar value is mapped to multiple vector parts. The parts
376   /// are stored in the VectorPart type.
377   struct ValueMap {
378     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
379     /// are mapped.
380     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
381
382     /// \return True if 'Key' is saved in the Value Map.
383     bool has(Value *Key) const { return MapStorage.count(Key); }
384
385     /// Initializes a new entry in the map. Sets all of the vector parts to the
386     /// save value in 'Val'.
387     /// \return A reference to a vector with splat values.
388     VectorParts &splat(Value *Key, Value *Val) {
389       VectorParts &Entry = MapStorage[Key];
390       Entry.assign(UF, Val);
391       return Entry;
392     }
393
394     ///\return A reference to the value that is stored at 'Key'.
395     VectorParts &get(Value *Key) {
396       VectorParts &Entry = MapStorage[Key];
397       if (Entry.empty())
398         Entry.resize(UF);
399       assert(Entry.size() == UF);
400       return Entry;
401     }
402
403   private:
404     /// The unroll factor. Each entry in the map stores this number of vector
405     /// elements.
406     unsigned UF;
407
408     /// Map storage. We use std::map and not DenseMap because insertions to a
409     /// dense map invalidates its iterators.
410     std::map<Value *, VectorParts> MapStorage;
411   };
412
413   /// The original loop.
414   Loop *OrigLoop;
415   /// Scev analysis to use.
416   ScalarEvolution *SE;
417   /// Loop Info.
418   LoopInfo *LI;
419   /// Dominator Tree.
420   DominatorTree *DT;
421   /// Alias Analysis.
422   AliasAnalysis *AA;
423   /// Data Layout.
424   const DataLayout *DL;
425   /// Target Library Info.
426   const TargetLibraryInfo *TLI;
427
428   /// The vectorization SIMD factor to use. Each vector will have this many
429   /// vector elements.
430   unsigned VF;
431
432 protected:
433   /// The vectorization unroll factor to use. Each scalar is vectorized to this
434   /// many different vector instructions.
435   unsigned UF;
436
437   /// The builder that we use
438   IRBuilder<> Builder;
439
440   // --- Vectorization state ---
441
442   /// The vector-loop preheader.
443   BasicBlock *LoopVectorPreHeader;
444   /// The scalar-loop preheader.
445   BasicBlock *LoopScalarPreHeader;
446   /// Middle Block between the vector and the scalar.
447   BasicBlock *LoopMiddleBlock;
448   ///The ExitBlock of the scalar loop.
449   BasicBlock *LoopExitBlock;
450   ///The vector loop body.
451   SmallVector<BasicBlock *, 4> LoopVectorBody;
452   ///The scalar loop body.
453   BasicBlock *LoopScalarBody;
454   /// A list of all bypass blocks. The first block is the entry of the loop.
455   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
456
457   /// The new Induction variable which was added to the new block.
458   PHINode *Induction;
459   /// The induction variable of the old basic block.
460   PHINode *OldInduction;
461   /// Holds the extended (to the widest induction type) start index.
462   Value *ExtendedIdx;
463   /// Maps scalars to widened vectors.
464   ValueMap WidenMap;
465   EdgeMaskCache MaskCache;
466
467   LoopVectorizationLegality *Legal;
468 };
469
470 class InnerLoopUnroller : public InnerLoopVectorizer {
471 public:
472   InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
473                     DominatorTree *DT, const DataLayout *DL,
474                     const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
475     InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
476
477 private:
478   void scalarizeInstruction(Instruction *Instr,
479                             bool IfPredicateStore = false) override;
480   void vectorizeMemoryInstruction(Instruction *Instr) override;
481   Value *getBroadcastInstrs(Value *V) override;
482   Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
483   Value *reverseVector(Value *Vec) override;
484 };
485
486 /// \brief Look for a meaningful debug location on the instruction or it's
487 /// operands.
488 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
489   if (!I)
490     return I;
491
492   DebugLoc Empty;
493   if (I->getDebugLoc() != Empty)
494     return I;
495
496   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
497     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
498       if (OpInst->getDebugLoc() != Empty)
499         return OpInst;
500   }
501
502   return I;
503 }
504
505 /// \brief Set the debug location in the builder using the debug location in the
506 /// instruction.
507 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
508   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
509     B.SetCurrentDebugLocation(Inst->getDebugLoc());
510   else
511     B.SetCurrentDebugLocation(DebugLoc());
512 }
513
514 #ifndef NDEBUG
515 /// \return string containing a file name and a line # for the given loop.
516 static std::string getDebugLocString(const Loop *L) {
517   std::string Result;
518   if (L) {
519     raw_string_ostream OS(Result);
520     const DebugLoc LoopDbgLoc = L->getStartLoc();
521     if (!LoopDbgLoc.isUnknown())
522       LoopDbgLoc.print(L->getHeader()->getContext(), OS);
523     else
524       // Just print the module name.
525       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
526     OS.flush();
527   }
528   return Result;
529 }
530 #endif
531
532 /// \brief Propagate known metadata from one instruction to another.
533 static void propagateMetadata(Instruction *To, const Instruction *From) {
534   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
535   From->getAllMetadataOtherThanDebugLoc(Metadata);
536
537   for (auto M : Metadata) {
538     unsigned Kind = M.first;
539
540     // These are safe to transfer (this is safe for TBAA, even when we
541     // if-convert, because should that metadata have had a control dependency
542     // on the condition, and thus actually aliased with some other
543     // non-speculated memory access when the condition was false, this would be
544     // caught by the runtime overlap checks).
545     if (Kind != LLVMContext::MD_tbaa &&
546         Kind != LLVMContext::MD_alias_scope &&
547         Kind != LLVMContext::MD_noalias &&
548         Kind != LLVMContext::MD_fpmath)
549       continue;
550
551     To->setMetadata(Kind, M.second);
552   }
553 }
554
555 /// \brief Propagate known metadata from one instruction to a vector of others.
556 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
557   for (Value *V : To)
558     if (Instruction *I = dyn_cast<Instruction>(V))
559       propagateMetadata(I, From);
560 }
561
562 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
563 /// to what vectorization factor.
564 /// This class does not look at the profitability of vectorization, only the
565 /// legality. This class has two main kinds of checks:
566 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
567 ///   will change the order of memory accesses in a way that will change the
568 ///   correctness of the program.
569 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
570 /// checks for a number of different conditions, such as the availability of a
571 /// single induction variable, that all types are supported and vectorize-able,
572 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
573 /// This class is also used by InnerLoopVectorizer for identifying
574 /// induction variable and the different reduction variables.
575 class LoopVectorizationLegality {
576 public:
577   unsigned NumLoads;
578   unsigned NumStores;
579   unsigned NumPredStores;
580
581   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
582                             DominatorTree *DT, TargetLibraryInfo *TLI,
583                             AliasAnalysis *AA, Function *F)
584       : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
585         DT(DT), TLI(TLI), AA(AA), TheFunction(F), Induction(nullptr),
586         WidestIndTy(nullptr), HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {
587   }
588
589   /// This enum represents the kinds of reductions that we support.
590   enum ReductionKind {
591     RK_NoReduction, ///< Not a reduction.
592     RK_IntegerAdd,  ///< Sum of integers.
593     RK_IntegerMult, ///< Product of integers.
594     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
595     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
596     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
597     RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
598     RK_FloatAdd,    ///< Sum of floats.
599     RK_FloatMult,   ///< Product of floats.
600     RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
601   };
602
603   /// This enum represents the kinds of inductions that we support.
604   enum InductionKind {
605     IK_NoInduction,         ///< Not an induction variable.
606     IK_IntInduction,        ///< Integer induction variable. Step = 1.
607     IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
608     IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
609     IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
610   };
611
612   // This enum represents the kind of minmax reduction.
613   enum MinMaxReductionKind {
614     MRK_Invalid,
615     MRK_UIntMin,
616     MRK_UIntMax,
617     MRK_SIntMin,
618     MRK_SIntMax,
619     MRK_FloatMin,
620     MRK_FloatMax
621   };
622
623   /// This struct holds information about reduction variables.
624   struct ReductionDescriptor {
625     ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
626       Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
627
628     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
629                         MinMaxReductionKind MK)
630         : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
631
632     // The starting value of the reduction.
633     // It does not have to be zero!
634     TrackingVH<Value> StartValue;
635     // The instruction who's value is used outside the loop.
636     Instruction *LoopExitInstr;
637     // The kind of the reduction.
638     ReductionKind Kind;
639     // If this a min/max reduction the kind of reduction.
640     MinMaxReductionKind MinMaxKind;
641   };
642
643   /// This POD struct holds information about a potential reduction operation.
644   struct ReductionInstDesc {
645     ReductionInstDesc(bool IsRedux, Instruction *I) :
646       IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
647
648     ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
649       IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
650
651     // Is this instruction a reduction candidate.
652     bool IsReduction;
653     // The last instruction in a min/max pattern (select of the select(icmp())
654     // pattern), or the current reduction instruction otherwise.
655     Instruction *PatternLastInst;
656     // If this is a min/max pattern the comparison predicate.
657     MinMaxReductionKind MinMaxKind;
658   };
659
660   /// This struct holds information about the memory runtime legality
661   /// check that a group of pointers do not overlap.
662   struct RuntimePointerCheck {
663     RuntimePointerCheck() : Need(false) {}
664
665     /// Reset the state of the pointer runtime information.
666     void reset() {
667       Need = false;
668       Pointers.clear();
669       Starts.clear();
670       Ends.clear();
671       IsWritePtr.clear();
672       DependencySetId.clear();
673       AliasSetId.clear();
674     }
675
676     /// Insert a pointer and calculate the start and end SCEVs.
677     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
678                 unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
679
680     /// This flag indicates if we need to add the runtime check.
681     bool Need;
682     /// Holds the pointers that we need to check.
683     SmallVector<TrackingVH<Value>, 2> Pointers;
684     /// Holds the pointer value at the beginning of the loop.
685     SmallVector<const SCEV*, 2> Starts;
686     /// Holds the pointer value at the end of the loop.
687     SmallVector<const SCEV*, 2> Ends;
688     /// Holds the information if this pointer is used for writing to memory.
689     SmallVector<bool, 2> IsWritePtr;
690     /// Holds the id of the set of pointers that could be dependent because of a
691     /// shared underlying object.
692     SmallVector<unsigned, 2> DependencySetId;
693     /// Holds the id of the disjoint alias set to which this pointer belongs.
694     SmallVector<unsigned, 2> AliasSetId;
695   };
696
697   /// A struct for saving information about induction variables.
698   struct InductionInfo {
699     InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
700     InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
701     /// Start value.
702     TrackingVH<Value> StartValue;
703     /// Induction kind.
704     InductionKind IK;
705   };
706
707   /// ReductionList contains the reduction descriptors for all
708   /// of the reductions that were found in the loop.
709   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
710
711   /// InductionList saves induction variables and maps them to the
712   /// induction descriptor.
713   typedef MapVector<PHINode*, InductionInfo> InductionList;
714
715   /// Returns true if it is legal to vectorize this loop.
716   /// This does not mean that it is profitable to vectorize this
717   /// loop, only that it is legal to do so.
718   bool canVectorize();
719
720   /// Returns the Induction variable.
721   PHINode *getInduction() { return Induction; }
722
723   /// Returns the reduction variables found in the loop.
724   ReductionList *getReductionVars() { return &Reductions; }
725
726   /// Returns the induction variables found in the loop.
727   InductionList *getInductionVars() { return &Inductions; }
728
729   /// Returns the widest induction type.
730   Type *getWidestInductionType() { return WidestIndTy; }
731
732   /// Returns True if V is an induction variable in this loop.
733   bool isInductionVariable(const Value *V);
734
735   /// Return true if the block BB needs to be predicated in order for the loop
736   /// to be vectorized.
737   bool blockNeedsPredication(BasicBlock *BB);
738
739   /// Check if this  pointer is consecutive when vectorizing. This happens
740   /// when the last index of the GEP is the induction variable, or that the
741   /// pointer itself is an induction variable.
742   /// This check allows us to vectorize A[idx] into a wide load/store.
743   /// Returns:
744   /// 0 - Stride is unknown or non-consecutive.
745   /// 1 - Address is consecutive.
746   /// -1 - Address is consecutive, and decreasing.
747   int isConsecutivePtr(Value *Ptr);
748
749   /// Returns true if the value V is uniform within the loop.
750   bool isUniform(Value *V);
751
752   /// Returns true if this instruction will remain scalar after vectorization.
753   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
754
755   /// Returns the information that we collected about runtime memory check.
756   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
757
758   /// This function returns the identity element (or neutral element) for
759   /// the operation K.
760   static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
761
762   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
763
764   bool hasStride(Value *V) { return StrideSet.count(V); }
765   bool mustCheckStrides() { return !StrideSet.empty(); }
766   SmallPtrSet<Value *, 8>::iterator strides_begin() {
767     return StrideSet.begin();
768   }
769   SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
770
771 private:
772   /// Check if a single basic block loop is vectorizable.
773   /// At this point we know that this is a loop with a constant trip count
774   /// and we only need to check individual instructions.
775   bool canVectorizeInstrs();
776
777   /// When we vectorize loops we may change the order in which
778   /// we read and write from memory. This method checks if it is
779   /// legal to vectorize the code, considering only memory constrains.
780   /// Returns true if the loop is vectorizable
781   bool canVectorizeMemory();
782
783   /// Return true if we can vectorize this loop using the IF-conversion
784   /// transformation.
785   bool canVectorizeWithIfConvert();
786
787   /// Collect the variables that need to stay uniform after vectorization.
788   void collectLoopUniforms();
789
790   /// Return true if all of the instructions in the block can be speculatively
791   /// executed. \p SafePtrs is a list of addresses that are known to be legal
792   /// and we know that we can read from them without segfault.
793   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
794
795   /// Returns True, if 'Phi' is the kind of reduction variable for type
796   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
797   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
798   /// Returns a struct describing if the instruction 'I' can be a reduction
799   /// variable of type 'Kind'. If the reduction is a min/max pattern of
800   /// select(icmp()) this function advances the instruction pointer 'I' from the
801   /// compare instruction to the select instruction and stores this pointer in
802   /// 'PatternLastInst' member of the returned struct.
803   ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
804                                      ReductionInstDesc &Desc);
805   /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
806   /// pattern corresponding to a min(X, Y) or max(X, Y).
807   static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
808                                                     ReductionInstDesc &Prev);
809   /// Returns the induction kind of Phi. This function may return NoInduction
810   /// if the PHI is not an induction variable.
811   InductionKind isInductionVariable(PHINode *Phi);
812
813   /// \brief Collect memory access with loop invariant strides.
814   ///
815   /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
816   /// invariant.
817   void collectStridedAcccess(Value *LoadOrStoreInst);
818
819   /// Report an analysis message to assist the user in diagnosing loops that are
820   /// not vectorized.
821   void emitAnalysis(Report &Message) {
822     DebugLoc DL = TheLoop->getStartLoc();
823     if (Instruction *I = Message.getInstr())
824       DL = I->getDebugLoc();
825     emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
826                                    *TheFunction, DL, Message.str());
827   }
828
829   /// The loop that we evaluate.
830   Loop *TheLoop;
831   /// Scev analysis.
832   ScalarEvolution *SE;
833   /// DataLayout analysis.
834   const DataLayout *DL;
835   /// Dominators.
836   DominatorTree *DT;
837   /// Target Library Info.
838   TargetLibraryInfo *TLI;
839   /// Alias analysis.
840   AliasAnalysis *AA;
841   /// Parent function
842   Function *TheFunction;
843
844   //  ---  vectorization state --- //
845
846   /// Holds the integer induction variable. This is the counter of the
847   /// loop.
848   PHINode *Induction;
849   /// Holds the reduction variables.
850   ReductionList Reductions;
851   /// Holds all of the induction variables that we found in the loop.
852   /// Notice that inductions don't need to start at zero and that induction
853   /// variables can be pointers.
854   InductionList Inductions;
855   /// Holds the widest induction type encountered.
856   Type *WidestIndTy;
857
858   /// Allowed outside users. This holds the reduction
859   /// vars which can be accessed from outside the loop.
860   SmallPtrSet<Value*, 4> AllowedExit;
861   /// This set holds the variables which are known to be uniform after
862   /// vectorization.
863   SmallPtrSet<Instruction*, 4> Uniforms;
864   /// We need to check that all of the pointers in this list are disjoint
865   /// at runtime.
866   RuntimePointerCheck PtrRtCheck;
867   /// Can we assume the absence of NaNs.
868   bool HasFunNoNaNAttr;
869
870   unsigned MaxSafeDepDistBytes;
871
872   ValueToValueMap Strides;
873   SmallPtrSet<Value *, 8> StrideSet;
874 };
875
876 /// LoopVectorizationCostModel - estimates the expected speedups due to
877 /// vectorization.
878 /// In many cases vectorization is not profitable. This can happen because of
879 /// a number of reasons. In this class we mainly attempt to predict the
880 /// expected speedup/slowdowns due to the supported instruction set. We use the
881 /// TargetTransformInfo to query the different backends for the cost of
882 /// different operations.
883 class LoopVectorizationCostModel {
884 public:
885   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
886                              LoopVectorizationLegality *Legal,
887                              const TargetTransformInfo &TTI,
888                              const DataLayout *DL, const TargetLibraryInfo *TLI,
889                              AssumptionTracker *AT, const Function *F,
890                              const LoopVectorizeHints *Hints)
891       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
892         AT(AT), TheFunction(F), Hints(Hints) {
893     CodeMetrics::collectEphemeralValues(L, AT, EphValues);
894   }
895
896   /// Information about vectorization costs
897   struct VectorizationFactor {
898     unsigned Width; // Vector width with best cost
899     unsigned Cost; // Cost of the loop with that width
900   };
901   /// \return The most profitable vectorization factor and the cost of that VF.
902   /// This method checks every power of two up to VF. If UserVF is not ZERO
903   /// then this vectorization factor will be selected if vectorization is
904   /// possible.
905   VectorizationFactor selectVectorizationFactor(bool OptForSize);
906
907   /// \return The size (in bits) of the widest type in the code that
908   /// needs to be vectorized. We ignore values that remain scalar such as
909   /// 64 bit loop indices.
910   unsigned getWidestType();
911
912   /// \return The most profitable unroll factor.
913   /// If UserUF is non-zero then this method finds the best unroll-factor
914   /// based on register pressure and other parameters.
915   /// VF and LoopCost are the selected vectorization factor and the cost of the
916   /// selected VF.
917   unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
918
919   /// \brief A struct that represents some properties of the register usage
920   /// of a loop.
921   struct RegisterUsage {
922     /// Holds the number of loop invariant values that are used in the loop.
923     unsigned LoopInvariantRegs;
924     /// Holds the maximum number of concurrent live intervals in the loop.
925     unsigned MaxLocalUsers;
926     /// Holds the number of instructions in the loop.
927     unsigned NumInstructions;
928   };
929
930   /// \return  information about the register usage of the loop.
931   RegisterUsage calculateRegisterUsage();
932
933 private:
934   /// Returns the expected execution cost. The unit of the cost does
935   /// not matter because we use the 'cost' units to compare different
936   /// vector widths. The cost that is returned is *not* normalized by
937   /// the factor width.
938   unsigned expectedCost(unsigned VF);
939
940   /// Returns the execution time cost of an instruction for a given vector
941   /// width. Vector width of one means scalar.
942   unsigned getInstructionCost(Instruction *I, unsigned VF);
943
944   /// A helper function for converting Scalar types to vector types.
945   /// If the incoming type is void, we return void. If the VF is 1, we return
946   /// the scalar type.
947   static Type* ToVectorTy(Type *Scalar, unsigned VF);
948
949   /// Returns whether the instruction is a load or store and will be a emitted
950   /// as a vector operation.
951   bool isConsecutiveLoadOrStore(Instruction *I);
952
953   /// Report an analysis message to assist the user in diagnosing loops that are
954   /// not vectorized.
955   void emitAnalysis(Report &Message) {
956     DebugLoc DL = TheLoop->getStartLoc();
957     if (Instruction *I = Message.getInstr())
958       DL = I->getDebugLoc();
959     emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
960                                    *TheFunction, DL, Message.str());
961   }
962
963   /// Values used only by @llvm.assume calls.
964   SmallPtrSet<const Value *, 32> EphValues;
965
966   /// The loop that we evaluate.
967   Loop *TheLoop;
968   /// Scev analysis.
969   ScalarEvolution *SE;
970   /// Loop Info analysis.
971   LoopInfo *LI;
972   /// Vectorization legality.
973   LoopVectorizationLegality *Legal;
974   /// Vector target information.
975   const TargetTransformInfo &TTI;
976   /// Target data layout information.
977   const DataLayout *DL;
978   /// Target Library Info.
979   const TargetLibraryInfo *TLI;
980   /// Tracker for @llvm.assume.
981   AssumptionTracker *AT;
982   const Function *TheFunction;
983   // Loop Vectorize Hint.
984   const LoopVectorizeHints *Hints;
985 };
986
987 /// Utility class for getting and setting loop vectorizer hints in the form
988 /// of loop metadata.
989 /// This class keeps a number of loop annotations locally (as member variables)
990 /// and can, upon request, write them back as metadata on the loop. It will
991 /// initially scan the loop for existing metadata, and will update the local
992 /// values based on information in the loop.
993 /// We cannot write all values to metadata, as the mere presence of some info,
994 /// for example 'force', means a decision has been made. So, we need to be
995 /// careful NOT to add them if the user hasn't specifically asked so.
996 class LoopVectorizeHints {
997   enum HintKind {
998     HK_WIDTH,
999     HK_UNROLL,
1000     HK_FORCE
1001   };
1002
1003   /// Hint - associates name and validation with the hint value.
1004   struct Hint {
1005     const char * Name;
1006     unsigned Value; // This may have to change for non-numeric values.
1007     HintKind Kind;
1008
1009     Hint(const char * Name, unsigned Value, HintKind Kind)
1010       : Name(Name), Value(Value), Kind(Kind) { }
1011
1012     bool validate(unsigned Val) {
1013       switch (Kind) {
1014       case HK_WIDTH:
1015         return isPowerOf2_32(Val) && Val <= MaxVectorWidth;
1016       case HK_UNROLL:
1017         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1018       case HK_FORCE:
1019         return (Val <= 1);
1020       }
1021       return false;
1022     }
1023   };
1024
1025   /// Vectorization width.
1026   Hint Width;
1027   /// Vectorization interleave factor.
1028   Hint Interleave;
1029   /// Vectorization forced
1030   Hint Force;
1031   /// Array to help iterating through all hints.
1032   Hint *Hints[3]; // avoiding initialisation due to MSVC2012
1033
1034   /// Return the loop metadata prefix.
1035   static StringRef Prefix() { return "llvm.loop."; }
1036
1037 public:
1038   enum ForceKind {
1039     FK_Undefined = -1, ///< Not selected.
1040     FK_Disabled = 0,   ///< Forcing disabled.
1041     FK_Enabled = 1,    ///< Forcing enabled.
1042   };
1043
1044   LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1045       : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
1046         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1047         Force("vectorize.enable", FK_Undefined, HK_FORCE),
1048         TheLoop(L) {
1049     // FIXME: Move this up initialisation when MSVC requirement is 2013+
1050     Hints[0] = &Width;
1051     Hints[1] = &Interleave;
1052     Hints[2] = &Force;
1053
1054     // Populate values with existing loop metadata.
1055     getHintsFromMetadata();
1056
1057     // force-vector-interleave overrides DisableInterleaving.
1058     if (VectorizationInterleave.getNumOccurrences() > 0)
1059       Interleave.Value = VectorizationInterleave;
1060
1061     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1062           << "LV: Interleaving disabled by the pass manager\n");
1063   }
1064
1065   /// Mark the loop L as already vectorized by setting the width to 1.
1066   void setAlreadyVectorized() {
1067     Width.Value = Interleave.Value = 1;
1068     // FIXME: Change all lines below for this when we can use MSVC 2013+
1069     //writeHintsToMetadata({ Width, Unroll });
1070     std::vector<Hint> hints;
1071     hints.reserve(2);
1072     hints.emplace_back(Width);
1073     hints.emplace_back(Interleave);
1074     writeHintsToMetadata(std::move(hints));
1075   }
1076
1077   /// Dumps all the hint information.
1078   std::string emitRemark() const {
1079     Report R;
1080     if (Force.Value == LoopVectorizeHints::FK_Disabled)
1081       R << "vectorization is explicitly disabled";
1082     else {
1083       R << "use -Rpass-analysis=loop-vectorize for more info";
1084       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1085         R << " (Force=true";
1086         if (Width.Value != 0)
1087           R << ", Vector Width=" << Width.Value;
1088         if (Interleave.Value != 0)
1089           R << ", Interleave Count=" << Interleave.Value;
1090         R << ")";
1091       }
1092     }
1093
1094     return R.str();
1095   }
1096
1097   unsigned getWidth() const { return Width.Value; }
1098   unsigned getInterleave() const { return Interleave.Value; }
1099   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1100
1101 private:
1102   /// Find hints specified in the loop metadata and update local values.
1103   void getHintsFromMetadata() {
1104     MDNode *LoopID = TheLoop->getLoopID();
1105     if (!LoopID)
1106       return;
1107
1108     // First operand should refer to the loop id itself.
1109     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1110     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1111
1112     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1113       const MDString *S = nullptr;
1114       SmallVector<Value*, 4> Args;
1115
1116       // The expected hint is either a MDString or a MDNode with the first
1117       // operand a MDString.
1118       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1119         if (!MD || MD->getNumOperands() == 0)
1120           continue;
1121         S = dyn_cast<MDString>(MD->getOperand(0));
1122         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1123           Args.push_back(MD->getOperand(i));
1124       } else {
1125         S = dyn_cast<MDString>(LoopID->getOperand(i));
1126         assert(Args.size() == 0 && "too many arguments for MDString");
1127       }
1128
1129       if (!S)
1130         continue;
1131
1132       // Check if the hint starts with the loop metadata prefix.
1133       StringRef Name = S->getString();
1134       if (Args.size() == 1)
1135         setHint(Name, Args[0]);
1136     }
1137   }
1138
1139   /// Checks string hint with one operand and set value if valid.
1140   void setHint(StringRef Name, Value *Arg) {
1141     if (!Name.startswith(Prefix()))
1142       return;
1143     Name = Name.substr(Prefix().size(), StringRef::npos);
1144
1145     const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
1146     if (!C) return;
1147     unsigned Val = C->getZExtValue();
1148
1149     for (auto H : Hints) {
1150       if (Name == H->Name) {
1151         if (H->validate(Val))
1152           H->Value = Val;
1153         else
1154           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1155         break;
1156       }
1157     }
1158   }
1159
1160   /// Create a new hint from name / value pair.
1161   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1162     LLVMContext &Context = TheLoop->getHeader()->getContext();
1163     SmallVector<Value*, 2> Vals;
1164     Vals.push_back(MDString::get(Context, Name));
1165     Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
1166     return MDNode::get(Context, Vals);
1167   }
1168
1169   /// Matches metadata with hint name.
1170   bool matchesHintMetadataName(MDNode *Node, std::vector<Hint> &HintTypes) {
1171     MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1172     if (!Name)
1173       return false;
1174
1175     for (auto H : HintTypes)
1176       if (Name->getName().endswith(H.Name))
1177         return true;
1178     return false;
1179   }
1180
1181   /// Sets current hints into loop metadata, keeping other values intact.
1182   void writeHintsToMetadata(std::vector<Hint> HintTypes) {
1183     if (HintTypes.size() == 0)
1184       return;
1185
1186     // Reserve the first element to LoopID (see below).
1187     SmallVector<Value*, 4> Vals(1);
1188     // If the loop already has metadata, then ignore the existing operands.
1189     MDNode *LoopID = TheLoop->getLoopID();
1190     if (LoopID) {
1191       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1192         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1193         // If node in update list, ignore old value.
1194         if (!matchesHintMetadataName(Node, HintTypes))
1195           Vals.push_back(Node);
1196       }
1197     }
1198
1199     // Now, add the missing hints.
1200     for (auto H : HintTypes)
1201       Vals.push_back(
1202           createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1203
1204     // Replace current metadata node with new one.
1205     LLVMContext &Context = TheLoop->getHeader()->getContext();
1206     MDNode *NewLoopID = MDNode::get(Context, Vals);
1207     // Set operand 0 to refer to the loop id itself.
1208     NewLoopID->replaceOperandWith(0, NewLoopID);
1209
1210     TheLoop->setLoopID(NewLoopID);
1211     if (LoopID)
1212       LoopID->replaceAllUsesWith(NewLoopID);
1213     LoopID = NewLoopID;
1214   }
1215
1216   /// The loop these hints belong to.
1217   const Loop *TheLoop;
1218 };
1219
1220 static void emitMissedWarning(Function *F, Loop *L,
1221                               const LoopVectorizeHints &LH) {
1222   emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1223                                L->getStartLoc(), LH.emitRemark());
1224
1225   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1226     if (LH.getWidth() != 1)
1227       emitLoopVectorizeWarning(
1228           F->getContext(), *F, L->getStartLoc(),
1229           "failed explicitly specified loop vectorization");
1230     else if (LH.getInterleave() != 1)
1231       emitLoopInterleaveWarning(
1232           F->getContext(), *F, L->getStartLoc(),
1233           "failed explicitly specified loop interleaving");
1234   }
1235 }
1236
1237 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1238   if (L.empty())
1239     return V.push_back(&L);
1240
1241   for (Loop *InnerL : L)
1242     addInnerLoop(*InnerL, V);
1243 }
1244
1245 /// The LoopVectorize Pass.
1246 struct LoopVectorize : public FunctionPass {
1247   /// Pass identification, replacement for typeid
1248   static char ID;
1249
1250   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1251     : FunctionPass(ID),
1252       DisableUnrolling(NoUnrolling),
1253       AlwaysVectorize(AlwaysVectorize) {
1254     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1255   }
1256
1257   ScalarEvolution *SE;
1258   const DataLayout *DL;
1259   LoopInfo *LI;
1260   TargetTransformInfo *TTI;
1261   DominatorTree *DT;
1262   BlockFrequencyInfo *BFI;
1263   TargetLibraryInfo *TLI;
1264   AliasAnalysis *AA;
1265   AssumptionTracker *AT;
1266   bool DisableUnrolling;
1267   bool AlwaysVectorize;
1268
1269   BlockFrequency ColdEntryFreq;
1270
1271   bool runOnFunction(Function &F) override {
1272     SE = &getAnalysis<ScalarEvolution>();
1273     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1274     DL = DLP ? &DLP->getDataLayout() : nullptr;
1275     LI = &getAnalysis<LoopInfo>();
1276     TTI = &getAnalysis<TargetTransformInfo>();
1277     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1278     BFI = &getAnalysis<BlockFrequencyInfo>();
1279     TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1280     AA = &getAnalysis<AliasAnalysis>();
1281     AT = &getAnalysis<AssumptionTracker>();
1282
1283     // Compute some weights outside of the loop over the loops. Compute this
1284     // using a BranchProbability to re-use its scaling math.
1285     const BranchProbability ColdProb(1, 5); // 20%
1286     ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1287
1288     // If the target claims to have no vector registers don't attempt
1289     // vectorization.
1290     if (!TTI->getNumberOfRegisters(true))
1291       return false;
1292
1293     if (!DL) {
1294       DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1295                    << ": Missing data layout\n");
1296       return false;
1297     }
1298
1299     // Build up a worklist of inner-loops to vectorize. This is necessary as
1300     // the act of vectorizing or partially unrolling a loop creates new loops
1301     // and can invalidate iterators across the loops.
1302     SmallVector<Loop *, 8> Worklist;
1303
1304     for (Loop *L : *LI)
1305       addInnerLoop(*L, Worklist);
1306
1307     LoopsAnalyzed += Worklist.size();
1308
1309     // Now walk the identified inner loops.
1310     bool Changed = false;
1311     while (!Worklist.empty())
1312       Changed |= processLoop(Worklist.pop_back_val());
1313
1314     // Process each loop nest in the function.
1315     return Changed;
1316   }
1317
1318   bool processLoop(Loop *L) {
1319     assert(L->empty() && "Only process inner loops.");
1320
1321 #ifndef NDEBUG
1322     const std::string DebugLocStr = getDebugLocString(L);
1323 #endif /* NDEBUG */
1324
1325     DEBUG(dbgs() << "\nLV: Checking a loop in \""
1326                  << L->getHeader()->getParent()->getName() << "\" from "
1327                  << DebugLocStr << "\n");
1328
1329     LoopVectorizeHints Hints(L, DisableUnrolling);
1330
1331     DEBUG(dbgs() << "LV: Loop hints:"
1332                  << " force="
1333                  << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1334                          ? "disabled"
1335                          : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1336                                 ? "enabled"
1337                                 : "?")) << " width=" << Hints.getWidth()
1338                  << " unroll=" << Hints.getInterleave() << "\n");
1339
1340     // Function containing loop
1341     Function *F = L->getHeader()->getParent();
1342
1343     // Looking at the diagnostic output is the only way to determine if a loop
1344     // was vectorized (other than looking at the IR or machine code), so it
1345     // is important to generate an optimization remark for each loop. Most of
1346     // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1347     // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1348     // less verbose reporting vectorized loops and unvectorized loops that may
1349     // benefit from vectorization, respectively.
1350
1351     if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1352       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1353       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1354                                      L->getStartLoc(), Hints.emitRemark());
1355       return false;
1356     }
1357
1358     if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1359       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1360       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1361                                      L->getStartLoc(), Hints.emitRemark());
1362       return false;
1363     }
1364
1365     if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1366       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1367       emitOptimizationRemarkAnalysis(
1368           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1369           "loop not vectorized: vector width and interleave count are "
1370           "explicitly set to 1");
1371       return false;
1372     }
1373
1374     // Check the loop for a trip count threshold:
1375     // do not vectorize loops with a tiny trip count.
1376     const unsigned TC = SE->getSmallConstantTripCount(L);
1377     if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1378       DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1379                    << "This loop is not worth vectorizing.");
1380       if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1381         DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1382       else {
1383         DEBUG(dbgs() << "\n");
1384         emitOptimizationRemarkAnalysis(
1385             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1386             "vectorization is not beneficial and is not explicitly forced");
1387         return false;
1388       }
1389     }
1390
1391     // Check if it is legal to vectorize the loop.
1392     LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F);
1393     if (!LVL.canVectorize()) {
1394       DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1395       emitMissedWarning(F, L, Hints);
1396       return false;
1397     }
1398
1399     // Use the cost model.
1400     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AT, F,
1401                                   &Hints);
1402
1403     // Check the function attributes to find out if this function should be
1404     // optimized for size.
1405     bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1406                       F->hasFnAttribute(Attribute::OptimizeForSize);
1407
1408     // Compute the weighted frequency of this loop being executed and see if it
1409     // is less than 20% of the function entry baseline frequency. Note that we
1410     // always have a canonical loop here because we think we *can* vectoriez.
1411     // FIXME: This is hidden behind a flag due to pervasive problems with
1412     // exactly what block frequency models.
1413     if (LoopVectorizeWithBlockFrequency) {
1414       BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1415       if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1416           LoopEntryFreq < ColdEntryFreq)
1417         OptForSize = true;
1418     }
1419
1420     // Check the function attributes to see if implicit floats are allowed.a
1421     // FIXME: This check doesn't seem possibly correct -- what if the loop is
1422     // an integer loop and the vector instructions selected are purely integer
1423     // vector instructions?
1424     if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1425       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1426             "attribute is used.\n");
1427       emitOptimizationRemarkAnalysis(
1428           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1429           "loop not vectorized due to NoImplicitFloat attribute");
1430       emitMissedWarning(F, L, Hints);
1431       return false;
1432     }
1433
1434     // Select the optimal vectorization factor.
1435     const LoopVectorizationCostModel::VectorizationFactor VF =
1436         CM.selectVectorizationFactor(OptForSize);
1437
1438     // Select the unroll factor.
1439     const unsigned UF =
1440         CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1441
1442     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1443                  << DebugLocStr << '\n');
1444     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1445
1446     if (VF.Width == 1) {
1447       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1448
1449       if (UF == 1) {
1450         emitOptimizationRemarkAnalysis(
1451             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1452             "not beneficial to vectorize and user disabled interleaving");
1453         return false;
1454       }
1455       DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1456
1457       // Report the unrolling decision.
1458       emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1459                              Twine("unrolled with interleaving factor " +
1460                                    Twine(UF) +
1461                                    " (vectorization not beneficial)"));
1462
1463       // We decided not to vectorize, but we may want to unroll.
1464
1465       InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1466       Unroller.vectorize(&LVL);
1467     } else {
1468       // If we decided that it is *legal* to vectorize the loop then do it.
1469       InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1470       LB.vectorize(&LVL);
1471       ++LoopsVectorized;
1472
1473       // Report the vectorization decision.
1474       emitOptimizationRemark(
1475           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1476           Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1477               ", unrolling interleave factor: " + Twine(UF) + ")");
1478     }
1479
1480     // Mark the loop as already vectorized to avoid vectorizing again.
1481     Hints.setAlreadyVectorized();
1482
1483     DEBUG(verifyFunction(*L->getHeader()->getParent()));
1484     return true;
1485   }
1486
1487   void getAnalysisUsage(AnalysisUsage &AU) const override {
1488     AU.addRequired<AssumptionTracker>();
1489     AU.addRequiredID(LoopSimplifyID);
1490     AU.addRequiredID(LCSSAID);
1491     AU.addRequired<BlockFrequencyInfo>();
1492     AU.addRequired<DominatorTreeWrapperPass>();
1493     AU.addRequired<LoopInfo>();
1494     AU.addRequired<ScalarEvolution>();
1495     AU.addRequired<TargetTransformInfo>();
1496     AU.addRequired<AliasAnalysis>();
1497     AU.addPreserved<LoopInfo>();
1498     AU.addPreserved<DominatorTreeWrapperPass>();
1499     AU.addPreserved<AliasAnalysis>();
1500   }
1501
1502 };
1503
1504 } // end anonymous namespace
1505
1506 //===----------------------------------------------------------------------===//
1507 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1508 // LoopVectorizationCostModel.
1509 //===----------------------------------------------------------------------===//
1510
1511 static Value *stripIntegerCast(Value *V) {
1512   if (CastInst *CI = dyn_cast<CastInst>(V))
1513     if (CI->getOperand(0)->getType()->isIntegerTy())
1514       return CI->getOperand(0);
1515   return V;
1516 }
1517
1518 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1519 ///
1520 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1521 /// \p Ptr.
1522 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1523                                              ValueToValueMap &PtrToStride,
1524                                              Value *Ptr, Value *OrigPtr = nullptr) {
1525
1526   const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1527
1528   // If there is an entry in the map return the SCEV of the pointer with the
1529   // symbolic stride replaced by one.
1530   ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1531   if (SI != PtrToStride.end()) {
1532     Value *StrideVal = SI->second;
1533
1534     // Strip casts.
1535     StrideVal = stripIntegerCast(StrideVal);
1536
1537     // Replace symbolic stride by one.
1538     Value *One = ConstantInt::get(StrideVal->getType(), 1);
1539     ValueToValueMap RewriteMap;
1540     RewriteMap[StrideVal] = One;
1541
1542     const SCEV *ByOne =
1543         SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1544     DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1545                  << "\n");
1546     return ByOne;
1547   }
1548
1549   // Otherwise, just return the SCEV of the original pointer.
1550   return SE->getSCEV(Ptr);
1551 }
1552
1553 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1554     ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1555     unsigned ASId, ValueToValueMap &Strides) {
1556   // Get the stride replaced scev.
1557   const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1558   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1559   assert(AR && "Invalid addrec expression");
1560   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1561   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1562   Pointers.push_back(Ptr);
1563   Starts.push_back(AR->getStart());
1564   Ends.push_back(ScEnd);
1565   IsWritePtr.push_back(WritePtr);
1566   DependencySetId.push_back(DepSetId);
1567   AliasSetId.push_back(ASId);
1568 }
1569
1570 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1571   // We need to place the broadcast of invariant variables outside the loop.
1572   Instruction *Instr = dyn_cast<Instruction>(V);
1573   bool NewInstr =
1574       (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1575                           Instr->getParent()) != LoopVectorBody.end());
1576   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1577
1578   // Place the code for broadcasting invariant variables in the new preheader.
1579   IRBuilder<>::InsertPointGuard Guard(Builder);
1580   if (Invariant)
1581     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1582
1583   // Broadcast the scalar into all locations in the vector.
1584   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1585
1586   return Shuf;
1587 }
1588
1589 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1590                                                  bool Negate) {
1591   assert(Val->getType()->isVectorTy() && "Must be a vector");
1592   assert(Val->getType()->getScalarType()->isIntegerTy() &&
1593          "Elem must be an integer");
1594   // Create the types.
1595   Type *ITy = Val->getType()->getScalarType();
1596   VectorType *Ty = cast<VectorType>(Val->getType());
1597   int VLen = Ty->getNumElements();
1598   SmallVector<Constant*, 8> Indices;
1599
1600   // Create a vector of consecutive numbers from zero to VF.
1601   for (int i = 0; i < VLen; ++i) {
1602     int64_t Idx = Negate ? (-i) : i;
1603     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1604   }
1605
1606   // Add the consecutive indices to the vector value.
1607   Constant *Cv = ConstantVector::get(Indices);
1608   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1609   return Builder.CreateAdd(Val, Cv, "induction");
1610 }
1611
1612 /// \brief Find the operand of the GEP that should be checked for consecutive
1613 /// stores. This ignores trailing indices that have no effect on the final
1614 /// pointer.
1615 static unsigned getGEPInductionOperand(const DataLayout *DL,
1616                                        const GetElementPtrInst *Gep) {
1617   unsigned LastOperand = Gep->getNumOperands() - 1;
1618   unsigned GEPAllocSize = DL->getTypeAllocSize(
1619       cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1620
1621   // Walk backwards and try to peel off zeros.
1622   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1623     // Find the type we're currently indexing into.
1624     gep_type_iterator GEPTI = gep_type_begin(Gep);
1625     std::advance(GEPTI, LastOperand - 1);
1626
1627     // If it's a type with the same allocation size as the result of the GEP we
1628     // can peel off the zero index.
1629     if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1630       break;
1631     --LastOperand;
1632   }
1633
1634   return LastOperand;
1635 }
1636
1637 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1638   assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1639   // Make sure that the pointer does not point to structs.
1640   if (Ptr->getType()->getPointerElementType()->isAggregateType())
1641     return 0;
1642
1643   // If this value is a pointer induction variable we know it is consecutive.
1644   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1645   if (Phi && Inductions.count(Phi)) {
1646     InductionInfo II = Inductions[Phi];
1647     if (IK_PtrInduction == II.IK)
1648       return 1;
1649     else if (IK_ReversePtrInduction == II.IK)
1650       return -1;
1651   }
1652
1653   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1654   if (!Gep)
1655     return 0;
1656
1657   unsigned NumOperands = Gep->getNumOperands();
1658   Value *GpPtr = Gep->getPointerOperand();
1659   // If this GEP value is a consecutive pointer induction variable and all of
1660   // the indices are constant then we know it is consecutive. We can
1661   Phi = dyn_cast<PHINode>(GpPtr);
1662   if (Phi && Inductions.count(Phi)) {
1663
1664     // Make sure that the pointer does not point to structs.
1665     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1666     if (GepPtrType->getElementType()->isAggregateType())
1667       return 0;
1668
1669     // Make sure that all of the index operands are loop invariant.
1670     for (unsigned i = 1; i < NumOperands; ++i)
1671       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1672         return 0;
1673
1674     InductionInfo II = Inductions[Phi];
1675     if (IK_PtrInduction == II.IK)
1676       return 1;
1677     else if (IK_ReversePtrInduction == II.IK)
1678       return -1;
1679   }
1680
1681   unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1682
1683   // Check that all of the gep indices are uniform except for our induction
1684   // operand.
1685   for (unsigned i = 0; i != NumOperands; ++i)
1686     if (i != InductionOperand &&
1687         !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1688       return 0;
1689
1690   // We can emit wide load/stores only if the last non-zero index is the
1691   // induction variable.
1692   const SCEV *Last = nullptr;
1693   if (!Strides.count(Gep))
1694     Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1695   else {
1696     // Because of the multiplication by a stride we can have a s/zext cast.
1697     // We are going to replace this stride by 1 so the cast is safe to ignore.
1698     //
1699     //  %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1700     //  %0 = trunc i64 %indvars.iv to i32
1701     //  %mul = mul i32 %0, %Stride1
1702     //  %idxprom = zext i32 %mul to i64  << Safe cast.
1703     //  %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1704     //
1705     Last = replaceSymbolicStrideSCEV(SE, Strides,
1706                                      Gep->getOperand(InductionOperand), Gep);
1707     if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1708       Last =
1709           (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1710               ? C->getOperand()
1711               : Last;
1712   }
1713   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1714     const SCEV *Step = AR->getStepRecurrence(*SE);
1715
1716     // The memory is consecutive because the last index is consecutive
1717     // and all other indices are loop invariant.
1718     if (Step->isOne())
1719       return 1;
1720     if (Step->isAllOnesValue())
1721       return -1;
1722   }
1723
1724   return 0;
1725 }
1726
1727 bool LoopVectorizationLegality::isUniform(Value *V) {
1728   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1729 }
1730
1731 InnerLoopVectorizer::VectorParts&
1732 InnerLoopVectorizer::getVectorValue(Value *V) {
1733   assert(V != Induction && "The new induction variable should not be used.");
1734   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1735
1736   // If we have a stride that is replaced by one, do it here.
1737   if (Legal->hasStride(V))
1738     V = ConstantInt::get(V->getType(), 1);
1739
1740   // If we have this scalar in the map, return it.
1741   if (WidenMap.has(V))
1742     return WidenMap.get(V);
1743
1744   // If this scalar is unknown, assume that it is a constant or that it is
1745   // loop invariant. Broadcast V and save the value for future uses.
1746   Value *B = getBroadcastInstrs(V);
1747   return WidenMap.splat(V, B);
1748 }
1749
1750 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1751   assert(Vec->getType()->isVectorTy() && "Invalid type");
1752   SmallVector<Constant*, 8> ShuffleMask;
1753   for (unsigned i = 0; i < VF; ++i)
1754     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1755
1756   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1757                                      ConstantVector::get(ShuffleMask),
1758                                      "reverse");
1759 }
1760
1761 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1762   // Attempt to issue a wide load.
1763   LoadInst *LI = dyn_cast<LoadInst>(Instr);
1764   StoreInst *SI = dyn_cast<StoreInst>(Instr);
1765
1766   assert((LI || SI) && "Invalid Load/Store instruction");
1767
1768   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1769   Type *DataTy = VectorType::get(ScalarDataTy, VF);
1770   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1771   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1772   // An alignment of 0 means target abi alignment. We need to use the scalar's
1773   // target abi alignment in such a case.
1774   if (!Alignment)
1775     Alignment = DL->getABITypeAlignment(ScalarDataTy);
1776   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1777   unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1778   unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1779
1780   if (SI && Legal->blockNeedsPredication(SI->getParent()))
1781     return scalarizeInstruction(Instr, true);
1782
1783   if (ScalarAllocatedSize != VectorElementSize)
1784     return scalarizeInstruction(Instr);
1785
1786   // If the pointer is loop invariant or if it is non-consecutive,
1787   // scalarize the load.
1788   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1789   bool Reverse = ConsecutiveStride < 0;
1790   bool UniformLoad = LI && Legal->isUniform(Ptr);
1791   if (!ConsecutiveStride || UniformLoad)
1792     return scalarizeInstruction(Instr);
1793
1794   Constant *Zero = Builder.getInt32(0);
1795   VectorParts &Entry = WidenMap.get(Instr);
1796
1797   // Handle consecutive loads/stores.
1798   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1799   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1800     setDebugLocFromInst(Builder, Gep);
1801     Value *PtrOperand = Gep->getPointerOperand();
1802     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1803     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1804
1805     // Create the new GEP with the new induction variable.
1806     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1807     Gep2->setOperand(0, FirstBasePtr);
1808     Gep2->setName("gep.indvar.base");
1809     Ptr = Builder.Insert(Gep2);
1810   } else if (Gep) {
1811     setDebugLocFromInst(Builder, Gep);
1812     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1813                                OrigLoop) && "Base ptr must be invariant");
1814
1815     // The last index does not have to be the induction. It can be
1816     // consecutive and be a function of the index. For example A[I+1];
1817     unsigned NumOperands = Gep->getNumOperands();
1818     unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1819     // Create the new GEP with the new induction variable.
1820     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1821
1822     for (unsigned i = 0; i < NumOperands; ++i) {
1823       Value *GepOperand = Gep->getOperand(i);
1824       Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1825
1826       // Update last index or loop invariant instruction anchored in loop.
1827       if (i == InductionOperand ||
1828           (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1829         assert((i == InductionOperand ||
1830                SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1831                "Must be last index or loop invariant");
1832
1833         VectorParts &GEPParts = getVectorValue(GepOperand);
1834         Value *Index = GEPParts[0];
1835         Index = Builder.CreateExtractElement(Index, Zero);
1836         Gep2->setOperand(i, Index);
1837         Gep2->setName("gep.indvar.idx");
1838       }
1839     }
1840     Ptr = Builder.Insert(Gep2);
1841   } else {
1842     // Use the induction element ptr.
1843     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1844     setDebugLocFromInst(Builder, Ptr);
1845     VectorParts &PtrVal = getVectorValue(Ptr);
1846     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1847   }
1848
1849   // Handle Stores:
1850   if (SI) {
1851     assert(!Legal->isUniform(SI->getPointerOperand()) &&
1852            "We do not allow storing to uniform addresses");
1853     setDebugLocFromInst(Builder, SI);
1854     // We don't want to update the value in the map as it might be used in
1855     // another expression. So don't use a reference type for "StoredVal".
1856     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1857
1858     for (unsigned Part = 0; Part < UF; ++Part) {
1859       // Calculate the pointer for the specific unroll-part.
1860       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1861
1862       if (Reverse) {
1863         // If we store to reverse consecutive memory locations then we need
1864         // to reverse the order of elements in the stored value.
1865         StoredVal[Part] = reverseVector(StoredVal[Part]);
1866         // If the address is consecutive but reversed, then the
1867         // wide store needs to start at the last vector element.
1868         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1869         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1870       }
1871
1872       Value *VecPtr = Builder.CreateBitCast(PartPtr,
1873                                             DataTy->getPointerTo(AddressSpace));
1874       StoreInst *NewSI =
1875         Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1876       propagateMetadata(NewSI, SI);
1877     }
1878     return;
1879   }
1880
1881   // Handle loads.
1882   assert(LI && "Must have a load instruction");
1883   setDebugLocFromInst(Builder, LI);
1884   for (unsigned Part = 0; Part < UF; ++Part) {
1885     // Calculate the pointer for the specific unroll-part.
1886     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1887
1888     if (Reverse) {
1889       // If the address is consecutive but reversed, then the
1890       // wide store needs to start at the last vector element.
1891       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1892       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1893     }
1894
1895     Value *VecPtr = Builder.CreateBitCast(PartPtr,
1896                                           DataTy->getPointerTo(AddressSpace));
1897     LoadInst *NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1898     propagateMetadata(NewLI, LI);
1899     Entry[Part] = Reverse ? reverseVector(NewLI) :  NewLI;
1900   }
1901 }
1902
1903 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1904   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1905   // Holds vector parameters or scalars, in case of uniform vals.
1906   SmallVector<VectorParts, 4> Params;
1907
1908   setDebugLocFromInst(Builder, Instr);
1909
1910   // Find all of the vectorized parameters.
1911   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1912     Value *SrcOp = Instr->getOperand(op);
1913
1914     // If we are accessing the old induction variable, use the new one.
1915     if (SrcOp == OldInduction) {
1916       Params.push_back(getVectorValue(SrcOp));
1917       continue;
1918     }
1919
1920     // Try using previously calculated values.
1921     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1922
1923     // If the src is an instruction that appeared earlier in the basic block
1924     // then it should already be vectorized.
1925     if (SrcInst && OrigLoop->contains(SrcInst)) {
1926       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1927       // The parameter is a vector value from earlier.
1928       Params.push_back(WidenMap.get(SrcInst));
1929     } else {
1930       // The parameter is a scalar from outside the loop. Maybe even a constant.
1931       VectorParts Scalars;
1932       Scalars.append(UF, SrcOp);
1933       Params.push_back(Scalars);
1934     }
1935   }
1936
1937   assert(Params.size() == Instr->getNumOperands() &&
1938          "Invalid number of operands");
1939
1940   // Does this instruction return a value ?
1941   bool IsVoidRetTy = Instr->getType()->isVoidTy();
1942
1943   Value *UndefVec = IsVoidRetTy ? nullptr :
1944     UndefValue::get(VectorType::get(Instr->getType(), VF));
1945   // Create a new entry in the WidenMap and initialize it to Undef or Null.
1946   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1947
1948   Instruction *InsertPt = Builder.GetInsertPoint();
1949   BasicBlock *IfBlock = Builder.GetInsertBlock();
1950   BasicBlock *CondBlock = nullptr;
1951
1952   VectorParts Cond;
1953   Loop *VectorLp = nullptr;
1954   if (IfPredicateStore) {
1955     assert(Instr->getParent()->getSinglePredecessor() &&
1956            "Only support single predecessor blocks");
1957     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1958                           Instr->getParent());
1959     VectorLp = LI->getLoopFor(IfBlock);
1960     assert(VectorLp && "Must have a loop for this block");
1961   }
1962
1963   // For each vector unroll 'part':
1964   for (unsigned Part = 0; Part < UF; ++Part) {
1965     // For each scalar that we create:
1966     for (unsigned Width = 0; Width < VF; ++Width) {
1967
1968       // Start if-block.
1969       Value *Cmp = nullptr;
1970       if (IfPredicateStore) {
1971         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1972         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1973         CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1974         LoopVectorBody.push_back(CondBlock);
1975         VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1976         // Update Builder with newly created basic block.
1977         Builder.SetInsertPoint(InsertPt);
1978       }
1979
1980       Instruction *Cloned = Instr->clone();
1981       if (!IsVoidRetTy)
1982         Cloned->setName(Instr->getName() + ".cloned");
1983       // Replace the operands of the cloned instructions with extracted scalars.
1984       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1985         Value *Op = Params[op][Part];
1986         // Param is a vector. Need to extract the right lane.
1987         if (Op->getType()->isVectorTy())
1988           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1989         Cloned->setOperand(op, Op);
1990       }
1991
1992       // Place the cloned scalar in the new loop.
1993       Builder.Insert(Cloned);
1994
1995       // If the original scalar returns a value we need to place it in a vector
1996       // so that future users will be able to use it.
1997       if (!IsVoidRetTy)
1998         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1999                                                        Builder.getInt32(Width));
2000       // End if-block.
2001       if (IfPredicateStore) {
2002          BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2003          LoopVectorBody.push_back(NewIfBlock);
2004          VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
2005          Builder.SetInsertPoint(InsertPt);
2006          Instruction *OldBr = IfBlock->getTerminator();
2007          BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2008          OldBr->eraseFromParent();
2009          IfBlock = NewIfBlock;
2010       }
2011     }
2012   }
2013 }
2014
2015 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2016                                  Instruction *Loc) {
2017   if (FirstInst)
2018     return FirstInst;
2019   if (Instruction *I = dyn_cast<Instruction>(V))
2020     return I->getParent() == Loc->getParent() ? I : nullptr;
2021   return nullptr;
2022 }
2023
2024 std::pair<Instruction *, Instruction *>
2025 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2026   Instruction *tnullptr = nullptr;
2027   if (!Legal->mustCheckStrides())
2028     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2029
2030   IRBuilder<> ChkBuilder(Loc);
2031
2032   // Emit checks.
2033   Value *Check = nullptr;
2034   Instruction *FirstInst = nullptr;
2035   for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2036                                          SE = Legal->strides_end();
2037        SI != SE; ++SI) {
2038     Value *Ptr = stripIntegerCast(*SI);
2039     Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2040                                        "stride.chk");
2041     // Store the first instruction we create.
2042     FirstInst = getFirstInst(FirstInst, C, Loc);
2043     if (Check)
2044       Check = ChkBuilder.CreateOr(Check, C);
2045     else
2046       Check = C;
2047   }
2048
2049   // We have to do this trickery because the IRBuilder might fold the check to a
2050   // constant expression in which case there is no Instruction anchored in a
2051   // the block.
2052   LLVMContext &Ctx = Loc->getContext();
2053   Instruction *TheCheck =
2054       BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2055   ChkBuilder.Insert(TheCheck, "stride.not.one");
2056   FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2057
2058   return std::make_pair(FirstInst, TheCheck);
2059 }
2060
2061 std::pair<Instruction *, Instruction *>
2062 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
2063   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
2064   Legal->getRuntimePointerCheck();
2065
2066   Instruction *tnullptr = nullptr;
2067   if (!PtrRtCheck->Need)
2068     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2069
2070   unsigned NumPointers = PtrRtCheck->Pointers.size();
2071   SmallVector<TrackingVH<Value> , 2> Starts;
2072   SmallVector<TrackingVH<Value> , 2> Ends;
2073
2074   LLVMContext &Ctx = Loc->getContext();
2075   SCEVExpander Exp(*SE, "induction");
2076   Instruction *FirstInst = nullptr;
2077
2078   for (unsigned i = 0; i < NumPointers; ++i) {
2079     Value *Ptr = PtrRtCheck->Pointers[i];
2080     const SCEV *Sc = SE->getSCEV(Ptr);
2081
2082     if (SE->isLoopInvariant(Sc, OrigLoop)) {
2083       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
2084             *Ptr <<"\n");
2085       Starts.push_back(Ptr);
2086       Ends.push_back(Ptr);
2087     } else {
2088       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
2089       unsigned AS = Ptr->getType()->getPointerAddressSpace();
2090
2091       // Use this type for pointer arithmetic.
2092       Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
2093
2094       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
2095       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
2096       Starts.push_back(Start);
2097       Ends.push_back(End);
2098     }
2099   }
2100
2101   IRBuilder<> ChkBuilder(Loc);
2102   // Our instructions might fold to a constant.
2103   Value *MemoryRuntimeCheck = nullptr;
2104   for (unsigned i = 0; i < NumPointers; ++i) {
2105     for (unsigned j = i+1; j < NumPointers; ++j) {
2106       // No need to check if two readonly pointers intersect.
2107       if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
2108         continue;
2109
2110       // Only need to check pointers between two different dependency sets.
2111       if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
2112        continue;
2113       // Only need to check pointers in the same alias set.
2114       if (PtrRtCheck->AliasSetId[i] != PtrRtCheck->AliasSetId[j])
2115         continue;
2116
2117       unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
2118       unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
2119
2120       assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
2121              (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
2122              "Trying to bounds check pointers with different address spaces");
2123
2124       Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
2125       Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
2126
2127       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
2128       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
2129       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy1, "bc");
2130       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy0, "bc");
2131
2132       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
2133       FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
2134       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
2135       FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
2136       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2137       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2138       if (MemoryRuntimeCheck) {
2139         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
2140                                          "conflict.rdx");
2141         FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2142       }
2143       MemoryRuntimeCheck = IsConflict;
2144     }
2145   }
2146
2147   // We have to do this trickery because the IRBuilder might fold the check to a
2148   // constant expression in which case there is no Instruction anchored in a
2149   // the block.
2150   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
2151                                                  ConstantInt::getTrue(Ctx));
2152   ChkBuilder.Insert(Check, "memcheck.conflict");
2153   FirstInst = getFirstInst(FirstInst, Check, Loc);
2154   return std::make_pair(FirstInst, Check);
2155 }
2156
2157 void InnerLoopVectorizer::createEmptyLoop() {
2158   /*
2159    In this function we generate a new loop. The new loop will contain
2160    the vectorized instructions while the old loop will continue to run the
2161    scalar remainder.
2162
2163        [ ] <-- Back-edge taken count overflow check.
2164     /   |
2165    /    v
2166   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
2167   |  /  |
2168   | /   v
2169   ||   [ ]     <-- vector pre header.
2170   ||    |
2171   ||    v
2172   ||   [  ] \
2173   ||   [  ]_|   <-- vector loop.
2174   ||    |
2175   | \   v
2176   |   >[ ]   <--- middle-block.
2177   |  /  |
2178   | /   v
2179   -|- >[ ]     <--- new preheader.
2180    |    |
2181    |    v
2182    |   [ ] \
2183    |   [ ]_|   <-- old scalar loop to handle remainder.
2184     \   |
2185      \  v
2186       >[ ]     <-- exit block.
2187    ...
2188    */
2189
2190   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2191   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2192   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2193   assert(BypassBlock && "Invalid loop structure");
2194   assert(ExitBlock && "Must have an exit block");
2195
2196   // Some loops have a single integer induction variable, while other loops
2197   // don't. One example is c++ iterators that often have multiple pointer
2198   // induction variables. In the code below we also support a case where we
2199   // don't have a single induction variable.
2200   OldInduction = Legal->getInduction();
2201   Type *IdxTy = Legal->getWidestInductionType();
2202
2203   // Find the loop boundaries.
2204   const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2205   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2206
2207   // The exit count might have the type of i64 while the phi is i32. This can
2208   // happen if we have an induction variable that is sign extended before the
2209   // compare. The only way that we get a backedge taken count is that the
2210   // induction variable was signed and as such will not overflow. In such a case
2211   // truncation is legal.
2212   if (ExitCount->getType()->getPrimitiveSizeInBits() >
2213       IdxTy->getPrimitiveSizeInBits())
2214     ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2215
2216   const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2217   // Get the total trip count from the count by adding 1.
2218   ExitCount = SE->getAddExpr(BackedgeTakeCount,
2219                              SE->getConstant(BackedgeTakeCount->getType(), 1));
2220
2221   // Expand the trip count and place the new instructions in the preheader.
2222   // Notice that the pre-header does not change, only the loop body.
2223   SCEVExpander Exp(*SE, "induction");
2224
2225   // We need to test whether the backedge-taken count is uint##_max. Adding one
2226   // to it will cause overflow and an incorrect loop trip count in the vector
2227   // body. In case of overflow we want to directly jump to the scalar remainder
2228   // loop.
2229   Value *BackedgeCount =
2230       Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2231                         BypassBlock->getTerminator());
2232   if (BackedgeCount->getType()->isPointerTy())
2233     BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2234                                                 "backedge.ptrcnt.to.int",
2235                                                 BypassBlock->getTerminator());
2236   Instruction *CheckBCOverflow =
2237       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2238                       Constant::getAllOnesValue(BackedgeCount->getType()),
2239                       "backedge.overflow", BypassBlock->getTerminator());
2240
2241   // The loop index does not have to start at Zero. Find the original start
2242   // value from the induction PHI node. If we don't have an induction variable
2243   // then we know that it starts at zero.
2244   Builder.SetInsertPoint(BypassBlock->getTerminator());
2245   Value *StartIdx = ExtendedIdx = OldInduction ?
2246     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2247                        IdxTy):
2248     ConstantInt::get(IdxTy, 0);
2249
2250   // We need an instruction to anchor the overflow check on. StartIdx needs to
2251   // be defined before the overflow check branch. Because the scalar preheader
2252   // is going to merge the start index and so the overflow branch block needs to
2253   // contain a definition of the start index.
2254   Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2255       StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2256       BypassBlock->getTerminator());
2257
2258   // Count holds the overall loop count (N).
2259   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2260                                    BypassBlock->getTerminator());
2261
2262   LoopBypassBlocks.push_back(BypassBlock);
2263
2264   // Split the single block loop into the two loop structure described above.
2265   BasicBlock *VectorPH =
2266   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2267   BasicBlock *VecBody =
2268   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2269   BasicBlock *MiddleBlock =
2270   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2271   BasicBlock *ScalarPH =
2272   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2273
2274   // Create and register the new vector loop.
2275   Loop* Lp = new Loop();
2276   Loop *ParentLoop = OrigLoop->getParentLoop();
2277
2278   // Insert the new loop into the loop nest and register the new basic blocks
2279   // before calling any utilities such as SCEV that require valid LoopInfo.
2280   if (ParentLoop) {
2281     ParentLoop->addChildLoop(Lp);
2282     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2283     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2284     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2285   } else {
2286     LI->addTopLevelLoop(Lp);
2287   }
2288   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2289
2290   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2291   // inside the loop.
2292   Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2293
2294   // Generate the induction variable.
2295   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2296   Induction = Builder.CreatePHI(IdxTy, 2, "index");
2297   // The loop step is equal to the vectorization factor (num of SIMD elements)
2298   // times the unroll factor (num of SIMD instructions).
2299   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2300
2301   // This is the IR builder that we use to add all of the logic for bypassing
2302   // the new vector loop.
2303   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2304   setDebugLocFromInst(BypassBuilder,
2305                       getDebugLocFromInstOrOperands(OldInduction));
2306
2307   // We may need to extend the index in case there is a type mismatch.
2308   // We know that the count starts at zero and does not overflow.
2309   if (Count->getType() != IdxTy) {
2310     // The exit count can be of pointer type. Convert it to the correct
2311     // integer type.
2312     if (ExitCount->getType()->isPointerTy())
2313       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2314     else
2315       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2316   }
2317
2318   // Add the start index to the loop count to get the new end index.
2319   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2320
2321   // Now we need to generate the expression for N - (N % VF), which is
2322   // the part that the vectorized body will execute.
2323   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2324   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2325   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2326                                                      "end.idx.rnd.down");
2327
2328   // Now, compare the new count to zero. If it is zero skip the vector loop and
2329   // jump to the scalar loop.
2330   Value *Cmp =
2331       BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2332
2333   BasicBlock *LastBypassBlock = BypassBlock;
2334
2335   // Generate code to check that the loops trip count that we computed by adding
2336   // one to the backedge-taken count will not overflow.
2337   {
2338     auto PastOverflowCheck =
2339         std::next(BasicBlock::iterator(OverflowCheckAnchor));
2340     BasicBlock *CheckBlock =
2341       LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2342     if (ParentLoop)
2343       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2344     LoopBypassBlocks.push_back(CheckBlock);
2345     Instruction *OldTerm = LastBypassBlock->getTerminator();
2346     BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2347     OldTerm->eraseFromParent();
2348     LastBypassBlock = CheckBlock;
2349   }
2350
2351   // Generate the code to check that the strides we assumed to be one are really
2352   // one. We want the new basic block to start at the first instruction in a
2353   // sequence of instructions that form a check.
2354   Instruction *StrideCheck;
2355   Instruction *FirstCheckInst;
2356   std::tie(FirstCheckInst, StrideCheck) =
2357       addStrideCheck(LastBypassBlock->getTerminator());
2358   if (StrideCheck) {
2359     // Create a new block containing the stride check.
2360     BasicBlock *CheckBlock =
2361         LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2362     if (ParentLoop)
2363       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2364     LoopBypassBlocks.push_back(CheckBlock);
2365
2366     // Replace the branch into the memory check block with a conditional branch
2367     // for the "few elements case".
2368     Instruction *OldTerm = LastBypassBlock->getTerminator();
2369     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2370     OldTerm->eraseFromParent();
2371
2372     Cmp = StrideCheck;
2373     LastBypassBlock = CheckBlock;
2374   }
2375
2376   // Generate the code that checks in runtime if arrays overlap. We put the
2377   // checks into a separate block to make the more common case of few elements
2378   // faster.
2379   Instruction *MemRuntimeCheck;
2380   std::tie(FirstCheckInst, MemRuntimeCheck) =
2381       addRuntimeCheck(LastBypassBlock->getTerminator());
2382   if (MemRuntimeCheck) {
2383     // Create a new block containing the memory check.
2384     BasicBlock *CheckBlock =
2385         LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2386     if (ParentLoop)
2387       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2388     LoopBypassBlocks.push_back(CheckBlock);
2389
2390     // Replace the branch into the memory check block with a conditional branch
2391     // for the "few elements case".
2392     Instruction *OldTerm = LastBypassBlock->getTerminator();
2393     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2394     OldTerm->eraseFromParent();
2395
2396     Cmp = MemRuntimeCheck;
2397     LastBypassBlock = CheckBlock;
2398   }
2399
2400   LastBypassBlock->getTerminator()->eraseFromParent();
2401   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2402                      LastBypassBlock);
2403
2404   // We are going to resume the execution of the scalar loop.
2405   // Go over all of the induction variables that we found and fix the
2406   // PHIs that are left in the scalar version of the loop.
2407   // The starting values of PHI nodes depend on the counter of the last
2408   // iteration in the vectorized loop.
2409   // If we come from a bypass edge then we need to start from the original
2410   // start value.
2411
2412   // This variable saves the new starting index for the scalar loop.
2413   PHINode *ResumeIndex = nullptr;
2414   LoopVectorizationLegality::InductionList::iterator I, E;
2415   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2416   // Set builder to point to last bypass block.
2417   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2418   for (I = List->begin(), E = List->end(); I != E; ++I) {
2419     PHINode *OrigPhi = I->first;
2420     LoopVectorizationLegality::InductionInfo II = I->second;
2421
2422     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2423     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2424                                          MiddleBlock->getTerminator());
2425     // We might have extended the type of the induction variable but we need a
2426     // truncated version for the scalar loop.
2427     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2428       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2429                       MiddleBlock->getTerminator()) : nullptr;
2430
2431     // Create phi nodes to merge from the  backedge-taken check block.
2432     PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2433                                            ScalarPH->getTerminator());
2434     BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2435
2436     PHINode *BCTruncResumeVal = nullptr;
2437     if (OrigPhi == OldInduction) {
2438       BCTruncResumeVal =
2439           PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2440                           ScalarPH->getTerminator());
2441       BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2442     }
2443
2444     Value *EndValue = nullptr;
2445     switch (II.IK) {
2446     case LoopVectorizationLegality::IK_NoInduction:
2447       llvm_unreachable("Unknown induction");
2448     case LoopVectorizationLegality::IK_IntInduction: {
2449       // Handle the integer induction counter.
2450       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2451
2452       // We have the canonical induction variable.
2453       if (OrigPhi == OldInduction) {
2454         // Create a truncated version of the resume value for the scalar loop,
2455         // we might have promoted the type to a larger width.
2456         EndValue =
2457           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2458         // The new PHI merges the original incoming value, in case of a bypass,
2459         // or the value at the end of the vectorized loop.
2460         for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2461           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2462         TruncResumeVal->addIncoming(EndValue, VecBody);
2463
2464         BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2465
2466         // We know what the end value is.
2467         EndValue = IdxEndRoundDown;
2468         // We also know which PHI node holds it.
2469         ResumeIndex = ResumeVal;
2470         break;
2471       }
2472
2473       // Not the canonical induction variable - add the vector loop count to the
2474       // start value.
2475       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2476                                                    II.StartValue->getType(),
2477                                                    "cast.crd");
2478       EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2479       break;
2480     }
2481     case LoopVectorizationLegality::IK_ReverseIntInduction: {
2482       // Convert the CountRoundDown variable to the PHI size.
2483       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2484                                                    II.StartValue->getType(),
2485                                                    "cast.crd");
2486       // Handle reverse integer induction counter.
2487       EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2488       break;
2489     }
2490     case LoopVectorizationLegality::IK_PtrInduction: {
2491       // For pointer induction variables, calculate the offset using
2492       // the end index.
2493       EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2494                                          "ptr.ind.end");
2495       break;
2496     }
2497     case LoopVectorizationLegality::IK_ReversePtrInduction: {
2498       // The value at the end of the loop for the reverse pointer is calculated
2499       // by creating a GEP with a negative index starting from the start value.
2500       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2501       Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2502                                               "rev.ind.end");
2503       EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2504                                          "rev.ptr.ind.end");
2505       break;
2506     }
2507     }// end of case
2508
2509     // The new PHI merges the original incoming value, in case of a bypass,
2510     // or the value at the end of the vectorized loop.
2511     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2512       if (OrigPhi == OldInduction)
2513         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2514       else
2515         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2516     }
2517     ResumeVal->addIncoming(EndValue, VecBody);
2518
2519     // Fix the scalar body counter (PHI node).
2520     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2521
2522     // The old induction's phi node in the scalar body needs the truncated
2523     // value.
2524     if (OrigPhi == OldInduction) {
2525       BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2526       OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2527     } else {
2528       BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2529       OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2530     }
2531   }
2532
2533   // If we are generating a new induction variable then we also need to
2534   // generate the code that calculates the exit value. This value is not
2535   // simply the end of the counter because we may skip the vectorized body
2536   // in case of a runtime check.
2537   if (!OldInduction){
2538     assert(!ResumeIndex && "Unexpected resume value found");
2539     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2540                                   MiddleBlock->getTerminator());
2541     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2542       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2543     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2544   }
2545
2546   // Make sure that we found the index where scalar loop needs to continue.
2547   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2548          "Invalid resume Index");
2549
2550   // Add a check in the middle block to see if we have completed
2551   // all of the iterations in the first vector loop.
2552   // If (N - N%VF) == N, then we *don't* need to run the remainder.
2553   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2554                                 ResumeIndex, "cmp.n",
2555                                 MiddleBlock->getTerminator());
2556
2557   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2558   // Remove the old terminator.
2559   MiddleBlock->getTerminator()->eraseFromParent();
2560
2561   // Create i+1 and fill the PHINode.
2562   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2563   Induction->addIncoming(StartIdx, VectorPH);
2564   Induction->addIncoming(NextIdx, VecBody);
2565   // Create the compare.
2566   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2567   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2568
2569   // Now we have two terminators. Remove the old one from the block.
2570   VecBody->getTerminator()->eraseFromParent();
2571
2572   // Get ready to start creating new instructions into the vectorized body.
2573   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2574
2575   // Save the state.
2576   LoopVectorPreHeader = VectorPH;
2577   LoopScalarPreHeader = ScalarPH;
2578   LoopMiddleBlock = MiddleBlock;
2579   LoopExitBlock = ExitBlock;
2580   LoopVectorBody.push_back(VecBody);
2581   LoopScalarBody = OldBasicBlock;
2582
2583   LoopVectorizeHints Hints(Lp, true);
2584   Hints.setAlreadyVectorized();
2585 }
2586
2587 /// This function returns the identity element (or neutral element) for
2588 /// the operation K.
2589 Constant*
2590 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2591   switch (K) {
2592   case RK_IntegerXor:
2593   case RK_IntegerAdd:
2594   case RK_IntegerOr:
2595     // Adding, Xoring, Oring zero to a number does not change it.
2596     return ConstantInt::get(Tp, 0);
2597   case RK_IntegerMult:
2598     // Multiplying a number by 1 does not change it.
2599     return ConstantInt::get(Tp, 1);
2600   case RK_IntegerAnd:
2601     // AND-ing a number with an all-1 value does not change it.
2602     return ConstantInt::get(Tp, -1, true);
2603   case  RK_FloatMult:
2604     // Multiplying a number by 1 does not change it.
2605     return ConstantFP::get(Tp, 1.0L);
2606   case  RK_FloatAdd:
2607     // Adding zero to a number does not change it.
2608     return ConstantFP::get(Tp, 0.0L);
2609   default:
2610     llvm_unreachable("Unknown reduction kind");
2611   }
2612 }
2613
2614 /// This function translates the reduction kind to an LLVM binary operator.
2615 static unsigned
2616 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2617   switch (Kind) {
2618     case LoopVectorizationLegality::RK_IntegerAdd:
2619       return Instruction::Add;
2620     case LoopVectorizationLegality::RK_IntegerMult:
2621       return Instruction::Mul;
2622     case LoopVectorizationLegality::RK_IntegerOr:
2623       return Instruction::Or;
2624     case LoopVectorizationLegality::RK_IntegerAnd:
2625       return Instruction::And;
2626     case LoopVectorizationLegality::RK_IntegerXor:
2627       return Instruction::Xor;
2628     case LoopVectorizationLegality::RK_FloatMult:
2629       return Instruction::FMul;
2630     case LoopVectorizationLegality::RK_FloatAdd:
2631       return Instruction::FAdd;
2632     case LoopVectorizationLegality::RK_IntegerMinMax:
2633       return Instruction::ICmp;
2634     case LoopVectorizationLegality::RK_FloatMinMax:
2635       return Instruction::FCmp;
2636     default:
2637       llvm_unreachable("Unknown reduction operation");
2638   }
2639 }
2640
2641 Value *createMinMaxOp(IRBuilder<> &Builder,
2642                       LoopVectorizationLegality::MinMaxReductionKind RK,
2643                       Value *Left,
2644                       Value *Right) {
2645   CmpInst::Predicate P = CmpInst::ICMP_NE;
2646   switch (RK) {
2647   default:
2648     llvm_unreachable("Unknown min/max reduction kind");
2649   case LoopVectorizationLegality::MRK_UIntMin:
2650     P = CmpInst::ICMP_ULT;
2651     break;
2652   case LoopVectorizationLegality::MRK_UIntMax:
2653     P = CmpInst::ICMP_UGT;
2654     break;
2655   case LoopVectorizationLegality::MRK_SIntMin:
2656     P = CmpInst::ICMP_SLT;
2657     break;
2658   case LoopVectorizationLegality::MRK_SIntMax:
2659     P = CmpInst::ICMP_SGT;
2660     break;
2661   case LoopVectorizationLegality::MRK_FloatMin:
2662     P = CmpInst::FCMP_OLT;
2663     break;
2664   case LoopVectorizationLegality::MRK_FloatMax:
2665     P = CmpInst::FCMP_OGT;
2666     break;
2667   }
2668
2669   Value *Cmp;
2670   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2671       RK == LoopVectorizationLegality::MRK_FloatMax)
2672     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2673   else
2674     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2675
2676   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2677   return Select;
2678 }
2679
2680 namespace {
2681 struct CSEDenseMapInfo {
2682   static bool canHandle(Instruction *I) {
2683     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2684            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2685   }
2686   static inline Instruction *getEmptyKey() {
2687     return DenseMapInfo<Instruction *>::getEmptyKey();
2688   }
2689   static inline Instruction *getTombstoneKey() {
2690     return DenseMapInfo<Instruction *>::getTombstoneKey();
2691   }
2692   static unsigned getHashValue(Instruction *I) {
2693     assert(canHandle(I) && "Unknown instruction!");
2694     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2695                                                            I->value_op_end()));
2696   }
2697   static bool isEqual(Instruction *LHS, Instruction *RHS) {
2698     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2699         LHS == getTombstoneKey() || RHS == getTombstoneKey())
2700       return LHS == RHS;
2701     return LHS->isIdenticalTo(RHS);
2702   }
2703 };
2704 }
2705
2706 /// \brief Check whether this block is a predicated block.
2707 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2708 /// = ...;  " blocks. We start with one vectorized basic block. For every
2709 /// conditional block we split this vectorized block. Therefore, every second
2710 /// block will be a predicated one.
2711 static bool isPredicatedBlock(unsigned BlockNum) {
2712   return BlockNum % 2;
2713 }
2714
2715 ///\brief Perform cse of induction variable instructions.
2716 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2717   // Perform simple cse.
2718   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2719   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2720     BasicBlock *BB = BBs[i];
2721     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2722       Instruction *In = I++;
2723
2724       if (!CSEDenseMapInfo::canHandle(In))
2725         continue;
2726
2727       // Check if we can replace this instruction with any of the
2728       // visited instructions.
2729       if (Instruction *V = CSEMap.lookup(In)) {
2730         In->replaceAllUsesWith(V);
2731         In->eraseFromParent();
2732         continue;
2733       }
2734       // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2735       // ...;" blocks for predicated stores. Every second block is a predicated
2736       // block.
2737       if (isPredicatedBlock(i))
2738         continue;
2739
2740       CSEMap[In] = In;
2741     }
2742   }
2743 }
2744
2745 /// \brief Adds a 'fast' flag to floating point operations.
2746 static Value *addFastMathFlag(Value *V) {
2747   if (isa<FPMathOperator>(V)){
2748     FastMathFlags Flags;
2749     Flags.setUnsafeAlgebra();
2750     cast<Instruction>(V)->setFastMathFlags(Flags);
2751   }
2752   return V;
2753 }
2754
2755 void InnerLoopVectorizer::vectorizeLoop() {
2756   //===------------------------------------------------===//
2757   //
2758   // Notice: any optimization or new instruction that go
2759   // into the code below should be also be implemented in
2760   // the cost-model.
2761   //
2762   //===------------------------------------------------===//
2763   Constant *Zero = Builder.getInt32(0);
2764
2765   // In order to support reduction variables we need to be able to vectorize
2766   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2767   // stages. First, we create a new vector PHI node with no incoming edges.
2768   // We use this value when we vectorize all of the instructions that use the
2769   // PHI. Next, after all of the instructions in the block are complete we
2770   // add the new incoming edges to the PHI. At this point all of the
2771   // instructions in the basic block are vectorized, so we can use them to
2772   // construct the PHI.
2773   PhiVector RdxPHIsToFix;
2774
2775   // Scan the loop in a topological order to ensure that defs are vectorized
2776   // before users.
2777   LoopBlocksDFS DFS(OrigLoop);
2778   DFS.perform(LI);
2779
2780   // Vectorize all of the blocks in the original loop.
2781   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2782        be = DFS.endRPO(); bb != be; ++bb)
2783     vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2784
2785   // At this point every instruction in the original loop is widened to
2786   // a vector form. We are almost done. Now, we need to fix the PHI nodes
2787   // that we vectorized. The PHI nodes are currently empty because we did
2788   // not want to introduce cycles. Notice that the remaining PHI nodes
2789   // that we need to fix are reduction variables.
2790
2791   // Create the 'reduced' values for each of the induction vars.
2792   // The reduced values are the vector values that we scalarize and combine
2793   // after the loop is finished.
2794   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2795        it != e; ++it) {
2796     PHINode *RdxPhi = *it;
2797     assert(RdxPhi && "Unable to recover vectorized PHI");
2798
2799     // Find the reduction variable descriptor.
2800     assert(Legal->getReductionVars()->count(RdxPhi) &&
2801            "Unable to find the reduction variable");
2802     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2803     (*Legal->getReductionVars())[RdxPhi];
2804
2805     setDebugLocFromInst(Builder, RdxDesc.StartValue);
2806
2807     // We need to generate a reduction vector from the incoming scalar.
2808     // To do so, we need to generate the 'identity' vector and override
2809     // one of the elements with the incoming scalar reduction. We need
2810     // to do it in the vector-loop preheader.
2811     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2812
2813     // This is the vector-clone of the value that leaves the loop.
2814     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2815     Type *VecTy = VectorExit[0]->getType();
2816
2817     // Find the reduction identity variable. Zero for addition, or, xor,
2818     // one for multiplication, -1 for And.
2819     Value *Identity;
2820     Value *VectorStart;
2821     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2822         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2823       // MinMax reduction have the start value as their identify.
2824       if (VF == 1) {
2825         VectorStart = Identity = RdxDesc.StartValue;
2826       } else {
2827         VectorStart = Identity = Builder.CreateVectorSplat(VF,
2828                                                            RdxDesc.StartValue,
2829                                                            "minmax.ident");
2830       }
2831     } else {
2832       // Handle other reduction kinds:
2833       Constant *Iden =
2834       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2835                                                       VecTy->getScalarType());
2836       if (VF == 1) {
2837         Identity = Iden;
2838         // This vector is the Identity vector where the first element is the
2839         // incoming scalar reduction.
2840         VectorStart = RdxDesc.StartValue;
2841       } else {
2842         Identity = ConstantVector::getSplat(VF, Iden);
2843
2844         // This vector is the Identity vector where the first element is the
2845         // incoming scalar reduction.
2846         VectorStart = Builder.CreateInsertElement(Identity,
2847                                                   RdxDesc.StartValue, Zero);
2848       }
2849     }
2850
2851     // Fix the vector-loop phi.
2852     // We created the induction variable so we know that the
2853     // preheader is the first entry.
2854     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2855
2856     // Reductions do not have to start at zero. They can start with
2857     // any loop invariant values.
2858     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2859     BasicBlock *Latch = OrigLoop->getLoopLatch();
2860     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2861     VectorParts &Val = getVectorValue(LoopVal);
2862     for (unsigned part = 0; part < UF; ++part) {
2863       // Make sure to add the reduction stat value only to the
2864       // first unroll part.
2865       Value *StartVal = (part == 0) ? VectorStart : Identity;
2866       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2867       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2868                                                   LoopVectorBody.back());
2869     }
2870
2871     // Before each round, move the insertion point right between
2872     // the PHIs and the values we are going to write.
2873     // This allows us to write both PHINodes and the extractelement
2874     // instructions.
2875     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2876
2877     VectorParts RdxParts;
2878     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2879     for (unsigned part = 0; part < UF; ++part) {
2880       // This PHINode contains the vectorized reduction variable, or
2881       // the initial value vector, if we bypass the vector loop.
2882       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2883       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2884       Value *StartVal = (part == 0) ? VectorStart : Identity;
2885       for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2886         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2887       NewPhi->addIncoming(RdxExitVal[part],
2888                           LoopVectorBody.back());
2889       RdxParts.push_back(NewPhi);
2890     }
2891
2892     // Reduce all of the unrolled parts into a single vector.
2893     Value *ReducedPartRdx = RdxParts[0];
2894     unsigned Op = getReductionBinOp(RdxDesc.Kind);
2895     setDebugLocFromInst(Builder, ReducedPartRdx);
2896     for (unsigned part = 1; part < UF; ++part) {
2897       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2898         // Floating point operations had to be 'fast' to enable the reduction.
2899         ReducedPartRdx = addFastMathFlag(
2900             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2901                                 ReducedPartRdx, "bin.rdx"));
2902       else
2903         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2904                                         ReducedPartRdx, RdxParts[part]);
2905     }
2906
2907     if (VF > 1) {
2908       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2909       // and vector ops, reducing the set of values being computed by half each
2910       // round.
2911       assert(isPowerOf2_32(VF) &&
2912              "Reduction emission only supported for pow2 vectors!");
2913       Value *TmpVec = ReducedPartRdx;
2914       SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2915       for (unsigned i = VF; i != 1; i >>= 1) {
2916         // Move the upper half of the vector to the lower half.
2917         for (unsigned j = 0; j != i/2; ++j)
2918           ShuffleMask[j] = Builder.getInt32(i/2 + j);
2919
2920         // Fill the rest of the mask with undef.
2921         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2922                   UndefValue::get(Builder.getInt32Ty()));
2923
2924         Value *Shuf =
2925         Builder.CreateShuffleVector(TmpVec,
2926                                     UndefValue::get(TmpVec->getType()),
2927                                     ConstantVector::get(ShuffleMask),
2928                                     "rdx.shuf");
2929
2930         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2931           // Floating point operations had to be 'fast' to enable the reduction.
2932           TmpVec = addFastMathFlag(Builder.CreateBinOp(
2933               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2934         else
2935           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2936       }
2937
2938       // The result is in the first element of the vector.
2939       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2940                                                     Builder.getInt32(0));
2941     }
2942
2943     // Create a phi node that merges control-flow from the backedge-taken check
2944     // block and the middle block.
2945     PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2946                                           LoopScalarPreHeader->getTerminator());
2947     BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2948     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2949
2950     // Now, we need to fix the users of the reduction variable
2951     // inside and outside of the scalar remainder loop.
2952     // We know that the loop is in LCSSA form. We need to update the
2953     // PHI nodes in the exit blocks.
2954     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2955          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2956       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2957       if (!LCSSAPhi) break;
2958
2959       // All PHINodes need to have a single entry edge, or two if
2960       // we already fixed them.
2961       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2962
2963       // We found our reduction value exit-PHI. Update it with the
2964       // incoming bypass edge.
2965       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2966         // Add an edge coming from the bypass.
2967         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2968         break;
2969       }
2970     }// end of the LCSSA phi scan.
2971
2972     // Fix the scalar loop reduction variable with the incoming reduction sum
2973     // from the vector body and from the backedge value.
2974     int IncomingEdgeBlockIdx =
2975     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2976     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2977     // Pick the other block.
2978     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2979     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2980     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2981   }// end of for each redux variable.
2982
2983   fixLCSSAPHIs();
2984
2985   // Remove redundant induction instructions.
2986   cse(LoopVectorBody);
2987 }
2988
2989 void InnerLoopVectorizer::fixLCSSAPHIs() {
2990   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2991        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2992     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2993     if (!LCSSAPhi) break;
2994     if (LCSSAPhi->getNumIncomingValues() == 1)
2995       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2996                             LoopMiddleBlock);
2997   }
2998
2999
3000 InnerLoopVectorizer::VectorParts
3001 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3002   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3003          "Invalid edge");
3004
3005   // Look for cached value.
3006   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3007   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3008   if (ECEntryIt != MaskCache.end())
3009     return ECEntryIt->second;
3010
3011   VectorParts SrcMask = createBlockInMask(Src);
3012
3013   // The terminator has to be a branch inst!
3014   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3015   assert(BI && "Unexpected terminator found");
3016
3017   if (BI->isConditional()) {
3018     VectorParts EdgeMask = getVectorValue(BI->getCondition());
3019
3020     if (BI->getSuccessor(0) != Dst)
3021       for (unsigned part = 0; part < UF; ++part)
3022         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3023
3024     for (unsigned part = 0; part < UF; ++part)
3025       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3026
3027     MaskCache[Edge] = EdgeMask;
3028     return EdgeMask;
3029   }
3030
3031   MaskCache[Edge] = SrcMask;
3032   return SrcMask;
3033 }
3034
3035 InnerLoopVectorizer::VectorParts
3036 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3037   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3038
3039   // Loop incoming mask is all-one.
3040   if (OrigLoop->getHeader() == BB) {
3041     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3042     return getVectorValue(C);
3043   }
3044
3045   // This is the block mask. We OR all incoming edges, and with zero.
3046   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3047   VectorParts BlockMask = getVectorValue(Zero);
3048
3049   // For each pred:
3050   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3051     VectorParts EM = createEdgeMask(*it, BB);
3052     for (unsigned part = 0; part < UF; ++part)
3053       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3054   }
3055
3056   return BlockMask;
3057 }
3058
3059 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3060                                               InnerLoopVectorizer::VectorParts &Entry,
3061                                               unsigned UF, unsigned VF, PhiVector *PV) {
3062   PHINode* P = cast<PHINode>(PN);
3063   // Handle reduction variables:
3064   if (Legal->getReductionVars()->count(P)) {
3065     for (unsigned part = 0; part < UF; ++part) {
3066       // This is phase one of vectorizing PHIs.
3067       Type *VecTy = (VF == 1) ? PN->getType() :
3068       VectorType::get(PN->getType(), VF);
3069       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3070                                     LoopVectorBody.back()-> getFirstInsertionPt());
3071     }
3072     PV->push_back(P);
3073     return;
3074   }
3075
3076   setDebugLocFromInst(Builder, P);
3077   // Check for PHI nodes that are lowered to vector selects.
3078   if (P->getParent() != OrigLoop->getHeader()) {
3079     // We know that all PHIs in non-header blocks are converted into
3080     // selects, so we don't have to worry about the insertion order and we
3081     // can just use the builder.
3082     // At this point we generate the predication tree. There may be
3083     // duplications since this is a simple recursive scan, but future
3084     // optimizations will clean it up.
3085
3086     unsigned NumIncoming = P->getNumIncomingValues();
3087
3088     // Generate a sequence of selects of the form:
3089     // SELECT(Mask3, In3,
3090     //      SELECT(Mask2, In2,
3091     //                   ( ...)))
3092     for (unsigned In = 0; In < NumIncoming; In++) {
3093       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3094                                         P->getParent());
3095       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3096
3097       for (unsigned part = 0; part < UF; ++part) {
3098         // We might have single edge PHIs (blocks) - use an identity
3099         // 'select' for the first PHI operand.
3100         if (In == 0)
3101           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3102                                              In0[part]);
3103         else
3104           // Select between the current value and the previous incoming edge
3105           // based on the incoming mask.
3106           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3107                                              Entry[part], "predphi");
3108       }
3109     }
3110     return;
3111   }
3112
3113   // This PHINode must be an induction variable.
3114   // Make sure that we know about it.
3115   assert(Legal->getInductionVars()->count(P) &&
3116          "Not an induction variable");
3117
3118   LoopVectorizationLegality::InductionInfo II =
3119   Legal->getInductionVars()->lookup(P);
3120
3121   switch (II.IK) {
3122     case LoopVectorizationLegality::IK_NoInduction:
3123       llvm_unreachable("Unknown induction");
3124     case LoopVectorizationLegality::IK_IntInduction: {
3125       assert(P->getType() == II.StartValue->getType() && "Types must match");
3126       Type *PhiTy = P->getType();
3127       Value *Broadcasted;
3128       if (P == OldInduction) {
3129         // Handle the canonical induction variable. We might have had to
3130         // extend the type.
3131         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3132       } else {
3133         // Handle other induction variables that are now based on the
3134         // canonical one.
3135         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3136                                                  "normalized.idx");
3137         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3138         Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
3139                                         "offset.idx");
3140       }
3141       Broadcasted = getBroadcastInstrs(Broadcasted);
3142       // After broadcasting the induction variable we need to make the vector
3143       // consecutive by adding 0, 1, 2, etc.
3144       for (unsigned part = 0; part < UF; ++part)
3145         Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
3146       return;
3147     }
3148     case LoopVectorizationLegality::IK_ReverseIntInduction:
3149     case LoopVectorizationLegality::IK_PtrInduction:
3150     case LoopVectorizationLegality::IK_ReversePtrInduction:
3151       // Handle reverse integer and pointer inductions.
3152       Value *StartIdx = ExtendedIdx;
3153       // This is the normalized GEP that starts counting at zero.
3154       Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
3155                                                "normalized.idx");
3156
3157       // Handle the reverse integer induction variable case.
3158       if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
3159         IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
3160         Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
3161                                                "resize.norm.idx");
3162         Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
3163                                                "reverse.idx");
3164
3165         // This is a new value so do not hoist it out.
3166         Value *Broadcasted = getBroadcastInstrs(ReverseInd);
3167         // After broadcasting the induction variable we need to make the
3168         // vector consecutive by adding  ... -3, -2, -1, 0.
3169         for (unsigned part = 0; part < UF; ++part)
3170           Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
3171                                              true);
3172         return;
3173       }
3174
3175       // Handle the pointer induction variable case.
3176       assert(P->getType()->isPointerTy() && "Unexpected type.");
3177
3178       // Is this a reverse induction ptr or a consecutive induction ptr.
3179       bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
3180                       II.IK);
3181
3182       // This is the vector of results. Notice that we don't generate
3183       // vector geps because scalar geps result in better code.
3184       for (unsigned part = 0; part < UF; ++part) {
3185         if (VF == 1) {
3186           int EltIndex = (part) * (Reverse ? -1 : 1);
3187           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3188           Value *GlobalIdx;
3189           if (Reverse)
3190             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3191           else
3192             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3193
3194           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3195                                              "next.gep");
3196           Entry[part] = SclrGep;
3197           continue;
3198         }
3199
3200         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3201         for (unsigned int i = 0; i < VF; ++i) {
3202           int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
3203           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3204           Value *GlobalIdx;
3205           if (!Reverse)
3206             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3207           else
3208             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3209
3210           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3211                                              "next.gep");
3212           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3213                                                Builder.getInt32(i),
3214                                                "insert.gep");
3215         }
3216         Entry[part] = VecVal;
3217       }
3218       return;
3219   }
3220 }
3221
3222 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3223   // For each instruction in the old loop.
3224   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3225     VectorParts &Entry = WidenMap.get(it);
3226     switch (it->getOpcode()) {
3227     case Instruction::Br:
3228       // Nothing to do for PHIs and BR, since we already took care of the
3229       // loop control flow instructions.
3230       continue;
3231     case Instruction::PHI:{
3232       // Vectorize PHINodes.
3233       widenPHIInstruction(it, Entry, UF, VF, PV);
3234       continue;
3235     }// End of PHI.
3236
3237     case Instruction::Add:
3238     case Instruction::FAdd:
3239     case Instruction::Sub:
3240     case Instruction::FSub:
3241     case Instruction::Mul:
3242     case Instruction::FMul:
3243     case Instruction::UDiv:
3244     case Instruction::SDiv:
3245     case Instruction::FDiv:
3246     case Instruction::URem:
3247     case Instruction::SRem:
3248     case Instruction::FRem:
3249     case Instruction::Shl:
3250     case Instruction::LShr:
3251     case Instruction::AShr:
3252     case Instruction::And:
3253     case Instruction::Or:
3254     case Instruction::Xor: {
3255       // Just widen binops.
3256       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3257       setDebugLocFromInst(Builder, BinOp);
3258       VectorParts &A = getVectorValue(it->getOperand(0));
3259       VectorParts &B = getVectorValue(it->getOperand(1));
3260
3261       // Use this vector value for all users of the original instruction.
3262       for (unsigned Part = 0; Part < UF; ++Part) {
3263         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3264
3265         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3266           VecOp->copyIRFlags(BinOp);
3267         
3268         Entry[Part] = V;
3269       }
3270
3271       propagateMetadata(Entry, it);
3272       break;
3273     }
3274     case Instruction::Select: {
3275       // Widen selects.
3276       // If the selector is loop invariant we can create a select
3277       // instruction with a scalar condition. Otherwise, use vector-select.
3278       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3279                                                OrigLoop);
3280       setDebugLocFromInst(Builder, it);
3281
3282       // The condition can be loop invariant  but still defined inside the
3283       // loop. This means that we can't just use the original 'cond' value.
3284       // We have to take the 'vectorized' value and pick the first lane.
3285       // Instcombine will make this a no-op.
3286       VectorParts &Cond = getVectorValue(it->getOperand(0));
3287       VectorParts &Op0  = getVectorValue(it->getOperand(1));
3288       VectorParts &Op1  = getVectorValue(it->getOperand(2));
3289
3290       Value *ScalarCond = (VF == 1) ? Cond[0] :
3291         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3292
3293       for (unsigned Part = 0; Part < UF; ++Part) {
3294         Entry[Part] = Builder.CreateSelect(
3295           InvariantCond ? ScalarCond : Cond[Part],
3296           Op0[Part],
3297           Op1[Part]);
3298       }
3299
3300       propagateMetadata(Entry, it);
3301       break;
3302     }
3303
3304     case Instruction::ICmp:
3305     case Instruction::FCmp: {
3306       // Widen compares. Generate vector compares.
3307       bool FCmp = (it->getOpcode() == Instruction::FCmp);
3308       CmpInst *Cmp = dyn_cast<CmpInst>(it);
3309       setDebugLocFromInst(Builder, it);
3310       VectorParts &A = getVectorValue(it->getOperand(0));
3311       VectorParts &B = getVectorValue(it->getOperand(1));
3312       for (unsigned Part = 0; Part < UF; ++Part) {
3313         Value *C = nullptr;
3314         if (FCmp)
3315           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3316         else
3317           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3318         Entry[Part] = C;
3319       }
3320
3321       propagateMetadata(Entry, it);
3322       break;
3323     }
3324
3325     case Instruction::Store:
3326     case Instruction::Load:
3327       vectorizeMemoryInstruction(it);
3328         break;
3329     case Instruction::ZExt:
3330     case Instruction::SExt:
3331     case Instruction::FPToUI:
3332     case Instruction::FPToSI:
3333     case Instruction::FPExt:
3334     case Instruction::PtrToInt:
3335     case Instruction::IntToPtr:
3336     case Instruction::SIToFP:
3337     case Instruction::UIToFP:
3338     case Instruction::Trunc:
3339     case Instruction::FPTrunc:
3340     case Instruction::BitCast: {
3341       CastInst *CI = dyn_cast<CastInst>(it);
3342       setDebugLocFromInst(Builder, it);
3343       /// Optimize the special case where the source is the induction
3344       /// variable. Notice that we can only optimize the 'trunc' case
3345       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3346       /// c. other casts depend on pointer size.
3347       if (CI->getOperand(0) == OldInduction &&
3348           it->getOpcode() == Instruction::Trunc) {
3349         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3350                                                CI->getType());
3351         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3352         for (unsigned Part = 0; Part < UF; ++Part)
3353           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3354         propagateMetadata(Entry, it);
3355         break;
3356       }
3357       /// Vectorize casts.
3358       Type *DestTy = (VF == 1) ? CI->getType() :
3359                                  VectorType::get(CI->getType(), VF);
3360
3361       VectorParts &A = getVectorValue(it->getOperand(0));
3362       for (unsigned Part = 0; Part < UF; ++Part)
3363         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3364       propagateMetadata(Entry, it);
3365       break;
3366     }
3367
3368     case Instruction::Call: {
3369       // Ignore dbg intrinsics.
3370       if (isa<DbgInfoIntrinsic>(it))
3371         break;
3372       setDebugLocFromInst(Builder, it);
3373
3374       Module *M = BB->getParent()->getParent();
3375       CallInst *CI = cast<CallInst>(it);
3376       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3377       assert(ID && "Not an intrinsic call!");
3378       switch (ID) {
3379       case Intrinsic::assume:
3380       case Intrinsic::lifetime_end:
3381       case Intrinsic::lifetime_start:
3382         scalarizeInstruction(it);
3383         break;
3384       default:
3385         bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3386         for (unsigned Part = 0; Part < UF; ++Part) {
3387           SmallVector<Value *, 4> Args;
3388           for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3389             if (HasScalarOpd && i == 1) {
3390               Args.push_back(CI->getArgOperand(i));
3391               continue;
3392             }
3393             VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3394             Args.push_back(Arg[Part]);
3395           }
3396           Type *Tys[] = {CI->getType()};
3397           if (VF > 1)
3398             Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3399
3400           Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3401           Entry[Part] = Builder.CreateCall(F, Args);
3402         }
3403
3404         propagateMetadata(Entry, it);
3405         break;
3406       }
3407       break;
3408     }
3409
3410     default:
3411       // All other instructions are unsupported. Scalarize them.
3412       scalarizeInstruction(it);
3413       break;
3414     }// end of switch.
3415   }// end of for_each instr.
3416 }
3417
3418 void InnerLoopVectorizer::updateAnalysis() {
3419   // Forget the original basic block.
3420   SE->forgetLoop(OrigLoop);
3421
3422   // Update the dominator tree information.
3423   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3424          "Entry does not dominate exit.");
3425
3426   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3427     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3428   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3429
3430   // Due to if predication of stores we might create a sequence of "if(pred)
3431   // a[i] = ...;  " blocks.
3432   for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3433     if (i == 0)
3434       DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3435     else if (isPredicatedBlock(i)) {
3436       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3437     } else {
3438       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3439     }
3440   }
3441
3442   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3443   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3444   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3445   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3446
3447   DEBUG(DT->verifyDomTree());
3448 }
3449
3450 /// \brief Check whether it is safe to if-convert this phi node.
3451 ///
3452 /// Phi nodes with constant expressions that can trap are not safe to if
3453 /// convert.
3454 static bool canIfConvertPHINodes(BasicBlock *BB) {
3455   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3456     PHINode *Phi = dyn_cast<PHINode>(I);
3457     if (!Phi)
3458       return true;
3459     for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3460       if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3461         if (C->canTrap())
3462           return false;
3463   }
3464   return true;
3465 }
3466
3467 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3468   if (!EnableIfConversion) {
3469     emitAnalysis(Report() << "if-conversion is disabled");
3470     return false;
3471   }
3472
3473   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3474
3475   // A list of pointers that we can safely read and write to.
3476   SmallPtrSet<Value *, 8> SafePointes;
3477
3478   // Collect safe addresses.
3479   for (Loop::block_iterator BI = TheLoop->block_begin(),
3480          BE = TheLoop->block_end(); BI != BE; ++BI) {
3481     BasicBlock *BB = *BI;
3482
3483     if (blockNeedsPredication(BB))
3484       continue;
3485
3486     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3487       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3488         SafePointes.insert(LI->getPointerOperand());
3489       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3490         SafePointes.insert(SI->getPointerOperand());
3491     }
3492   }
3493
3494   // Collect the blocks that need predication.
3495   BasicBlock *Header = TheLoop->getHeader();
3496   for (Loop::block_iterator BI = TheLoop->block_begin(),
3497          BE = TheLoop->block_end(); BI != BE; ++BI) {
3498     BasicBlock *BB = *BI;
3499
3500     // We don't support switch statements inside loops.
3501     if (!isa<BranchInst>(BB->getTerminator())) {
3502       emitAnalysis(Report(BB->getTerminator())
3503                    << "loop contains a switch statement");
3504       return false;
3505     }
3506
3507     // We must be able to predicate all blocks that need to be predicated.
3508     if (blockNeedsPredication(BB)) {
3509       if (!blockCanBePredicated(BB, SafePointes)) {
3510         emitAnalysis(Report(BB->getTerminator())
3511                      << "control flow cannot be substituted for a select");
3512         return false;
3513       }
3514     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3515       emitAnalysis(Report(BB->getTerminator())
3516                    << "control flow cannot be substituted for a select");
3517       return false;
3518     }
3519   }
3520
3521   // We can if-convert this loop.
3522   return true;
3523 }
3524
3525 bool LoopVectorizationLegality::canVectorize() {
3526   // We must have a loop in canonical form. Loops with indirectbr in them cannot
3527   // be canonicalized.
3528   if (!TheLoop->getLoopPreheader()) {
3529     emitAnalysis(
3530         Report() << "loop control flow is not understood by vectorizer");
3531     return false;
3532   }
3533
3534   // We can only vectorize innermost loops.
3535   if (TheLoop->getSubLoopsVector().size()) {
3536     emitAnalysis(Report() << "loop is not the innermost loop");
3537     return false;
3538   }
3539
3540   // We must have a single backedge.
3541   if (TheLoop->getNumBackEdges() != 1) {
3542     emitAnalysis(
3543         Report() << "loop control flow is not understood by vectorizer");
3544     return false;
3545   }
3546
3547   // We must have a single exiting block.
3548   if (!TheLoop->getExitingBlock()) {
3549     emitAnalysis(
3550         Report() << "loop control flow is not understood by vectorizer");
3551     return false;
3552   }
3553
3554   // We need to have a loop header.
3555   DEBUG(dbgs() << "LV: Found a loop: " <<
3556         TheLoop->getHeader()->getName() << '\n');
3557
3558   // Check if we can if-convert non-single-bb loops.
3559   unsigned NumBlocks = TheLoop->getNumBlocks();
3560   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3561     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3562     return false;
3563   }
3564
3565   // ScalarEvolution needs to be able to find the exit count.
3566   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3567   if (ExitCount == SE->getCouldNotCompute()) {
3568     emitAnalysis(Report() << "could not determine number of loop iterations");
3569     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3570     return false;
3571   }
3572
3573   // Check if we can vectorize the instructions and CFG in this loop.
3574   if (!canVectorizeInstrs()) {
3575     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3576     return false;
3577   }
3578
3579   // Go over each instruction and look at memory deps.
3580   if (!canVectorizeMemory()) {
3581     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3582     return false;
3583   }
3584
3585   // Collect all of the variables that remain uniform after vectorization.
3586   collectLoopUniforms();
3587
3588   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3589         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3590         <<"!\n");
3591
3592   // Okay! We can vectorize. At this point we don't have any other mem analysis
3593   // which may limit our maximum vectorization factor, so just return true with
3594   // no restrictions.
3595   return true;
3596 }
3597
3598 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3599   if (Ty->isPointerTy())
3600     return DL.getIntPtrType(Ty);
3601
3602   // It is possible that char's or short's overflow when we ask for the loop's
3603   // trip count, work around this by changing the type size.
3604   if (Ty->getScalarSizeInBits() < 32)
3605     return Type::getInt32Ty(Ty->getContext());
3606
3607   return Ty;
3608 }
3609
3610 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3611   Ty0 = convertPointerToIntegerType(DL, Ty0);
3612   Ty1 = convertPointerToIntegerType(DL, Ty1);
3613   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3614     return Ty0;
3615   return Ty1;
3616 }
3617
3618 /// \brief Check that the instruction has outside loop users and is not an
3619 /// identified reduction variable.
3620 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3621                                SmallPtrSetImpl<Value *> &Reductions) {
3622   // Reduction instructions are allowed to have exit users. All other
3623   // instructions must not have external users.
3624   if (!Reductions.count(Inst))
3625     //Check that all of the users of the loop are inside the BB.
3626     for (User *U : Inst->users()) {
3627       Instruction *UI = cast<Instruction>(U);
3628       // This user may be a reduction exit value.
3629       if (!TheLoop->contains(UI)) {
3630         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3631         return true;
3632       }
3633     }
3634   return false;
3635 }
3636
3637 bool LoopVectorizationLegality::canVectorizeInstrs() {
3638   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3639   BasicBlock *Header = TheLoop->getHeader();
3640
3641   // Look for the attribute signaling the absence of NaNs.
3642   Function &F = *Header->getParent();
3643   if (F.hasFnAttribute("no-nans-fp-math"))
3644     HasFunNoNaNAttr = F.getAttributes().getAttribute(
3645       AttributeSet::FunctionIndex,
3646       "no-nans-fp-math").getValueAsString() == "true";
3647
3648   // For each block in the loop.
3649   for (Loop::block_iterator bb = TheLoop->block_begin(),
3650        be = TheLoop->block_end(); bb != be; ++bb) {
3651
3652     // Scan the instructions in the block and look for hazards.
3653     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3654          ++it) {
3655
3656       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3657         Type *PhiTy = Phi->getType();
3658         // Check that this PHI type is allowed.
3659         if (!PhiTy->isIntegerTy() &&
3660             !PhiTy->isFloatingPointTy() &&
3661             !PhiTy->isPointerTy()) {
3662           emitAnalysis(Report(it)
3663                        << "loop control flow is not understood by vectorizer");
3664           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3665           return false;
3666         }
3667
3668         // If this PHINode is not in the header block, then we know that we
3669         // can convert it to select during if-conversion. No need to check if
3670         // the PHIs in this block are induction or reduction variables.
3671         if (*bb != Header) {
3672           // Check that this instruction has no outside users or is an
3673           // identified reduction value with an outside user.
3674           if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3675             continue;
3676           emitAnalysis(Report(it) << "value could not be identified as "
3677                                      "an induction or reduction variable");
3678           return false;
3679         }
3680
3681         // We only allow if-converted PHIs with more than two incoming values.
3682         if (Phi->getNumIncomingValues() != 2) {
3683           emitAnalysis(Report(it)
3684                        << "control flow not understood by vectorizer");
3685           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3686           return false;
3687         }
3688
3689         // This is the value coming from the preheader.
3690         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3691         // Check if this is an induction variable.
3692         InductionKind IK = isInductionVariable(Phi);
3693
3694         if (IK_NoInduction != IK) {
3695           // Get the widest type.
3696           if (!WidestIndTy)
3697             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3698           else
3699             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3700
3701           // Int inductions are special because we only allow one IV.
3702           if (IK == IK_IntInduction) {
3703             // Use the phi node with the widest type as induction. Use the last
3704             // one if there are multiple (no good reason for doing this other
3705             // than it is expedient).
3706             if (!Induction || PhiTy == WidestIndTy)
3707               Induction = Phi;
3708           }
3709
3710           DEBUG(dbgs() << "LV: Found an induction variable.\n");
3711           Inductions[Phi] = InductionInfo(StartValue, IK);
3712
3713           // Until we explicitly handle the case of an induction variable with
3714           // an outside loop user we have to give up vectorizing this loop.
3715           if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3716             emitAnalysis(Report(it) << "use of induction value outside of the "
3717                                        "loop is not handled by vectorizer");
3718             return false;
3719           }
3720
3721           continue;
3722         }
3723
3724         if (AddReductionVar(Phi, RK_IntegerAdd)) {
3725           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3726           continue;
3727         }
3728         if (AddReductionVar(Phi, RK_IntegerMult)) {
3729           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3730           continue;
3731         }
3732         if (AddReductionVar(Phi, RK_IntegerOr)) {
3733           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3734           continue;
3735         }
3736         if (AddReductionVar(Phi, RK_IntegerAnd)) {
3737           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3738           continue;
3739         }
3740         if (AddReductionVar(Phi, RK_IntegerXor)) {
3741           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3742           continue;
3743         }
3744         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3745           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3746           continue;
3747         }
3748         if (AddReductionVar(Phi, RK_FloatMult)) {
3749           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3750           continue;
3751         }
3752         if (AddReductionVar(Phi, RK_FloatAdd)) {
3753           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3754           continue;
3755         }
3756         if (AddReductionVar(Phi, RK_FloatMinMax)) {
3757           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3758                 "\n");
3759           continue;
3760         }
3761
3762         emitAnalysis(Report(it) << "value that could not be identified as "
3763                                    "reduction is used outside the loop");
3764         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3765         return false;
3766       }// end of PHI handling
3767
3768       // We still don't handle functions. However, we can ignore dbg intrinsic
3769       // calls and we do handle certain intrinsic and libm functions.
3770       CallInst *CI = dyn_cast<CallInst>(it);
3771       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3772         emitAnalysis(Report(it) << "call instruction cannot be vectorized");
3773         DEBUG(dbgs() << "LV: Found a call site.\n");
3774         return false;
3775       }
3776
3777       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3778       // second argument is the same (i.e. loop invariant)
3779       if (CI &&
3780           hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3781         if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3782           emitAnalysis(Report(it)
3783                        << "intrinsic instruction cannot be vectorized");
3784           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3785           return false;
3786         }
3787       }
3788
3789       // Check that the instruction return type is vectorizable.
3790       // Also, we can't vectorize extractelement instructions.
3791       if ((!VectorType::isValidElementType(it->getType()) &&
3792            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3793         emitAnalysis(Report(it)
3794                      << "instruction return type cannot be vectorized");
3795         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3796         return false;
3797       }
3798
3799       // Check that the stored type is vectorizable.
3800       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3801         Type *T = ST->getValueOperand()->getType();
3802         if (!VectorType::isValidElementType(T)) {
3803           emitAnalysis(Report(ST) << "store instruction cannot be vectorized");
3804           return false;
3805         }
3806         if (EnableMemAccessVersioning)
3807           collectStridedAcccess(ST);
3808       }
3809
3810       if (EnableMemAccessVersioning)
3811         if (LoadInst *LI = dyn_cast<LoadInst>(it))
3812           collectStridedAcccess(LI);
3813
3814       // Reduction instructions are allowed to have exit users.
3815       // All other instructions must not have external users.
3816       if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3817         emitAnalysis(Report(it) << "value cannot be used outside the loop");
3818         return false;
3819       }
3820
3821     } // next instr.
3822
3823   }
3824
3825   if (!Induction) {
3826     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3827     if (Inductions.empty()) {
3828       emitAnalysis(Report()
3829                    << "loop induction variable could not be identified");
3830       return false;
3831     }
3832   }
3833
3834   return true;
3835 }
3836
3837 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3838 /// return the induction operand of the gep pointer.
3839 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3840                                  const DataLayout *DL, Loop *Lp) {
3841   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3842   if (!GEP)
3843     return Ptr;
3844