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