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