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