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