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