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