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