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