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