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