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