Correctly update dom-tree after loop vectorizer.
[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         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   const Function *TheFunction;
981   // Loop Vectorize Hint.
982   const LoopVectorizeHints *Hints;
983 };
984
985 /// Utility class for getting and setting loop vectorizer hints in the form
986 /// of loop metadata.
987 /// This class keeps a number of loop annotations locally (as member variables)
988 /// and can, upon request, write them back as metadata on the loop. It will
989 /// initially scan the loop for existing metadata, and will update the local
990 /// values based on information in the loop.
991 /// We cannot write all values to metadata, as the mere presence of some info,
992 /// for example 'force', means a decision has been made. So, we need to be
993 /// careful NOT to add them if the user hasn't specifically asked so.
994 class LoopVectorizeHints {
995   enum HintKind {
996     HK_WIDTH,
997     HK_UNROLL,
998     HK_FORCE
999   };
1000
1001   /// Hint - associates name and validation with the hint value.
1002   struct Hint {
1003     const char * Name;
1004     unsigned Value; // This may have to change for non-numeric values.
1005     HintKind Kind;
1006
1007     Hint(const char * Name, unsigned Value, HintKind Kind)
1008       : Name(Name), Value(Value), Kind(Kind) { }
1009
1010     bool validate(unsigned Val) {
1011       switch (Kind) {
1012       case HK_WIDTH:
1013         return isPowerOf2_32(Val) && Val <= MaxVectorWidth;
1014       case HK_UNROLL:
1015         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1016       case HK_FORCE:
1017         return (Val <= 1);
1018       }
1019       return false;
1020     }
1021   };
1022
1023   /// Vectorization width.
1024   Hint Width;
1025   /// Vectorization interleave factor.
1026   Hint Interleave;
1027   /// Vectorization forced
1028   Hint Force;
1029
1030   /// Return the loop metadata prefix.
1031   static StringRef Prefix() { return "llvm.loop."; }
1032
1033 public:
1034   enum ForceKind {
1035     FK_Undefined = -1, ///< Not selected.
1036     FK_Disabled = 0,   ///< Forcing disabled.
1037     FK_Enabled = 1,    ///< Forcing enabled.
1038   };
1039
1040   LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1041       : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
1042         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1043         Force("vectorize.enable", FK_Undefined, HK_FORCE),
1044         TheLoop(L) {
1045     // Populate values with existing loop metadata.
1046     getHintsFromMetadata();
1047
1048     // force-vector-interleave overrides DisableInterleaving.
1049     if (VectorizationInterleave.getNumOccurrences() > 0)
1050       Interleave.Value = VectorizationInterleave;
1051
1052     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1053           << "LV: Interleaving disabled by the pass manager\n");
1054   }
1055
1056   /// Mark the loop L as already vectorized by setting the width to 1.
1057   void setAlreadyVectorized() {
1058     Width.Value = Interleave.Value = 1;
1059     Hint Hints[] = {Width, Interleave};
1060     writeHintsToMetadata(Hints);
1061   }
1062
1063   /// Dumps all the hint information.
1064   std::string emitRemark() const {
1065     Report R;
1066     if (Force.Value == LoopVectorizeHints::FK_Disabled)
1067       R << "vectorization is explicitly disabled";
1068     else {
1069       R << "use -Rpass-analysis=loop-vectorize for more info";
1070       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1071         R << " (Force=true";
1072         if (Width.Value != 0)
1073           R << ", Vector Width=" << Width.Value;
1074         if (Interleave.Value != 0)
1075           R << ", Interleave Count=" << Interleave.Value;
1076         R << ")";
1077       }
1078     }
1079
1080     return R.str();
1081   }
1082
1083   unsigned getWidth() const { return Width.Value; }
1084   unsigned getInterleave() const { return Interleave.Value; }
1085   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1086
1087 private:
1088   /// Find hints specified in the loop metadata and update local values.
1089   void getHintsFromMetadata() {
1090     MDNode *LoopID = TheLoop->getLoopID();
1091     if (!LoopID)
1092       return;
1093
1094     // First operand should refer to the loop id itself.
1095     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1096     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1097
1098     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1099       const MDString *S = nullptr;
1100       SmallVector<Value*, 4> Args;
1101
1102       // The expected hint is either a MDString or a MDNode with the first
1103       // operand a MDString.
1104       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1105         if (!MD || MD->getNumOperands() == 0)
1106           continue;
1107         S = dyn_cast<MDString>(MD->getOperand(0));
1108         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1109           Args.push_back(MD->getOperand(i));
1110       } else {
1111         S = dyn_cast<MDString>(LoopID->getOperand(i));
1112         assert(Args.size() == 0 && "too many arguments for MDString");
1113       }
1114
1115       if (!S)
1116         continue;
1117
1118       // Check if the hint starts with the loop metadata prefix.
1119       StringRef Name = S->getString();
1120       if (Args.size() == 1)
1121         setHint(Name, Args[0]);
1122     }
1123   }
1124
1125   /// Checks string hint with one operand and set value if valid.
1126   void setHint(StringRef Name, Value *Arg) {
1127     if (!Name.startswith(Prefix()))
1128       return;
1129     Name = Name.substr(Prefix().size(), StringRef::npos);
1130
1131     const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
1132     if (!C) return;
1133     unsigned Val = C->getZExtValue();
1134
1135     Hint *Hints[] = {&Width, &Interleave, &Force};
1136     for (auto H : Hints) {
1137       if (Name == H->Name) {
1138         if (H->validate(Val))
1139           H->Value = Val;
1140         else
1141           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1142         break;
1143       }
1144     }
1145   }
1146
1147   /// Create a new hint from name / value pair.
1148   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1149     LLVMContext &Context = TheLoop->getHeader()->getContext();
1150     Value *Vals[] = {MDString::get(Context, Name),
1151                      ConstantInt::get(Type::getInt32Ty(Context), V)};
1152     return MDNode::get(Context, Vals);
1153   }
1154
1155   /// Matches metadata with hint name.
1156   bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1157     MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1158     if (!Name)
1159       return false;
1160
1161     for (auto H : HintTypes)
1162       if (Name->getName().endswith(H.Name))
1163         return true;
1164     return false;
1165   }
1166
1167   /// Sets current hints into loop metadata, keeping other values intact.
1168   void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1169     if (HintTypes.size() == 0)
1170       return;
1171
1172     // Reserve the first element to LoopID (see below).
1173     SmallVector<Value*, 4> Vals(1);
1174     // If the loop already has metadata, then ignore the existing operands.
1175     MDNode *LoopID = TheLoop->getLoopID();
1176     if (LoopID) {
1177       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1178         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1179         // If node in update list, ignore old value.
1180         if (!matchesHintMetadataName(Node, HintTypes))
1181           Vals.push_back(Node);
1182       }
1183     }
1184
1185     // Now, add the missing hints.
1186     for (auto H : HintTypes)
1187       Vals.push_back(
1188           createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1189
1190     // Replace current metadata node with new one.
1191     LLVMContext &Context = TheLoop->getHeader()->getContext();
1192     MDNode *NewLoopID = MDNode::get(Context, Vals);
1193     // Set operand 0 to refer to the loop id itself.
1194     NewLoopID->replaceOperandWith(0, NewLoopID);
1195
1196     TheLoop->setLoopID(NewLoopID);
1197     if (LoopID)
1198       LoopID->replaceAllUsesWith(NewLoopID);
1199     LoopID = NewLoopID;
1200   }
1201
1202   /// The loop these hints belong to.
1203   const Loop *TheLoop;
1204 };
1205
1206 static void emitMissedWarning(Function *F, Loop *L,
1207                               const LoopVectorizeHints &LH) {
1208   emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1209                                L->getStartLoc(), LH.emitRemark());
1210
1211   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1212     if (LH.getWidth() != 1)
1213       emitLoopVectorizeWarning(
1214           F->getContext(), *F, L->getStartLoc(),
1215           "failed explicitly specified loop vectorization");
1216     else if (LH.getInterleave() != 1)
1217       emitLoopInterleaveWarning(
1218           F->getContext(), *F, L->getStartLoc(),
1219           "failed explicitly specified loop interleaving");
1220   }
1221 }
1222
1223 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1224   if (L.empty())
1225     return V.push_back(&L);
1226
1227   for (Loop *InnerL : L)
1228     addInnerLoop(*InnerL, V);
1229 }
1230
1231 /// The LoopVectorize Pass.
1232 struct LoopVectorize : public FunctionPass {
1233   /// Pass identification, replacement for typeid
1234   static char ID;
1235
1236   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1237     : FunctionPass(ID),
1238       DisableUnrolling(NoUnrolling),
1239       AlwaysVectorize(AlwaysVectorize) {
1240     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1241   }
1242
1243   ScalarEvolution *SE;
1244   const DataLayout *DL;
1245   LoopInfo *LI;
1246   TargetTransformInfo *TTI;
1247   DominatorTree *DT;
1248   BlockFrequencyInfo *BFI;
1249   TargetLibraryInfo *TLI;
1250   AliasAnalysis *AA;
1251   AssumptionTracker *AT;
1252   bool DisableUnrolling;
1253   bool AlwaysVectorize;
1254
1255   BlockFrequency ColdEntryFreq;
1256
1257   bool runOnFunction(Function &F) override {
1258     SE = &getAnalysis<ScalarEvolution>();
1259     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1260     DL = DLP ? &DLP->getDataLayout() : nullptr;
1261     LI = &getAnalysis<LoopInfo>();
1262     TTI = &getAnalysis<TargetTransformInfo>();
1263     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1264     BFI = &getAnalysis<BlockFrequencyInfo>();
1265     TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1266     AA = &getAnalysis<AliasAnalysis>();
1267     AT = &getAnalysis<AssumptionTracker>();
1268
1269     // Compute some weights outside of the loop over the loops. Compute this
1270     // using a BranchProbability to re-use its scaling math.
1271     const BranchProbability ColdProb(1, 5); // 20%
1272     ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1273
1274     // If the target claims to have no vector registers don't attempt
1275     // vectorization.
1276     if (!TTI->getNumberOfRegisters(true))
1277       return false;
1278
1279     if (!DL) {
1280       DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1281                    << ": Missing data layout\n");
1282       return false;
1283     }
1284
1285     // Build up a worklist of inner-loops to vectorize. This is necessary as
1286     // the act of vectorizing or partially unrolling a loop creates new loops
1287     // and can invalidate iterators across the loops.
1288     SmallVector<Loop *, 8> Worklist;
1289
1290     for (Loop *L : *LI)
1291       addInnerLoop(*L, Worklist);
1292
1293     LoopsAnalyzed += Worklist.size();
1294
1295     // Now walk the identified inner loops.
1296     bool Changed = false;
1297     while (!Worklist.empty())
1298       Changed |= processLoop(Worklist.pop_back_val());
1299
1300     // Process each loop nest in the function.
1301     return Changed;
1302   }
1303
1304   bool processLoop(Loop *L) {
1305     assert(L->empty() && "Only process inner loops.");
1306
1307 #ifndef NDEBUG
1308     const std::string DebugLocStr = getDebugLocString(L);
1309 #endif /* NDEBUG */
1310
1311     DEBUG(dbgs() << "\nLV: Checking a loop in \""
1312                  << L->getHeader()->getParent()->getName() << "\" from "
1313                  << DebugLocStr << "\n");
1314
1315     LoopVectorizeHints Hints(L, DisableUnrolling);
1316
1317     DEBUG(dbgs() << "LV: Loop hints:"
1318                  << " force="
1319                  << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1320                          ? "disabled"
1321                          : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1322                                 ? "enabled"
1323                                 : "?")) << " width=" << Hints.getWidth()
1324                  << " unroll=" << Hints.getInterleave() << "\n");
1325
1326     // Function containing loop
1327     Function *F = L->getHeader()->getParent();
1328
1329     // Looking at the diagnostic output is the only way to determine if a loop
1330     // was vectorized (other than looking at the IR or machine code), so it
1331     // is important to generate an optimization remark for each loop. Most of
1332     // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1333     // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1334     // less verbose reporting vectorized loops and unvectorized loops that may
1335     // benefit from vectorization, respectively.
1336
1337     if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1338       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1339       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1340                                      L->getStartLoc(), Hints.emitRemark());
1341       return false;
1342     }
1343
1344     if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1345       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1346       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1347                                      L->getStartLoc(), Hints.emitRemark());
1348       return false;
1349     }
1350
1351     if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1352       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1353       emitOptimizationRemarkAnalysis(
1354           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1355           "loop not vectorized: vector width and interleave count are "
1356           "explicitly set to 1");
1357       return false;
1358     }
1359
1360     // Check the loop for a trip count threshold:
1361     // do not vectorize loops with a tiny trip count.
1362     const unsigned TC = SE->getSmallConstantTripCount(L);
1363     if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1364       DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1365                    << "This loop is not worth vectorizing.");
1366       if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1367         DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1368       else {
1369         DEBUG(dbgs() << "\n");
1370         emitOptimizationRemarkAnalysis(
1371             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1372             "vectorization is not beneficial and is not explicitly forced");
1373         return false;
1374       }
1375     }
1376
1377     // Check if it is legal to vectorize the loop.
1378     LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F);
1379     if (!LVL.canVectorize()) {
1380       DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1381       emitMissedWarning(F, L, Hints);
1382       return false;
1383     }
1384
1385     // Use the cost model.
1386     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AT, F,
1387                                   &Hints);
1388
1389     // Check the function attributes to find out if this function should be
1390     // optimized for size.
1391     bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1392                       F->hasFnAttribute(Attribute::OptimizeForSize);
1393
1394     // Compute the weighted frequency of this loop being executed and see if it
1395     // is less than 20% of the function entry baseline frequency. Note that we
1396     // always have a canonical loop here because we think we *can* vectoriez.
1397     // FIXME: This is hidden behind a flag due to pervasive problems with
1398     // exactly what block frequency models.
1399     if (LoopVectorizeWithBlockFrequency) {
1400       BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1401       if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1402           LoopEntryFreq < ColdEntryFreq)
1403         OptForSize = true;
1404     }
1405
1406     // Check the function attributes to see if implicit floats are allowed.a
1407     // FIXME: This check doesn't seem possibly correct -- what if the loop is
1408     // an integer loop and the vector instructions selected are purely integer
1409     // vector instructions?
1410     if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1411       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1412             "attribute is used.\n");
1413       emitOptimizationRemarkAnalysis(
1414           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1415           "loop not vectorized due to NoImplicitFloat attribute");
1416       emitMissedWarning(F, L, Hints);
1417       return false;
1418     }
1419
1420     // Select the optimal vectorization factor.
1421     const LoopVectorizationCostModel::VectorizationFactor VF =
1422         CM.selectVectorizationFactor(OptForSize);
1423
1424     // Select the unroll factor.
1425     const unsigned UF =
1426         CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1427
1428     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1429                  << DebugLocStr << '\n');
1430     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1431
1432     if (VF.Width == 1) {
1433       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1434
1435       if (UF == 1) {
1436         emitOptimizationRemarkAnalysis(
1437             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1438             "not beneficial to vectorize and user disabled interleaving");
1439         return false;
1440       }
1441       DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1442
1443       // Report the unrolling decision.
1444       emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1445                              Twine("unrolled with interleaving factor " +
1446                                    Twine(UF) +
1447                                    " (vectorization not beneficial)"));
1448
1449       // We decided not to vectorize, but we may want to unroll.
1450
1451       InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1452       Unroller.vectorize(&LVL);
1453     } else {
1454       // If we decided that it is *legal* to vectorize the loop then do it.
1455       InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1456       LB.vectorize(&LVL);
1457       ++LoopsVectorized;
1458
1459       // Report the vectorization decision.
1460       emitOptimizationRemark(
1461           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1462           Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1463               ", unrolling interleave factor: " + Twine(UF) + ")");
1464     }
1465
1466     // Mark the loop as already vectorized to avoid vectorizing again.
1467     Hints.setAlreadyVectorized();
1468
1469     DEBUG(verifyFunction(*L->getHeader()->getParent()));
1470     return true;
1471   }
1472
1473   void getAnalysisUsage(AnalysisUsage &AU) const override {
1474     AU.addRequired<AssumptionTracker>();
1475     AU.addRequiredID(LoopSimplifyID);
1476     AU.addRequiredID(LCSSAID);
1477     AU.addRequired<BlockFrequencyInfo>();
1478     AU.addRequired<DominatorTreeWrapperPass>();
1479     AU.addRequired<LoopInfo>();
1480     AU.addRequired<ScalarEvolution>();
1481     AU.addRequired<TargetTransformInfo>();
1482     AU.addRequired<AliasAnalysis>();
1483     AU.addPreserved<LoopInfo>();
1484     AU.addPreserved<DominatorTreeWrapperPass>();
1485     AU.addPreserved<AliasAnalysis>();
1486   }
1487
1488 };
1489
1490 } // end anonymous namespace
1491
1492 //===----------------------------------------------------------------------===//
1493 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1494 // LoopVectorizationCostModel.
1495 //===----------------------------------------------------------------------===//
1496
1497 static Value *stripIntegerCast(Value *V) {
1498   if (CastInst *CI = dyn_cast<CastInst>(V))
1499     if (CI->getOperand(0)->getType()->isIntegerTy())
1500       return CI->getOperand(0);
1501   return V;
1502 }
1503
1504 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1505 ///
1506 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1507 /// \p Ptr.
1508 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1509                                              ValueToValueMap &PtrToStride,
1510                                              Value *Ptr, Value *OrigPtr = nullptr) {
1511
1512   const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1513
1514   // If there is an entry in the map return the SCEV of the pointer with the
1515   // symbolic stride replaced by one.
1516   ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1517   if (SI != PtrToStride.end()) {
1518     Value *StrideVal = SI->second;
1519
1520     // Strip casts.
1521     StrideVal = stripIntegerCast(StrideVal);
1522
1523     // Replace symbolic stride by one.
1524     Value *One = ConstantInt::get(StrideVal->getType(), 1);
1525     ValueToValueMap RewriteMap;
1526     RewriteMap[StrideVal] = One;
1527
1528     const SCEV *ByOne =
1529         SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1530     DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1531                  << "\n");
1532     return ByOne;
1533   }
1534
1535   // Otherwise, just return the SCEV of the original pointer.
1536   return SE->getSCEV(Ptr);
1537 }
1538
1539 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1540     ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1541     unsigned ASId, ValueToValueMap &Strides) {
1542   // Get the stride replaced scev.
1543   const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1544   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1545   assert(AR && "Invalid addrec expression");
1546   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1547   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1548   Pointers.push_back(Ptr);
1549   Starts.push_back(AR->getStart());
1550   Ends.push_back(ScEnd);
1551   IsWritePtr.push_back(WritePtr);
1552   DependencySetId.push_back(DepSetId);
1553   AliasSetId.push_back(ASId);
1554 }
1555
1556 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1557   // We need to place the broadcast of invariant variables outside the loop.
1558   Instruction *Instr = dyn_cast<Instruction>(V);
1559   bool NewInstr =
1560       (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1561                           Instr->getParent()) != LoopVectorBody.end());
1562   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1563
1564   // Place the code for broadcasting invariant variables in the new preheader.
1565   IRBuilder<>::InsertPointGuard Guard(Builder);
1566   if (Invariant)
1567     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1568
1569   // Broadcast the scalar into all locations in the vector.
1570   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1571
1572   return Shuf;
1573 }
1574
1575 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1576                                                  bool Negate) {
1577   assert(Val->getType()->isVectorTy() && "Must be a vector");
1578   assert(Val->getType()->getScalarType()->isIntegerTy() &&
1579          "Elem must be an integer");
1580   // Create the types.
1581   Type *ITy = Val->getType()->getScalarType();
1582   VectorType *Ty = cast<VectorType>(Val->getType());
1583   int VLen = Ty->getNumElements();
1584   SmallVector<Constant*, 8> Indices;
1585
1586   // Create a vector of consecutive numbers from zero to VF.
1587   for (int i = 0; i < VLen; ++i) {
1588     int64_t Idx = Negate ? (-i) : i;
1589     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1590   }
1591
1592   // Add the consecutive indices to the vector value.
1593   Constant *Cv = ConstantVector::get(Indices);
1594   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1595   return Builder.CreateAdd(Val, Cv, "induction");
1596 }
1597
1598 /// \brief Find the operand of the GEP that should be checked for consecutive
1599 /// stores. This ignores trailing indices that have no effect on the final
1600 /// pointer.
1601 static unsigned getGEPInductionOperand(const DataLayout *DL,
1602                                        const GetElementPtrInst *Gep) {
1603   unsigned LastOperand = Gep->getNumOperands() - 1;
1604   unsigned GEPAllocSize = DL->getTypeAllocSize(
1605       cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1606
1607   // Walk backwards and try to peel off zeros.
1608   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1609     // Find the type we're currently indexing into.
1610     gep_type_iterator GEPTI = gep_type_begin(Gep);
1611     std::advance(GEPTI, LastOperand - 1);
1612
1613     // If it's a type with the same allocation size as the result of the GEP we
1614     // can peel off the zero index.
1615     if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1616       break;
1617     --LastOperand;
1618   }
1619
1620   return LastOperand;
1621 }
1622
1623 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1624   assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1625   // Make sure that the pointer does not point to structs.
1626   if (Ptr->getType()->getPointerElementType()->isAggregateType())
1627     return 0;
1628
1629   // If this value is a pointer induction variable we know it is consecutive.
1630   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1631   if (Phi && Inductions.count(Phi)) {
1632     InductionInfo II = Inductions[Phi];
1633     if (IK_PtrInduction == II.IK)
1634       return 1;
1635     else if (IK_ReversePtrInduction == II.IK)
1636       return -1;
1637   }
1638
1639   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1640   if (!Gep)
1641     return 0;
1642
1643   unsigned NumOperands = Gep->getNumOperands();
1644   Value *GpPtr = Gep->getPointerOperand();
1645   // If this GEP value is a consecutive pointer induction variable and all of
1646   // the indices are constant then we know it is consecutive. We can
1647   Phi = dyn_cast<PHINode>(GpPtr);
1648   if (Phi && Inductions.count(Phi)) {
1649
1650     // Make sure that the pointer does not point to structs.
1651     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1652     if (GepPtrType->getElementType()->isAggregateType())
1653       return 0;
1654
1655     // Make sure that all of the index operands are loop invariant.
1656     for (unsigned i = 1; i < NumOperands; ++i)
1657       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1658         return 0;
1659
1660     InductionInfo II = Inductions[Phi];
1661     if (IK_PtrInduction == II.IK)
1662       return 1;
1663     else if (IK_ReversePtrInduction == II.IK)
1664       return -1;
1665   }
1666
1667   unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1668
1669   // Check that all of the gep indices are uniform except for our induction
1670   // operand.
1671   for (unsigned i = 0; i != NumOperands; ++i)
1672     if (i != InductionOperand &&
1673         !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1674       return 0;
1675
1676   // We can emit wide load/stores only if the last non-zero index is the
1677   // induction variable.
1678   const SCEV *Last = nullptr;
1679   if (!Strides.count(Gep))
1680     Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1681   else {
1682     // Because of the multiplication by a stride we can have a s/zext cast.
1683     // We are going to replace this stride by 1 so the cast is safe to ignore.
1684     //
1685     //  %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1686     //  %0 = trunc i64 %indvars.iv to i32
1687     //  %mul = mul i32 %0, %Stride1
1688     //  %idxprom = zext i32 %mul to i64  << Safe cast.
1689     //  %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1690     //
1691     Last = replaceSymbolicStrideSCEV(SE, Strides,
1692                                      Gep->getOperand(InductionOperand), Gep);
1693     if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1694       Last =
1695           (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1696               ? C->getOperand()
1697               : Last;
1698   }
1699   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1700     const SCEV *Step = AR->getStepRecurrence(*SE);
1701
1702     // The memory is consecutive because the last index is consecutive
1703     // and all other indices are loop invariant.
1704     if (Step->isOne())
1705       return 1;
1706     if (Step->isAllOnesValue())
1707       return -1;
1708   }
1709
1710   return 0;
1711 }
1712
1713 bool LoopVectorizationLegality::isUniform(Value *V) {
1714   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1715 }
1716
1717 InnerLoopVectorizer::VectorParts&
1718 InnerLoopVectorizer::getVectorValue(Value *V) {
1719   assert(V != Induction && "The new induction variable should not be used.");
1720   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1721
1722   // If we have a stride that is replaced by one, do it here.
1723   if (Legal->hasStride(V))
1724     V = ConstantInt::get(V->getType(), 1);
1725
1726   // If we have this scalar in the map, return it.
1727   if (WidenMap.has(V))
1728     return WidenMap.get(V);
1729
1730   // If this scalar is unknown, assume that it is a constant or that it is
1731   // loop invariant. Broadcast V and save the value for future uses.
1732   Value *B = getBroadcastInstrs(V);
1733   return WidenMap.splat(V, B);
1734 }
1735
1736 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1737   assert(Vec->getType()->isVectorTy() && "Invalid type");
1738   SmallVector<Constant*, 8> ShuffleMask;
1739   for (unsigned i = 0; i < VF; ++i)
1740     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1741
1742   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1743                                      ConstantVector::get(ShuffleMask),
1744                                      "reverse");
1745 }
1746
1747 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1748   // Attempt to issue a wide load.
1749   LoadInst *LI = dyn_cast<LoadInst>(Instr);
1750   StoreInst *SI = dyn_cast<StoreInst>(Instr);
1751
1752   assert((LI || SI) && "Invalid Load/Store instruction");
1753
1754   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1755   Type *DataTy = VectorType::get(ScalarDataTy, VF);
1756   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1757   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1758   // An alignment of 0 means target abi alignment. We need to use the scalar's
1759   // target abi alignment in such a case.
1760   if (!Alignment)
1761     Alignment = DL->getABITypeAlignment(ScalarDataTy);
1762   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1763   unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1764   unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1765
1766   if (SI && Legal->blockNeedsPredication(SI->getParent()))
1767     return scalarizeInstruction(Instr, true);
1768
1769   if (ScalarAllocatedSize != VectorElementSize)
1770     return scalarizeInstruction(Instr);
1771
1772   // If the pointer is loop invariant or if it is non-consecutive,
1773   // scalarize the load.
1774   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1775   bool Reverse = ConsecutiveStride < 0;
1776   bool UniformLoad = LI && Legal->isUniform(Ptr);
1777   if (!ConsecutiveStride || UniformLoad)
1778     return scalarizeInstruction(Instr);
1779
1780   Constant *Zero = Builder.getInt32(0);
1781   VectorParts &Entry = WidenMap.get(Instr);
1782
1783   // Handle consecutive loads/stores.
1784   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1785   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1786     setDebugLocFromInst(Builder, Gep);
1787     Value *PtrOperand = Gep->getPointerOperand();
1788     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1789     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1790
1791     // Create the new GEP with the new induction variable.
1792     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1793     Gep2->setOperand(0, FirstBasePtr);
1794     Gep2->setName("gep.indvar.base");
1795     Ptr = Builder.Insert(Gep2);
1796   } else if (Gep) {
1797     setDebugLocFromInst(Builder, Gep);
1798     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1799                                OrigLoop) && "Base ptr must be invariant");
1800
1801     // The last index does not have to be the induction. It can be
1802     // consecutive and be a function of the index. For example A[I+1];
1803     unsigned NumOperands = Gep->getNumOperands();
1804     unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1805     // Create the new GEP with the new induction variable.
1806     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1807
1808     for (unsigned i = 0; i < NumOperands; ++i) {
1809       Value *GepOperand = Gep->getOperand(i);
1810       Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1811
1812       // Update last index or loop invariant instruction anchored in loop.
1813       if (i == InductionOperand ||
1814           (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1815         assert((i == InductionOperand ||
1816                SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1817                "Must be last index or loop invariant");
1818
1819         VectorParts &GEPParts = getVectorValue(GepOperand);
1820         Value *Index = GEPParts[0];
1821         Index = Builder.CreateExtractElement(Index, Zero);
1822         Gep2->setOperand(i, Index);
1823         Gep2->setName("gep.indvar.idx");
1824       }
1825     }
1826     Ptr = Builder.Insert(Gep2);
1827   } else {
1828     // Use the induction element ptr.
1829     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1830     setDebugLocFromInst(Builder, Ptr);
1831     VectorParts &PtrVal = getVectorValue(Ptr);
1832     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1833   }
1834
1835   // Handle Stores:
1836   if (SI) {
1837     assert(!Legal->isUniform(SI->getPointerOperand()) &&
1838            "We do not allow storing to uniform addresses");
1839     setDebugLocFromInst(Builder, SI);
1840     // We don't want to update the value in the map as it might be used in
1841     // another expression. So don't use a reference type for "StoredVal".
1842     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1843
1844     for (unsigned Part = 0; Part < UF; ++Part) {
1845       // Calculate the pointer for the specific unroll-part.
1846       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1847
1848       if (Reverse) {
1849         // If we store to reverse consecutive memory locations then we need
1850         // to reverse the order of elements in the stored value.
1851         StoredVal[Part] = reverseVector(StoredVal[Part]);
1852         // If the address is consecutive but reversed, then the
1853         // wide store needs to start at the last vector element.
1854         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1855         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1856       }
1857
1858       Value *VecPtr = Builder.CreateBitCast(PartPtr,
1859                                             DataTy->getPointerTo(AddressSpace));
1860       StoreInst *NewSI =
1861         Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1862       propagateMetadata(NewSI, SI);
1863     }
1864     return;
1865   }
1866
1867   // Handle loads.
1868   assert(LI && "Must have a load instruction");
1869   setDebugLocFromInst(Builder, LI);
1870   for (unsigned Part = 0; Part < UF; ++Part) {
1871     // Calculate the pointer for the specific unroll-part.
1872     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1873
1874     if (Reverse) {
1875       // If the address is consecutive but reversed, then the
1876       // wide store needs to start at the last vector element.
1877       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1878       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1879     }
1880
1881     Value *VecPtr = Builder.CreateBitCast(PartPtr,
1882                                           DataTy->getPointerTo(AddressSpace));
1883     LoadInst *NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1884     propagateMetadata(NewLI, LI);
1885     Entry[Part] = Reverse ? reverseVector(NewLI) :  NewLI;
1886   }
1887 }
1888
1889 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1890   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1891   // Holds vector parameters or scalars, in case of uniform vals.
1892   SmallVector<VectorParts, 4> Params;
1893
1894   setDebugLocFromInst(Builder, Instr);
1895
1896   // Find all of the vectorized parameters.
1897   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1898     Value *SrcOp = Instr->getOperand(op);
1899
1900     // If we are accessing the old induction variable, use the new one.
1901     if (SrcOp == OldInduction) {
1902       Params.push_back(getVectorValue(SrcOp));
1903       continue;
1904     }
1905
1906     // Try using previously calculated values.
1907     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1908
1909     // If the src is an instruction that appeared earlier in the basic block
1910     // then it should already be vectorized.
1911     if (SrcInst && OrigLoop->contains(SrcInst)) {
1912       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1913       // The parameter is a vector value from earlier.
1914       Params.push_back(WidenMap.get(SrcInst));
1915     } else {
1916       // The parameter is a scalar from outside the loop. Maybe even a constant.
1917       VectorParts Scalars;
1918       Scalars.append(UF, SrcOp);
1919       Params.push_back(Scalars);
1920     }
1921   }
1922
1923   assert(Params.size() == Instr->getNumOperands() &&
1924          "Invalid number of operands");
1925
1926   // Does this instruction return a value ?
1927   bool IsVoidRetTy = Instr->getType()->isVoidTy();
1928
1929   Value *UndefVec = IsVoidRetTy ? nullptr :
1930     UndefValue::get(VectorType::get(Instr->getType(), VF));
1931   // Create a new entry in the WidenMap and initialize it to Undef or Null.
1932   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1933
1934   Instruction *InsertPt = Builder.GetInsertPoint();
1935   BasicBlock *IfBlock = Builder.GetInsertBlock();
1936   BasicBlock *CondBlock = nullptr;
1937
1938   VectorParts Cond;
1939   Loop *VectorLp = nullptr;
1940   if (IfPredicateStore) {
1941     assert(Instr->getParent()->getSinglePredecessor() &&
1942            "Only support single predecessor blocks");
1943     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1944                           Instr->getParent());
1945     VectorLp = LI->getLoopFor(IfBlock);
1946     assert(VectorLp && "Must have a loop for this block");
1947   }
1948
1949   // For each vector unroll 'part':
1950   for (unsigned Part = 0; Part < UF; ++Part) {
1951     // For each scalar that we create:
1952     for (unsigned Width = 0; Width < VF; ++Width) {
1953
1954       // Start if-block.
1955       Value *Cmp = nullptr;
1956       if (IfPredicateStore) {
1957         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1958         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1959         CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1960         LoopVectorBody.push_back(CondBlock);
1961         VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1962         // Update Builder with newly created basic block.
1963         Builder.SetInsertPoint(InsertPt);
1964       }
1965
1966       Instruction *Cloned = Instr->clone();
1967       if (!IsVoidRetTy)
1968         Cloned->setName(Instr->getName() + ".cloned");
1969       // Replace the operands of the cloned instructions with extracted scalars.
1970       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1971         Value *Op = Params[op][Part];
1972         // Param is a vector. Need to extract the right lane.
1973         if (Op->getType()->isVectorTy())
1974           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1975         Cloned->setOperand(op, Op);
1976       }
1977
1978       // Place the cloned scalar in the new loop.
1979       Builder.Insert(Cloned);
1980
1981       // If the original scalar returns a value we need to place it in a vector
1982       // so that future users will be able to use it.
1983       if (!IsVoidRetTy)
1984         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1985                                                        Builder.getInt32(Width));
1986       // End if-block.
1987       if (IfPredicateStore) {
1988          BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1989          LoopVectorBody.push_back(NewIfBlock);
1990          VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1991          Builder.SetInsertPoint(InsertPt);
1992          Instruction *OldBr = IfBlock->getTerminator();
1993          BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1994          OldBr->eraseFromParent();
1995          IfBlock = NewIfBlock;
1996       }
1997     }
1998   }
1999 }
2000
2001 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2002                                  Instruction *Loc) {
2003   if (FirstInst)
2004     return FirstInst;
2005   if (Instruction *I = dyn_cast<Instruction>(V))
2006     return I->getParent() == Loc->getParent() ? I : nullptr;
2007   return nullptr;
2008 }
2009
2010 std::pair<Instruction *, Instruction *>
2011 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2012   Instruction *tnullptr = nullptr;
2013   if (!Legal->mustCheckStrides())
2014     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2015
2016   IRBuilder<> ChkBuilder(Loc);
2017
2018   // Emit checks.
2019   Value *Check = nullptr;
2020   Instruction *FirstInst = nullptr;
2021   for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2022                                          SE = Legal->strides_end();
2023        SI != SE; ++SI) {
2024     Value *Ptr = stripIntegerCast(*SI);
2025     Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2026                                        "stride.chk");
2027     // Store the first instruction we create.
2028     FirstInst = getFirstInst(FirstInst, C, Loc);
2029     if (Check)
2030       Check = ChkBuilder.CreateOr(Check, C);
2031     else
2032       Check = C;
2033   }
2034
2035   // We have to do this trickery because the IRBuilder might fold the check to a
2036   // constant expression in which case there is no Instruction anchored in a
2037   // the block.
2038   LLVMContext &Ctx = Loc->getContext();
2039   Instruction *TheCheck =
2040       BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2041   ChkBuilder.Insert(TheCheck, "stride.not.one");
2042   FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2043
2044   return std::make_pair(FirstInst, TheCheck);
2045 }
2046
2047 std::pair<Instruction *, Instruction *>
2048 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
2049   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
2050   Legal->getRuntimePointerCheck();
2051
2052   Instruction *tnullptr = nullptr;
2053   if (!PtrRtCheck->Need)
2054     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2055
2056   unsigned NumPointers = PtrRtCheck->Pointers.size();
2057   SmallVector<TrackingVH<Value> , 2> Starts;
2058   SmallVector<TrackingVH<Value> , 2> Ends;
2059
2060   LLVMContext &Ctx = Loc->getContext();
2061   SCEVExpander Exp(*SE, "induction");
2062   Instruction *FirstInst = nullptr;
2063
2064   for (unsigned i = 0; i < NumPointers; ++i) {
2065     Value *Ptr = PtrRtCheck->Pointers[i];
2066     const SCEV *Sc = SE->getSCEV(Ptr);
2067
2068     if (SE->isLoopInvariant(Sc, OrigLoop)) {
2069       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
2070             *Ptr <<"\n");
2071       Starts.push_back(Ptr);
2072       Ends.push_back(Ptr);
2073     } else {
2074       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
2075       unsigned AS = Ptr->getType()->getPointerAddressSpace();
2076
2077       // Use this type for pointer arithmetic.
2078       Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
2079
2080       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
2081       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
2082       Starts.push_back(Start);
2083       Ends.push_back(End);
2084     }
2085   }
2086
2087   IRBuilder<> ChkBuilder(Loc);
2088   // Our instructions might fold to a constant.
2089   Value *MemoryRuntimeCheck = nullptr;
2090   for (unsigned i = 0; i < NumPointers; ++i) {
2091     for (unsigned j = i+1; j < NumPointers; ++j) {
2092       // No need to check if two readonly pointers intersect.
2093       if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
2094         continue;
2095
2096       // Only need to check pointers between two different dependency sets.
2097       if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
2098        continue;
2099       // Only need to check pointers in the same alias set.
2100       if (PtrRtCheck->AliasSetId[i] != PtrRtCheck->AliasSetId[j])
2101         continue;
2102
2103       unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
2104       unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
2105
2106       assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
2107              (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
2108              "Trying to bounds check pointers with different address spaces");
2109
2110       Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
2111       Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
2112
2113       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
2114       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
2115       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy1, "bc");
2116       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy0, "bc");
2117
2118       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
2119       FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
2120       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
2121       FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
2122       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2123       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2124       if (MemoryRuntimeCheck) {
2125         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
2126                                          "conflict.rdx");
2127         FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2128       }
2129       MemoryRuntimeCheck = IsConflict;
2130     }
2131   }
2132
2133   // We have to do this trickery because the IRBuilder might fold the check to a
2134   // constant expression in which case there is no Instruction anchored in a
2135   // the block.
2136   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
2137                                                  ConstantInt::getTrue(Ctx));
2138   ChkBuilder.Insert(Check, "memcheck.conflict");
2139   FirstInst = getFirstInst(FirstInst, Check, Loc);
2140   return std::make_pair(FirstInst, Check);
2141 }
2142
2143 void InnerLoopVectorizer::createEmptyLoop() {
2144   /*
2145    In this function we generate a new loop. The new loop will contain
2146    the vectorized instructions while the old loop will continue to run the
2147    scalar remainder.
2148
2149        [ ] <-- Back-edge taken count overflow check.
2150     /   |
2151    /    v
2152   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
2153   |  /  |
2154   | /   v
2155   ||   [ ]     <-- vector pre header.
2156   ||    |
2157   ||    v
2158   ||   [  ] \
2159   ||   [  ]_|   <-- vector loop.
2160   ||    |
2161   | \   v
2162   |   >[ ]   <--- middle-block.
2163   |  /  |
2164   | /   v
2165   -|- >[ ]     <--- new preheader.
2166    |    |
2167    |    v
2168    |   [ ] \
2169    |   [ ]_|   <-- old scalar loop to handle remainder.
2170     \   |
2171      \  v
2172       >[ ]     <-- exit block.
2173    ...
2174    */
2175
2176   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2177   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2178   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2179   assert(BypassBlock && "Invalid loop structure");
2180   assert(ExitBlock && "Must have an exit block");
2181
2182   // Some loops have a single integer induction variable, while other loops
2183   // don't. One example is c++ iterators that often have multiple pointer
2184   // induction variables. In the code below we also support a case where we
2185   // don't have a single induction variable.
2186   OldInduction = Legal->getInduction();
2187   Type *IdxTy = Legal->getWidestInductionType();
2188
2189   // Find the loop boundaries.
2190   const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2191   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2192
2193   // The exit count might have the type of i64 while the phi is i32. This can
2194   // happen if we have an induction variable that is sign extended before the
2195   // compare. The only way that we get a backedge taken count is that the
2196   // induction variable was signed and as such will not overflow. In such a case
2197   // truncation is legal.
2198   if (ExitCount->getType()->getPrimitiveSizeInBits() >
2199       IdxTy->getPrimitiveSizeInBits())
2200     ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2201
2202   const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2203   // Get the total trip count from the count by adding 1.
2204   ExitCount = SE->getAddExpr(BackedgeTakeCount,
2205                              SE->getConstant(BackedgeTakeCount->getType(), 1));
2206
2207   // Expand the trip count and place the new instructions in the preheader.
2208   // Notice that the pre-header does not change, only the loop body.
2209   SCEVExpander Exp(*SE, "induction");
2210
2211   // We need to test whether the backedge-taken count is uint##_max. Adding one
2212   // to it will cause overflow and an incorrect loop trip count in the vector
2213   // body. In case of overflow we want to directly jump to the scalar remainder
2214   // loop.
2215   Value *BackedgeCount =
2216       Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2217                         BypassBlock->getTerminator());
2218   if (BackedgeCount->getType()->isPointerTy())
2219     BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2220                                                 "backedge.ptrcnt.to.int",
2221                                                 BypassBlock->getTerminator());
2222   Instruction *CheckBCOverflow =
2223       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2224                       Constant::getAllOnesValue(BackedgeCount->getType()),
2225                       "backedge.overflow", BypassBlock->getTerminator());
2226
2227   // The loop index does not have to start at Zero. Find the original start
2228   // value from the induction PHI node. If we don't have an induction variable
2229   // then we know that it starts at zero.
2230   Builder.SetInsertPoint(BypassBlock->getTerminator());
2231   Value *StartIdx = ExtendedIdx = OldInduction ?
2232     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2233                        IdxTy):
2234     ConstantInt::get(IdxTy, 0);
2235
2236   // We need an instruction to anchor the overflow check on. StartIdx needs to
2237   // be defined before the overflow check branch. Because the scalar preheader
2238   // is going to merge the start index and so the overflow branch block needs to
2239   // contain a definition of the start index.
2240   Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2241       StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2242       BypassBlock->getTerminator());
2243
2244   // Count holds the overall loop count (N).
2245   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2246                                    BypassBlock->getTerminator());
2247
2248   LoopBypassBlocks.push_back(BypassBlock);
2249
2250   // Split the single block loop into the two loop structure described above.
2251   BasicBlock *VectorPH =
2252   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2253   BasicBlock *VecBody =
2254   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2255   BasicBlock *MiddleBlock =
2256   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2257   BasicBlock *ScalarPH =
2258   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2259
2260   // Create and register the new vector loop.
2261   Loop* Lp = new Loop();
2262   Loop *ParentLoop = OrigLoop->getParentLoop();
2263
2264   // Insert the new loop into the loop nest and register the new basic blocks
2265   // before calling any utilities such as SCEV that require valid LoopInfo.
2266   if (ParentLoop) {
2267     ParentLoop->addChildLoop(Lp);
2268     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2269     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2270     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2271   } else {
2272     LI->addTopLevelLoop(Lp);
2273   }
2274   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2275
2276   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2277   // inside the loop.
2278   Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2279
2280   // Generate the induction variable.
2281   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2282   Induction = Builder.CreatePHI(IdxTy, 2, "index");
2283   // The loop step is equal to the vectorization factor (num of SIMD elements)
2284   // times the unroll factor (num of SIMD instructions).
2285   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2286
2287   // This is the IR builder that we use to add all of the logic for bypassing
2288   // the new vector loop.
2289   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2290   setDebugLocFromInst(BypassBuilder,
2291                       getDebugLocFromInstOrOperands(OldInduction));
2292
2293   // We may need to extend the index in case there is a type mismatch.
2294   // We know that the count starts at zero and does not overflow.
2295   if (Count->getType() != IdxTy) {
2296     // The exit count can be of pointer type. Convert it to the correct
2297     // integer type.
2298     if (ExitCount->getType()->isPointerTy())
2299       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2300     else
2301       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2302   }
2303
2304   // Add the start index to the loop count to get the new end index.
2305   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2306
2307   // Now we need to generate the expression for N - (N % VF), which is
2308   // the part that the vectorized body will execute.
2309   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2310   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2311   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2312                                                      "end.idx.rnd.down");
2313
2314   // Now, compare the new count to zero. If it is zero skip the vector loop and
2315   // jump to the scalar loop.
2316   Value *Cmp =
2317       BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2318
2319   BasicBlock *LastBypassBlock = BypassBlock;
2320
2321   // Generate code to check that the loops trip count that we computed by adding
2322   // one to the backedge-taken count will not overflow.
2323   {
2324     auto PastOverflowCheck =
2325         std::next(BasicBlock::iterator(OverflowCheckAnchor));
2326     BasicBlock *CheckBlock =
2327       LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2328     if (ParentLoop)
2329       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2330     LoopBypassBlocks.push_back(CheckBlock);
2331     Instruction *OldTerm = LastBypassBlock->getTerminator();
2332     BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2333     OldTerm->eraseFromParent();
2334     LastBypassBlock = CheckBlock;
2335   }
2336
2337   // Generate the code to check that the strides we assumed to be one are really
2338   // one. We want the new basic block to start at the first instruction in a
2339   // sequence of instructions that form a check.
2340   Instruction *StrideCheck;
2341   Instruction *FirstCheckInst;
2342   std::tie(FirstCheckInst, StrideCheck) =
2343       addStrideCheck(LastBypassBlock->getTerminator());
2344   if (StrideCheck) {
2345     // Create a new block containing the stride check.
2346     BasicBlock *CheckBlock =
2347         LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2348     if (ParentLoop)
2349       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2350     LoopBypassBlocks.push_back(CheckBlock);
2351
2352     // Replace the branch into the memory check block with a conditional branch
2353     // for the "few elements case".
2354     Instruction *OldTerm = LastBypassBlock->getTerminator();
2355     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2356     OldTerm->eraseFromParent();
2357
2358     Cmp = StrideCheck;
2359     LastBypassBlock = CheckBlock;
2360   }
2361
2362   // Generate the code that checks in runtime if arrays overlap. We put the
2363   // checks into a separate block to make the more common case of few elements
2364   // faster.
2365   Instruction *MemRuntimeCheck;
2366   std::tie(FirstCheckInst, MemRuntimeCheck) =
2367       addRuntimeCheck(LastBypassBlock->getTerminator());
2368   if (MemRuntimeCheck) {
2369     // Create a new block containing the memory check.
2370     BasicBlock *CheckBlock =
2371         LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2372     if (ParentLoop)
2373       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2374     LoopBypassBlocks.push_back(CheckBlock);
2375
2376     // Replace the branch into the memory check block with a conditional branch
2377     // for the "few elements case".
2378     Instruction *OldTerm = LastBypassBlock->getTerminator();
2379     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2380     OldTerm->eraseFromParent();
2381
2382     Cmp = MemRuntimeCheck;
2383     LastBypassBlock = CheckBlock;
2384   }
2385
2386   LastBypassBlock->getTerminator()->eraseFromParent();
2387   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2388                      LastBypassBlock);
2389
2390   // We are going to resume the execution of the scalar loop.
2391   // Go over all of the induction variables that we found and fix the
2392   // PHIs that are left in the scalar version of the loop.
2393   // The starting values of PHI nodes depend on the counter of the last
2394   // iteration in the vectorized loop.
2395   // If we come from a bypass edge then we need to start from the original
2396   // start value.
2397
2398   // This variable saves the new starting index for the scalar loop.
2399   PHINode *ResumeIndex = nullptr;
2400   LoopVectorizationLegality::InductionList::iterator I, E;
2401   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2402   // Set builder to point to last bypass block.
2403   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2404   for (I = List->begin(), E = List->end(); I != E; ++I) {
2405     PHINode *OrigPhi = I->first;
2406     LoopVectorizationLegality::InductionInfo II = I->second;
2407
2408     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2409     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2410                                          MiddleBlock->getTerminator());
2411     // We might have extended the type of the induction variable but we need a
2412     // truncated version for the scalar loop.
2413     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2414       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2415                       MiddleBlock->getTerminator()) : nullptr;
2416
2417     // Create phi nodes to merge from the  backedge-taken check block.
2418     PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2419                                            ScalarPH->getTerminator());
2420     BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2421
2422     PHINode *BCTruncResumeVal = nullptr;
2423     if (OrigPhi == OldInduction) {
2424       BCTruncResumeVal =
2425           PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2426                           ScalarPH->getTerminator());
2427       BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2428     }
2429
2430     Value *EndValue = nullptr;
2431     switch (II.IK) {
2432     case LoopVectorizationLegality::IK_NoInduction:
2433       llvm_unreachable("Unknown induction");
2434     case LoopVectorizationLegality::IK_IntInduction: {
2435       // Handle the integer induction counter.
2436       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2437
2438       // We have the canonical induction variable.
2439       if (OrigPhi == OldInduction) {
2440         // Create a truncated version of the resume value for the scalar loop,
2441         // we might have promoted the type to a larger width.
2442         EndValue =
2443           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2444         // The new PHI merges the original incoming value, in case of a bypass,
2445         // or the value at the end of the vectorized loop.
2446         for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2447           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2448         TruncResumeVal->addIncoming(EndValue, VecBody);
2449
2450         BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2451
2452         // We know what the end value is.
2453         EndValue = IdxEndRoundDown;
2454         // We also know which PHI node holds it.
2455         ResumeIndex = ResumeVal;
2456         break;
2457       }
2458
2459       // Not the canonical induction variable - add the vector loop count to the
2460       // start value.
2461       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2462                                                    II.StartValue->getType(),
2463                                                    "cast.crd");
2464       EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2465       break;
2466     }
2467     case LoopVectorizationLegality::IK_ReverseIntInduction: {
2468       // Convert the CountRoundDown variable to the PHI size.
2469       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2470                                                    II.StartValue->getType(),
2471                                                    "cast.crd");
2472       // Handle reverse integer induction counter.
2473       EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2474       break;
2475     }
2476     case LoopVectorizationLegality::IK_PtrInduction: {
2477       // For pointer induction variables, calculate the offset using
2478       // the end index.
2479       EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2480                                          "ptr.ind.end");
2481       break;
2482     }
2483     case LoopVectorizationLegality::IK_ReversePtrInduction: {
2484       // The value at the end of the loop for the reverse pointer is calculated
2485       // by creating a GEP with a negative index starting from the start value.
2486       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2487       Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2488                                               "rev.ind.end");
2489       EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2490                                          "rev.ptr.ind.end");
2491       break;
2492     }
2493     }// end of case
2494
2495     // The new PHI merges the original incoming value, in case of a bypass,
2496     // or the value at the end of the vectorized loop.
2497     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2498       if (OrigPhi == OldInduction)
2499         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2500       else
2501         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2502     }
2503     ResumeVal->addIncoming(EndValue, VecBody);
2504
2505     // Fix the scalar body counter (PHI node).
2506     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2507
2508     // The old induction's phi node in the scalar body needs the truncated
2509     // value.
2510     if (OrigPhi == OldInduction) {
2511       BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2512       OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2513     } else {
2514       BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2515       OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2516     }
2517   }
2518
2519   // If we are generating a new induction variable then we also need to
2520   // generate the code that calculates the exit value. This value is not
2521   // simply the end of the counter because we may skip the vectorized body
2522   // in case of a runtime check.
2523   if (!OldInduction){
2524     assert(!ResumeIndex && "Unexpected resume value found");
2525     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2526                                   MiddleBlock->getTerminator());
2527     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2528       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2529     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2530   }
2531
2532   // Make sure that we found the index where scalar loop needs to continue.
2533   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2534          "Invalid resume Index");
2535
2536   // Add a check in the middle block to see if we have completed
2537   // all of the iterations in the first vector loop.
2538   // If (N - N%VF) == N, then we *don't* need to run the remainder.
2539   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2540                                 ResumeIndex, "cmp.n",
2541                                 MiddleBlock->getTerminator());
2542
2543   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2544   // Remove the old terminator.
2545   MiddleBlock->getTerminator()->eraseFromParent();
2546
2547   // Create i+1 and fill the PHINode.
2548   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2549   Induction->addIncoming(StartIdx, VectorPH);
2550   Induction->addIncoming(NextIdx, VecBody);
2551   // Create the compare.
2552   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2553   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2554
2555   // Now we have two terminators. Remove the old one from the block.
2556   VecBody->getTerminator()->eraseFromParent();
2557
2558   // Get ready to start creating new instructions into the vectorized body.
2559   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2560
2561   // Save the state.
2562   LoopVectorPreHeader = VectorPH;
2563   LoopScalarPreHeader = ScalarPH;
2564   LoopMiddleBlock = MiddleBlock;
2565   LoopExitBlock = ExitBlock;
2566   LoopVectorBody.push_back(VecBody);
2567   LoopScalarBody = OldBasicBlock;
2568
2569   LoopVectorizeHints Hints(Lp, true);
2570   Hints.setAlreadyVectorized();
2571 }
2572
2573 /// This function returns the identity element (or neutral element) for
2574 /// the operation K.
2575 Constant*
2576 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2577   switch (K) {
2578   case RK_IntegerXor:
2579   case RK_IntegerAdd:
2580   case RK_IntegerOr:
2581     // Adding, Xoring, Oring zero to a number does not change it.
2582     return ConstantInt::get(Tp, 0);
2583   case RK_IntegerMult:
2584     // Multiplying a number by 1 does not change it.
2585     return ConstantInt::get(Tp, 1);
2586   case RK_IntegerAnd:
2587     // AND-ing a number with an all-1 value does not change it.
2588     return ConstantInt::get(Tp, -1, true);
2589   case  RK_FloatMult:
2590     // Multiplying a number by 1 does not change it.
2591     return ConstantFP::get(Tp, 1.0L);
2592   case  RK_FloatAdd:
2593     // Adding zero to a number does not change it.
2594     return ConstantFP::get(Tp, 0.0L);
2595   default:
2596     llvm_unreachable("Unknown reduction kind");
2597   }
2598 }
2599
2600 /// This function translates the reduction kind to an LLVM binary operator.
2601 static unsigned
2602 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2603   switch (Kind) {
2604     case LoopVectorizationLegality::RK_IntegerAdd:
2605       return Instruction::Add;
2606     case LoopVectorizationLegality::RK_IntegerMult:
2607       return Instruction::Mul;
2608     case LoopVectorizationLegality::RK_IntegerOr:
2609       return Instruction::Or;
2610     case LoopVectorizationLegality::RK_IntegerAnd:
2611       return Instruction::And;
2612     case LoopVectorizationLegality::RK_IntegerXor:
2613       return Instruction::Xor;
2614     case LoopVectorizationLegality::RK_FloatMult:
2615       return Instruction::FMul;
2616     case LoopVectorizationLegality::RK_FloatAdd:
2617       return Instruction::FAdd;
2618     case LoopVectorizationLegality::RK_IntegerMinMax:
2619       return Instruction::ICmp;
2620     case LoopVectorizationLegality::RK_FloatMinMax:
2621       return Instruction::FCmp;
2622     default:
2623       llvm_unreachable("Unknown reduction operation");
2624   }
2625 }
2626
2627 Value *createMinMaxOp(IRBuilder<> &Builder,
2628                       LoopVectorizationLegality::MinMaxReductionKind RK,
2629                       Value *Left,
2630                       Value *Right) {
2631   CmpInst::Predicate P = CmpInst::ICMP_NE;
2632   switch (RK) {
2633   default:
2634     llvm_unreachable("Unknown min/max reduction kind");
2635   case LoopVectorizationLegality::MRK_UIntMin:
2636     P = CmpInst::ICMP_ULT;
2637     break;
2638   case LoopVectorizationLegality::MRK_UIntMax:
2639     P = CmpInst::ICMP_UGT;
2640     break;
2641   case LoopVectorizationLegality::MRK_SIntMin:
2642     P = CmpInst::ICMP_SLT;
2643     break;
2644   case LoopVectorizationLegality::MRK_SIntMax:
2645     P = CmpInst::ICMP_SGT;
2646     break;
2647   case LoopVectorizationLegality::MRK_FloatMin:
2648     P = CmpInst::FCMP_OLT;
2649     break;
2650   case LoopVectorizationLegality::MRK_FloatMax:
2651     P = CmpInst::FCMP_OGT;
2652     break;
2653   }
2654
2655   Value *Cmp;
2656   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2657       RK == LoopVectorizationLegality::MRK_FloatMax)
2658     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2659   else
2660     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2661
2662   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2663   return Select;
2664 }
2665
2666 namespace {
2667 struct CSEDenseMapInfo {
2668   static bool canHandle(Instruction *I) {
2669     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2670            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2671   }
2672   static inline Instruction *getEmptyKey() {
2673     return DenseMapInfo<Instruction *>::getEmptyKey();
2674   }
2675   static inline Instruction *getTombstoneKey() {
2676     return DenseMapInfo<Instruction *>::getTombstoneKey();
2677   }
2678   static unsigned getHashValue(Instruction *I) {
2679     assert(canHandle(I) && "Unknown instruction!");
2680     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2681                                                            I->value_op_end()));
2682   }
2683   static bool isEqual(Instruction *LHS, Instruction *RHS) {
2684     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2685         LHS == getTombstoneKey() || RHS == getTombstoneKey())
2686       return LHS == RHS;
2687     return LHS->isIdenticalTo(RHS);
2688   }
2689 };
2690 }
2691
2692 /// \brief Check whether this block is a predicated block.
2693 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2694 /// = ...;  " blocks. We start with one vectorized basic block. For every
2695 /// conditional block we split this vectorized block. Therefore, every second
2696 /// block will be a predicated one.
2697 static bool isPredicatedBlock(unsigned BlockNum) {
2698   return BlockNum % 2;
2699 }
2700
2701 ///\brief Perform cse of induction variable instructions.
2702 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2703   // Perform simple cse.
2704   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2705   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2706     BasicBlock *BB = BBs[i];
2707     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2708       Instruction *In = I++;
2709
2710       if (!CSEDenseMapInfo::canHandle(In))
2711         continue;
2712
2713       // Check if we can replace this instruction with any of the
2714       // visited instructions.
2715       if (Instruction *V = CSEMap.lookup(In)) {
2716         In->replaceAllUsesWith(V);
2717         In->eraseFromParent();
2718         continue;
2719       }
2720       // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2721       // ...;" blocks for predicated stores. Every second block is a predicated
2722       // block.
2723       if (isPredicatedBlock(i))
2724         continue;
2725
2726       CSEMap[In] = In;
2727     }
2728   }
2729 }
2730
2731 /// \brief Adds a 'fast' flag to floating point operations.
2732 static Value *addFastMathFlag(Value *V) {
2733   if (isa<FPMathOperator>(V)){
2734     FastMathFlags Flags;
2735     Flags.setUnsafeAlgebra();
2736     cast<Instruction>(V)->setFastMathFlags(Flags);
2737   }
2738   return V;
2739 }
2740
2741 void InnerLoopVectorizer::vectorizeLoop() {
2742   //===------------------------------------------------===//
2743   //
2744   // Notice: any optimization or new instruction that go
2745   // into the code below should be also be implemented in
2746   // the cost-model.
2747   //
2748   //===------------------------------------------------===//
2749   Constant *Zero = Builder.getInt32(0);
2750
2751   // In order to support reduction variables we need to be able to vectorize
2752   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2753   // stages. First, we create a new vector PHI node with no incoming edges.
2754   // We use this value when we vectorize all of the instructions that use the
2755   // PHI. Next, after all of the instructions in the block are complete we
2756   // add the new incoming edges to the PHI. At this point all of the
2757   // instructions in the basic block are vectorized, so we can use them to
2758   // construct the PHI.
2759   PhiVector RdxPHIsToFix;
2760
2761   // Scan the loop in a topological order to ensure that defs are vectorized
2762   // before users.
2763   LoopBlocksDFS DFS(OrigLoop);
2764   DFS.perform(LI);
2765
2766   // Vectorize all of the blocks in the original loop.
2767   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2768        be = DFS.endRPO(); bb != be; ++bb)
2769     vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2770
2771   // At this point every instruction in the original loop is widened to
2772   // a vector form. We are almost done. Now, we need to fix the PHI nodes
2773   // that we vectorized. The PHI nodes are currently empty because we did
2774   // not want to introduce cycles. Notice that the remaining PHI nodes
2775   // that we need to fix are reduction variables.
2776
2777   // Create the 'reduced' values for each of the induction vars.
2778   // The reduced values are the vector values that we scalarize and combine
2779   // after the loop is finished.
2780   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2781        it != e; ++it) {
2782     PHINode *RdxPhi = *it;
2783     assert(RdxPhi && "Unable to recover vectorized PHI");
2784
2785     // Find the reduction variable descriptor.
2786     assert(Legal->getReductionVars()->count(RdxPhi) &&
2787            "Unable to find the reduction variable");
2788     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2789     (*Legal->getReductionVars())[RdxPhi];
2790
2791     setDebugLocFromInst(Builder, RdxDesc.StartValue);
2792
2793     // We need to generate a reduction vector from the incoming scalar.
2794     // To do so, we need to generate the 'identity' vector and override
2795     // one of the elements with the incoming scalar reduction. We need
2796     // to do it in the vector-loop preheader.
2797     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2798
2799     // This is the vector-clone of the value that leaves the loop.
2800     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2801     Type *VecTy = VectorExit[0]->getType();
2802
2803     // Find the reduction identity variable. Zero for addition, or, xor,
2804     // one for multiplication, -1 for And.
2805     Value *Identity;
2806     Value *VectorStart;
2807     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2808         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2809       // MinMax reduction have the start value as their identify.
2810       if (VF == 1) {
2811         VectorStart = Identity = RdxDesc.StartValue;
2812       } else {
2813         VectorStart = Identity = Builder.CreateVectorSplat(VF,
2814                                                            RdxDesc.StartValue,
2815                                                            "minmax.ident");
2816       }
2817     } else {
2818       // Handle other reduction kinds:
2819       Constant *Iden =
2820       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2821                                                       VecTy->getScalarType());
2822       if (VF == 1) {
2823         Identity = Iden;
2824         // This vector is the Identity vector where the first element is the
2825         // incoming scalar reduction.
2826         VectorStart = RdxDesc.StartValue;
2827       } else {
2828         Identity = ConstantVector::getSplat(VF, Iden);
2829
2830         // This vector is the Identity vector where the first element is the
2831         // incoming scalar reduction.
2832         VectorStart = Builder.CreateInsertElement(Identity,
2833                                                   RdxDesc.StartValue, Zero);
2834       }
2835     }
2836
2837     // Fix the vector-loop phi.
2838     // We created the induction variable so we know that the
2839     // preheader is the first entry.
2840     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2841
2842     // Reductions do not have to start at zero. They can start with
2843     // any loop invariant values.
2844     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2845     BasicBlock *Latch = OrigLoop->getLoopLatch();
2846     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2847     VectorParts &Val = getVectorValue(LoopVal);
2848     for (unsigned part = 0; part < UF; ++part) {
2849       // Make sure to add the reduction stat value only to the
2850       // first unroll part.
2851       Value *StartVal = (part == 0) ? VectorStart : Identity;
2852       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2853       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2854                                                   LoopVectorBody.back());
2855     }
2856
2857     // Before each round, move the insertion point right between
2858     // the PHIs and the values we are going to write.
2859     // This allows us to write both PHINodes and the extractelement
2860     // instructions.
2861     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2862
2863     VectorParts RdxParts;
2864     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2865     for (unsigned part = 0; part < UF; ++part) {
2866       // This PHINode contains the vectorized reduction variable, or
2867       // the initial value vector, if we bypass the vector loop.
2868       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2869       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2870       Value *StartVal = (part == 0) ? VectorStart : Identity;
2871       for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2872         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2873       NewPhi->addIncoming(RdxExitVal[part],
2874                           LoopVectorBody.back());
2875       RdxParts.push_back(NewPhi);
2876     }
2877
2878     // Reduce all of the unrolled parts into a single vector.
2879     Value *ReducedPartRdx = RdxParts[0];
2880     unsigned Op = getReductionBinOp(RdxDesc.Kind);
2881     setDebugLocFromInst(Builder, ReducedPartRdx);
2882     for (unsigned part = 1; part < UF; ++part) {
2883       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2884         // Floating point operations had to be 'fast' to enable the reduction.
2885         ReducedPartRdx = addFastMathFlag(
2886             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2887                                 ReducedPartRdx, "bin.rdx"));
2888       else
2889         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2890                                         ReducedPartRdx, RdxParts[part]);
2891     }
2892
2893     if (VF > 1) {
2894       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2895       // and vector ops, reducing the set of values being computed by half each
2896       // round.
2897       assert(isPowerOf2_32(VF) &&
2898              "Reduction emission only supported for pow2 vectors!");
2899       Value *TmpVec = ReducedPartRdx;
2900       SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2901       for (unsigned i = VF; i != 1; i >>= 1) {
2902         // Move the upper half of the vector to the lower half.
2903         for (unsigned j = 0; j != i/2; ++j)
2904           ShuffleMask[j] = Builder.getInt32(i/2 + j);
2905
2906         // Fill the rest of the mask with undef.
2907         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2908                   UndefValue::get(Builder.getInt32Ty()));
2909
2910         Value *Shuf =
2911         Builder.CreateShuffleVector(TmpVec,
2912                                     UndefValue::get(TmpVec->getType()),
2913                                     ConstantVector::get(ShuffleMask),
2914                                     "rdx.shuf");
2915
2916         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2917           // Floating point operations had to be 'fast' to enable the reduction.
2918           TmpVec = addFastMathFlag(Builder.CreateBinOp(
2919               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2920         else
2921           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2922       }
2923
2924       // The result is in the first element of the vector.
2925       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2926                                                     Builder.getInt32(0));
2927     }
2928
2929     // Create a phi node that merges control-flow from the backedge-taken check
2930     // block and the middle block.
2931     PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2932                                           LoopScalarPreHeader->getTerminator());
2933     BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2934     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2935
2936     // Now, we need to fix the users of the reduction variable
2937     // inside and outside of the scalar remainder loop.
2938     // We know that the loop is in LCSSA form. We need to update the
2939     // PHI nodes in the exit blocks.
2940     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2941          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2942       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2943       if (!LCSSAPhi) break;
2944
2945       // All PHINodes need to have a single entry edge, or two if
2946       // we already fixed them.
2947       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2948
2949       // We found our reduction value exit-PHI. Update it with the
2950       // incoming bypass edge.
2951       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2952         // Add an edge coming from the bypass.
2953         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2954         break;
2955       }
2956     }// end of the LCSSA phi scan.
2957
2958     // Fix the scalar loop reduction variable with the incoming reduction sum
2959     // from the vector body and from the backedge value.
2960     int IncomingEdgeBlockIdx =
2961     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2962     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2963     // Pick the other block.
2964     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2965     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2966     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2967   }// end of for each redux variable.
2968
2969   fixLCSSAPHIs();
2970
2971   // Remove redundant induction instructions.
2972   cse(LoopVectorBody);
2973 }
2974
2975 void InnerLoopVectorizer::fixLCSSAPHIs() {
2976   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2977        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2978     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2979     if (!LCSSAPhi) break;
2980     if (LCSSAPhi->getNumIncomingValues() == 1)
2981       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2982                             LoopMiddleBlock);
2983   }
2984 }
2985
2986 InnerLoopVectorizer::VectorParts
2987 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2988   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2989          "Invalid edge");
2990
2991   // Look for cached value.
2992   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2993   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2994   if (ECEntryIt != MaskCache.end())
2995     return ECEntryIt->second;
2996
2997   VectorParts SrcMask = createBlockInMask(Src);
2998
2999   // The terminator has to be a branch inst!
3000   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3001   assert(BI && "Unexpected terminator found");
3002
3003   if (BI->isConditional()) {
3004     VectorParts EdgeMask = getVectorValue(BI->getCondition());
3005
3006     if (BI->getSuccessor(0) != Dst)
3007       for (unsigned part = 0; part < UF; ++part)
3008         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3009
3010     for (unsigned part = 0; part < UF; ++part)
3011       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3012
3013     MaskCache[Edge] = EdgeMask;
3014     return EdgeMask;
3015   }
3016
3017   MaskCache[Edge] = SrcMask;
3018   return SrcMask;
3019 }
3020
3021 InnerLoopVectorizer::VectorParts
3022 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3023   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3024
3025   // Loop incoming mask is all-one.
3026   if (OrigLoop->getHeader() == BB) {
3027     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3028     return getVectorValue(C);
3029   }
3030
3031   // This is the block mask. We OR all incoming edges, and with zero.
3032   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3033   VectorParts BlockMask = getVectorValue(Zero);
3034
3035   // For each pred:
3036   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3037     VectorParts EM = createEdgeMask(*it, BB);
3038     for (unsigned part = 0; part < UF; ++part)
3039       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3040   }
3041
3042   return BlockMask;
3043 }
3044
3045 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3046                                               InnerLoopVectorizer::VectorParts &Entry,
3047                                               unsigned UF, unsigned VF, PhiVector *PV) {
3048   PHINode* P = cast<PHINode>(PN);
3049   // Handle reduction variables:
3050   if (Legal->getReductionVars()->count(P)) {
3051     for (unsigned part = 0; part < UF; ++part) {
3052       // This is phase one of vectorizing PHIs.
3053       Type *VecTy = (VF == 1) ? PN->getType() :
3054       VectorType::get(PN->getType(), VF);
3055       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3056                                     LoopVectorBody.back()-> getFirstInsertionPt());
3057     }
3058     PV->push_back(P);
3059     return;
3060   }
3061
3062   setDebugLocFromInst(Builder, P);
3063   // Check for PHI nodes that are lowered to vector selects.
3064   if (P->getParent() != OrigLoop->getHeader()) {
3065     // We know that all PHIs in non-header blocks are converted into
3066     // selects, so we don't have to worry about the insertion order and we
3067     // can just use the builder.
3068     // At this point we generate the predication tree. There may be
3069     // duplications since this is a simple recursive scan, but future
3070     // optimizations will clean it up.
3071
3072     unsigned NumIncoming = P->getNumIncomingValues();
3073
3074     // Generate a sequence of selects of the form:
3075     // SELECT(Mask3, In3,
3076     //      SELECT(Mask2, In2,
3077     //                   ( ...)))
3078     for (unsigned In = 0; In < NumIncoming; In++) {
3079       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3080                                         P->getParent());
3081       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3082
3083       for (unsigned part = 0; part < UF; ++part) {
3084         // We might have single edge PHIs (blocks) - use an identity
3085         // 'select' for the first PHI operand.
3086         if (In == 0)
3087           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3088                                              In0[part]);
3089         else
3090           // Select between the current value and the previous incoming edge
3091           // based on the incoming mask.
3092           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3093                                              Entry[part], "predphi");
3094       }
3095     }
3096     return;
3097   }
3098
3099   // This PHINode must be an induction variable.
3100   // Make sure that we know about it.
3101   assert(Legal->getInductionVars()->count(P) &&
3102          "Not an induction variable");
3103
3104   LoopVectorizationLegality::InductionInfo II =
3105   Legal->getInductionVars()->lookup(P);
3106
3107   switch (II.IK) {
3108     case LoopVectorizationLegality::IK_NoInduction:
3109       llvm_unreachable("Unknown induction");
3110     case LoopVectorizationLegality::IK_IntInduction: {
3111       assert(P->getType() == II.StartValue->getType() && "Types must match");
3112       Type *PhiTy = P->getType();
3113       Value *Broadcasted;
3114       if (P == OldInduction) {
3115         // Handle the canonical induction variable. We might have had to
3116         // extend the type.
3117         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3118       } else {
3119         // Handle other induction variables that are now based on the
3120         // canonical one.
3121         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3122                                                  "normalized.idx");
3123         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3124         Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
3125                                         "offset.idx");
3126       }
3127       Broadcasted = getBroadcastInstrs(Broadcasted);
3128       // After broadcasting the induction variable we need to make the vector
3129       // consecutive by adding 0, 1, 2, etc.
3130       for (unsigned part = 0; part < UF; ++part)
3131         Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
3132       return;
3133     }
3134     case LoopVectorizationLegality::IK_ReverseIntInduction:
3135     case LoopVectorizationLegality::IK_PtrInduction:
3136     case LoopVectorizationLegality::IK_ReversePtrInduction:
3137       // Handle reverse integer and pointer inductions.
3138       Value *StartIdx = ExtendedIdx;
3139       // This is the normalized GEP that starts counting at zero.
3140       Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
3141                                                "normalized.idx");
3142
3143       // Handle the reverse integer induction variable case.
3144       if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
3145         IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
3146         Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
3147                                                "resize.norm.idx");
3148         Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
3149                                                "reverse.idx");
3150
3151         // This is a new value so do not hoist it out.
3152         Value *Broadcasted = getBroadcastInstrs(ReverseInd);
3153         // After broadcasting the induction variable we need to make the
3154         // vector consecutive by adding  ... -3, -2, -1, 0.
3155         for (unsigned part = 0; part < UF; ++part)
3156           Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
3157                                              true);
3158         return;
3159       }
3160
3161       // Handle the pointer induction variable case.
3162       assert(P->getType()->isPointerTy() && "Unexpected type.");
3163
3164       // Is this a reverse induction ptr or a consecutive induction ptr.
3165       bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
3166                       II.IK);
3167
3168       // This is the vector of results. Notice that we don't generate
3169       // vector geps because scalar geps result in better code.
3170       for (unsigned part = 0; part < UF; ++part) {
3171         if (VF == 1) {
3172           int EltIndex = (part) * (Reverse ? -1 : 1);
3173           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3174           Value *GlobalIdx;
3175           if (Reverse)
3176             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3177           else
3178             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3179
3180           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3181                                              "next.gep");
3182           Entry[part] = SclrGep;
3183           continue;
3184         }
3185
3186         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3187         for (unsigned int i = 0; i < VF; ++i) {
3188           int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
3189           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3190           Value *GlobalIdx;
3191           if (!Reverse)
3192             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3193           else
3194             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3195
3196           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3197                                              "next.gep");
3198           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3199                                                Builder.getInt32(i),
3200                                                "insert.gep");
3201         }
3202         Entry[part] = VecVal;
3203       }
3204       return;
3205   }
3206 }
3207
3208 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3209   // For each instruction in the old loop.
3210   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3211     VectorParts &Entry = WidenMap.get(it);
3212     switch (it->getOpcode()) {
3213     case Instruction::Br:
3214       // Nothing to do for PHIs and BR, since we already took care of the
3215       // loop control flow instructions.
3216       continue;
3217     case Instruction::PHI:{
3218       // Vectorize PHINodes.
3219       widenPHIInstruction(it, Entry, UF, VF, PV);
3220       continue;
3221     }// End of PHI.
3222
3223     case Instruction::Add:
3224     case Instruction::FAdd:
3225     case Instruction::Sub:
3226     case Instruction::FSub:
3227     case Instruction::Mul:
3228     case Instruction::FMul:
3229     case Instruction::UDiv:
3230     case Instruction::SDiv:
3231     case Instruction::FDiv:
3232     case Instruction::URem:
3233     case Instruction::SRem:
3234     case Instruction::FRem:
3235     case Instruction::Shl:
3236     case Instruction::LShr:
3237     case Instruction::AShr:
3238     case Instruction::And:
3239     case Instruction::Or:
3240     case Instruction::Xor: {
3241       // Just widen binops.
3242       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3243       setDebugLocFromInst(Builder, BinOp);
3244       VectorParts &A = getVectorValue(it->getOperand(0));
3245       VectorParts &B = getVectorValue(it->getOperand(1));
3246
3247       // Use this vector value for all users of the original instruction.
3248       for (unsigned Part = 0; Part < UF; ++Part) {
3249         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3250
3251         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3252           VecOp->copyIRFlags(BinOp);
3253
3254         Entry[Part] = V;
3255       }
3256
3257       propagateMetadata(Entry, it);
3258       break;
3259     }
3260     case Instruction::Select: {
3261       // Widen selects.
3262       // If the selector is loop invariant we can create a select
3263       // instruction with a scalar condition. Otherwise, use vector-select.
3264       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3265                                                OrigLoop);
3266       setDebugLocFromInst(Builder, it);
3267
3268       // The condition can be loop invariant  but still defined inside the
3269       // loop. This means that we can't just use the original 'cond' value.
3270       // We have to take the 'vectorized' value and pick the first lane.
3271       // Instcombine will make this a no-op.
3272       VectorParts &Cond = getVectorValue(it->getOperand(0));
3273       VectorParts &Op0  = getVectorValue(it->getOperand(1));
3274       VectorParts &Op1  = getVectorValue(it->getOperand(2));
3275
3276       Value *ScalarCond = (VF == 1) ? Cond[0] :
3277         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3278
3279       for (unsigned Part = 0; Part < UF; ++Part) {
3280         Entry[Part] = Builder.CreateSelect(
3281           InvariantCond ? ScalarCond : Cond[Part],
3282           Op0[Part],
3283           Op1[Part]);
3284       }
3285
3286       propagateMetadata(Entry, it);
3287       break;
3288     }
3289
3290     case Instruction::ICmp:
3291     case Instruction::FCmp: {
3292       // Widen compares. Generate vector compares.
3293       bool FCmp = (it->getOpcode() == Instruction::FCmp);
3294       CmpInst *Cmp = dyn_cast<CmpInst>(it);
3295       setDebugLocFromInst(Builder, it);
3296       VectorParts &A = getVectorValue(it->getOperand(0));
3297       VectorParts &B = getVectorValue(it->getOperand(1));
3298       for (unsigned Part = 0; Part < UF; ++Part) {
3299         Value *C = nullptr;
3300         if (FCmp)
3301           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3302         else
3303           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3304         Entry[Part] = C;
3305       }
3306
3307       propagateMetadata(Entry, it);