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