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