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