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