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