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