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 "LoopVectorizationPlanner.h"
51 #include "llvm/ADT/APInt.h"
52 #include "llvm/ADT/ArrayRef.h"
53 #include "llvm/ADT/DenseMap.h"
54 #include "llvm/ADT/DenseMapInfo.h"
55 #include "llvm/ADT/Hashing.h"
56 #include "llvm/ADT/MapVector.h"
57 #include "llvm/ADT/None.h"
58 #include "llvm/ADT/Optional.h"
59 #include "llvm/ADT/SCCIterator.h"
60 #include "llvm/ADT/STLExtras.h"
61 #include "llvm/ADT/SetVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/SmallSet.h"
64 #include "llvm/ADT/SmallVector.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/ADT/StringRef.h"
67 #include "llvm/ADT/Twine.h"
68 #include "llvm/ADT/iterator_range.h"
69 #include "llvm/Analysis/AssumptionCache.h"
70 #include "llvm/Analysis/BasicAliasAnalysis.h"
71 #include "llvm/Analysis/BlockFrequencyInfo.h"
72 #include "llvm/Analysis/CodeMetrics.h"
73 #include "llvm/Analysis/DemandedBits.h"
74 #include "llvm/Analysis/GlobalsModRef.h"
75 #include "llvm/Analysis/LoopAccessAnalysis.h"
76 #include "llvm/Analysis/LoopAnalysisManager.h"
77 #include "llvm/Analysis/LoopInfo.h"
78 #include "llvm/Analysis/LoopIterator.h"
79 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
80 #include "llvm/Analysis/ScalarEvolution.h"
81 #include "llvm/Analysis/ScalarEvolutionExpander.h"
82 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/TargetTransformInfo.h"
85 #include "llvm/Analysis/VectorUtils.h"
86 #include "llvm/IR/Attributes.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/Constant.h"
90 #include "llvm/IR/Constants.h"
91 #include "llvm/IR/DataLayout.h"
92 #include "llvm/IR/DebugInfoMetadata.h"
93 #include "llvm/IR/DebugLoc.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/DiagnosticInfo.h"
96 #include "llvm/IR/Dominators.h"
97 #include "llvm/IR/Function.h"
98 #include "llvm/IR/IRBuilder.h"
99 #include "llvm/IR/InstrTypes.h"
100 #include "llvm/IR/Instruction.h"
101 #include "llvm/IR/Instructions.h"
102 #include "llvm/IR/IntrinsicInst.h"
103 #include "llvm/IR/Intrinsics.h"
104 #include "llvm/IR/LLVMContext.h"
105 #include "llvm/IR/Metadata.h"
106 #include "llvm/IR/Module.h"
107 #include "llvm/IR/Operator.h"
108 #include "llvm/IR/Type.h"
109 #include "llvm/IR/Use.h"
110 #include "llvm/IR/User.h"
111 #include "llvm/IR/Value.h"
112 #include "llvm/IR/ValueHandle.h"
113 #include "llvm/IR/Verifier.h"
114 #include "llvm/Pass.h"
115 #include "llvm/Support/Casting.h"
116 #include "llvm/Support/CommandLine.h"
117 #include "llvm/Support/Compiler.h"
118 #include "llvm/Support/Debug.h"
119 #include "llvm/Support/ErrorHandling.h"
120 #include "llvm/Support/MathExtras.h"
121 #include "llvm/Support/raw_ostream.h"
122 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
123 #include "llvm/Transforms/Utils/LoopSimplify.h"
124 #include "llvm/Transforms/Utils/LoopUtils.h"
125 #include "llvm/Transforms/Utils/LoopVersioning.h"
126 #include <algorithm>
127 #include <cassert>
128 #include <cstdint>
129 #include <cstdlib>
130 #include <functional>
131 #include <iterator>
132 #include <limits>
133 #include <memory>
134 #include <string>
135 #include <tuple>
136 #include <utility>
137 #include <vector>
138 
139 using namespace llvm;
140 
141 #define LV_NAME "loop-vectorize"
142 #define DEBUG_TYPE LV_NAME
143 
144 STATISTIC(LoopsVectorized, "Number of loops vectorized");
145 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
146 
147 static cl::opt<bool>
148     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
149                        cl::desc("Enable if-conversion during vectorization."));
150 
151 /// Loops with a known constant trip count below this number are vectorized only
152 /// if no scalar iteration overheads are incurred.
153 static cl::opt<unsigned> TinyTripCountVectorThreshold(
154     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
155     cl::desc("Loops with a constant trip count that is smaller than this "
156              "value are vectorized only if no scalar iteration overheads "
157              "are incurred."));
158 
159 static cl::opt<bool> MaximizeBandwidth(
160     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
161     cl::desc("Maximize bandwidth when selecting vectorization factor which "
162              "will be determined by the smallest type in loop."));
163 
164 static cl::opt<bool> EnableInterleavedMemAccesses(
165     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
166     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
167 
168 /// Maximum factor for an interleaved memory access.
169 static cl::opt<unsigned> MaxInterleaveGroupFactor(
170     "max-interleave-group-factor", cl::Hidden,
171     cl::desc("Maximum factor for an interleaved access group (default = 8)"),
172     cl::init(8));
173 
174 /// We don't interleave loops with a known constant trip count below this
175 /// number.
176 static const unsigned TinyTripCountInterleaveThreshold = 128;
177 
178 static cl::opt<unsigned> ForceTargetNumScalarRegs(
179     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
180     cl::desc("A flag that overrides the target's number of scalar registers."));
181 
182 static cl::opt<unsigned> ForceTargetNumVectorRegs(
183     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
184     cl::desc("A flag that overrides the target's number of vector registers."));
185 
186 /// Maximum vectorization interleave count.
187 static const unsigned MaxInterleaveFactor = 16;
188 
189 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
190     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
191     cl::desc("A flag that overrides the target's max interleave factor for "
192              "scalar loops."));
193 
194 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
195     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
196     cl::desc("A flag that overrides the target's max interleave factor for "
197              "vectorized loops."));
198 
199 static cl::opt<unsigned> ForceTargetInstructionCost(
200     "force-target-instruction-cost", cl::init(0), cl::Hidden,
201     cl::desc("A flag that overrides the target's expected cost for "
202              "an instruction to a single constant value. Mostly "
203              "useful for getting consistent testing."));
204 
205 static cl::opt<unsigned> SmallLoopCost(
206     "small-loop-cost", cl::init(20), cl::Hidden,
207     cl::desc(
208         "The cost of a loop that is considered 'small' by the interleaver."));
209 
210 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
211     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
212     cl::desc("Enable the use of the block frequency analysis to access PGO "
213              "heuristics minimizing code growth in cold regions and being more "
214              "aggressive in hot regions."));
215 
216 // Runtime interleave loops for load/store throughput.
217 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
218     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
219     cl::desc(
220         "Enable runtime interleaving until load/store ports are saturated"));
221 
222 /// The number of stores in a loop that are allowed to need predication.
223 static cl::opt<unsigned> NumberOfStoresToPredicate(
224     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
225     cl::desc("Max number of stores to be predicated behind an if."));
226 
227 static cl::opt<bool> EnableIndVarRegisterHeur(
228     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
229     cl::desc("Count the induction variable only once when interleaving"));
230 
231 static cl::opt<bool> EnableCondStoresVectorization(
232     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
233     cl::desc("Enable if predication of stores during vectorization."));
234 
235 static cl::opt<unsigned> MaxNestedScalarReductionIC(
236     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
237     cl::desc("The maximum interleave count to use when interleaving a scalar "
238              "reduction in a nested loop."));
239 
240 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
241     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
242     cl::desc("The maximum allowed number of runtime memory checks with a "
243              "vectorize(enable) pragma."));
244 
245 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
246     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
247     cl::desc("The maximum number of SCEV checks allowed."));
248 
249 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
250     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
251     cl::desc("The maximum number of SCEV checks allowed with a "
252              "vectorize(enable) pragma"));
253 
254 /// Create an analysis remark that explains why vectorization failed
255 ///
256 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
257 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
258 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
259 /// the location of the remark.  \return the remark object that can be
260 /// streamed to.
261 static OptimizationRemarkAnalysis
262 createMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop,
263                      Instruction *I = nullptr) {
264   Value *CodeRegion = TheLoop->getHeader();
265   DebugLoc DL = TheLoop->getStartLoc();
266 
267   if (I) {
268     CodeRegion = I->getParent();
269     // If there is no debug location attached to the instruction, revert back to
270     // using the loop's.
271     if (I->getDebugLoc())
272       DL = I->getDebugLoc();
273   }
274 
275   OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
276   R << "loop not vectorized: ";
277   return R;
278 }
279 
280 namespace {
281 
282 class LoopVectorizationRequirements;
283 
284 } // end anonymous namespace
285 
286 /// Returns true if the given loop body has a cycle, excluding the loop
287 /// itself.
288 static bool hasCyclesInLoopBody(const Loop &L) {
289   if (!L.empty())
290     return true;
291 
292   for (const auto &SCC :
293        make_range(scc_iterator<Loop, LoopBodyTraits>::begin(L),
294                   scc_iterator<Loop, LoopBodyTraits>::end(L))) {
295     if (SCC.size() > 1) {
296       DEBUG(dbgs() << "LVL: Detected a cycle in the loop body:\n");
297       DEBUG(L.dump());
298       return true;
299     }
300   }
301   return false;
302 }
303 
304 /// A helper function for converting Scalar types to vector types.
305 /// If the incoming type is void, we return void. If the VF is 1, we return
306 /// the scalar type.
307 static Type *ToVectorTy(Type *Scalar, unsigned VF) {
308   if (Scalar->isVoidTy() || VF == 1)
309     return Scalar;
310   return VectorType::get(Scalar, VF);
311 }
312 
313 // FIXME: The following helper functions have multiple implementations
314 // in the project. They can be effectively organized in a common Load/Store
315 // utilities unit.
316 
317 /// A helper function that returns the pointer operand of a load or store
318 /// instruction.
319 static Value *getPointerOperand(Value *I) {
320   if (auto *LI = dyn_cast<LoadInst>(I))
321     return LI->getPointerOperand();
322   if (auto *SI = dyn_cast<StoreInst>(I))
323     return SI->getPointerOperand();
324   return nullptr;
325 }
326 
327 /// A helper function that returns the type of loaded or stored value.
328 static Type *getMemInstValueType(Value *I) {
329   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
330          "Expected Load or Store instruction");
331   if (auto *LI = dyn_cast<LoadInst>(I))
332     return LI->getType();
333   return cast<StoreInst>(I)->getValueOperand()->getType();
334 }
335 
336 /// A helper function that returns the alignment of load or store instruction.
337 static unsigned getMemInstAlignment(Value *I) {
338   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
339          "Expected Load or Store instruction");
340   if (auto *LI = dyn_cast<LoadInst>(I))
341     return LI->getAlignment();
342   return cast<StoreInst>(I)->getAlignment();
343 }
344 
345 /// A helper function that returns the address space of the pointer operand of
346 /// load or store instruction.
347 static unsigned getMemInstAddressSpace(Value *I) {
348   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
349          "Expected Load or Store instruction");
350   if (auto *LI = dyn_cast<LoadInst>(I))
351     return LI->getPointerAddressSpace();
352   return cast<StoreInst>(I)->getPointerAddressSpace();
353 }
354 
355 /// A helper function that returns true if the given type is irregular. The
356 /// type is irregular if its allocated size doesn't equal the store size of an
357 /// element of the corresponding vector type at the given vectorization factor.
358 static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
359   // Determine if an array of VF elements of type Ty is "bitcast compatible"
360   // with a <VF x Ty> vector.
361   if (VF > 1) {
362     auto *VectorTy = VectorType::get(Ty, VF);
363     return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
364   }
365 
366   // If the vectorization factor is one, we just check if an array of type Ty
367   // requires padding between elements.
368   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
369 }
370 
371 /// A helper function that returns the reciprocal of the block probability of
372 /// predicated blocks. If we return X, we are assuming the predicated block
373 /// will execute once for every X iterations of the loop header.
374 ///
375 /// TODO: We should use actual block probability here, if available. Currently,
376 ///       we always assume predicated blocks have a 50% chance of executing.
377 static unsigned getReciprocalPredBlockProb() { return 2; }
378 
379 /// A helper function that adds a 'fast' flag to floating-point operations.
380 static Value *addFastMathFlag(Value *V) {
381   if (isa<FPMathOperator>(V)) {
382     FastMathFlags Flags;
383     Flags.setFast();
384     cast<Instruction>(V)->setFastMathFlags(Flags);
385   }
386   return V;
387 }
388 
389 /// A helper function that returns an integer or floating-point constant with
390 /// value C.
391 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
392   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
393                            : ConstantFP::get(Ty, C);
394 }
395 
396 namespace llvm {
397 
398 /// InnerLoopVectorizer vectorizes loops which contain only one basic
399 /// block to a specified vectorization factor (VF).
400 /// This class performs the widening of scalars into vectors, or multiple
401 /// scalars. This class also implements the following features:
402 /// * It inserts an epilogue loop for handling loops that don't have iteration
403 ///   counts that are known to be a multiple of the vectorization factor.
404 /// * It handles the code generation for reduction variables.
405 /// * Scalarization (implementation using scalars) of un-vectorizable
406 ///   instructions.
407 /// InnerLoopVectorizer does not perform any vectorization-legality
408 /// checks, and relies on the caller to check for the different legality
409 /// aspects. The InnerLoopVectorizer relies on the
410 /// LoopVectorizationLegality class to provide information about the induction
411 /// and reduction variables that were found to a given vectorization factor.
412 class InnerLoopVectorizer {
413 public:
414   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
415                       LoopInfo *LI, DominatorTree *DT,
416                       const TargetLibraryInfo *TLI,
417                       const TargetTransformInfo *TTI, AssumptionCache *AC,
418                       OptimizationRemarkEmitter *ORE, unsigned VecWidth,
419                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
420                       LoopVectorizationCostModel *CM)
421       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
422         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
423         Builder(PSE.getSE()->getContext()),
424         VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {}
425   virtual ~InnerLoopVectorizer() = default;
426 
427   /// Create a new empty loop. Unlink the old loop and connect the new one.
428   /// Return the pre-header block of the new loop.
429   BasicBlock *createVectorizedLoopSkeleton();
430 
431   /// Widen a single instruction within the innermost loop.
432   void widenInstruction(Instruction &I);
433 
434   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
435   void fixVectorizedLoop();
436 
437   // Return true if any runtime check is added.
438   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
439 
440   /// A type for vectorized values in the new loop. Each value from the
441   /// original loop, when vectorized, is represented by UF vector values in the
442   /// new unrolled loop, where UF is the unroll factor.
443   using VectorParts = SmallVector<Value *, 2>;
444 
445   /// Vectorize a single PHINode in a block. This method handles the induction
446   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
447   /// arbitrary length vectors.
448   void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
449 
450   /// A helper function to scalarize a single Instruction in the innermost loop.
451   /// Generates a sequence of scalar instances for each lane between \p MinLane
452   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
453   /// inclusive..
454   void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance,
455                             bool IfPredicateInstr);
456 
457   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
458   /// is provided, the integer induction variable will first be truncated to
459   /// the corresponding type.
460   void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
461 
462   /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
463   /// vector or scalar value on-demand if one is not yet available. When
464   /// vectorizing a loop, we visit the definition of an instruction before its
465   /// uses. When visiting the definition, we either vectorize or scalarize the
466   /// instruction, creating an entry for it in the corresponding map. (In some
467   /// cases, such as induction variables, we will create both vector and scalar
468   /// entries.) Then, as we encounter uses of the definition, we derive values
469   /// for each scalar or vector use unless such a value is already available.
470   /// For example, if we scalarize a definition and one of its uses is vector,
471   /// we build the required vector on-demand with an insertelement sequence
472   /// when visiting the use. Otherwise, if the use is scalar, we can use the
473   /// existing scalar definition.
474   ///
475   /// Return a value in the new loop corresponding to \p V from the original
476   /// loop at unroll index \p Part. If the value has already been vectorized,
477   /// the corresponding vector entry in VectorLoopValueMap is returned. If,
478   /// however, the value has a scalar entry in VectorLoopValueMap, we construct
479   /// a new vector value on-demand by inserting the scalar values into a vector
480   /// with an insertelement sequence. If the value has been neither vectorized
481   /// nor scalarized, it must be loop invariant, so we simply broadcast the
482   /// value into a vector.
483   Value *getOrCreateVectorValue(Value *V, unsigned Part);
484 
485   /// Return a value in the new loop corresponding to \p V from the original
486   /// loop at unroll and vector indices \p Instance. If the value has been
487   /// vectorized but not scalarized, the necessary extractelement instruction
488   /// will be generated.
489   Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
490 
491   /// Construct the vector value of a scalarized value \p V one lane at a time.
492   void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
493 
494   /// Try to vectorize the interleaved access group that \p Instr belongs to.
495   void vectorizeInterleaveGroup(Instruction *Instr);
496 
497   /// Vectorize Load and Store instructions, optionally masking the vector
498   /// operations if \p BlockInMask is non-null.
499   void vectorizeMemoryInstruction(Instruction *Instr,
500                                   VectorParts *BlockInMask = nullptr);
501 
502   /// \brief Set the debug location in the builder using the debug location in
503   /// the instruction.
504   void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
505 
506 protected:
507   friend class LoopVectorizationPlanner;
508 
509   /// A small list of PHINodes.
510   using PhiVector = SmallVector<PHINode *, 4>;
511 
512   /// A type for scalarized values in the new loop. Each value from the
513   /// original loop, when scalarized, is represented by UF x VF scalar values
514   /// in the new unrolled loop, where UF is the unroll factor and VF is the
515   /// vectorization factor.
516   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
517 
518   /// Set up the values of the IVs correctly when exiting the vector loop.
519   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
520                     Value *CountRoundDown, Value *EndValue,
521                     BasicBlock *MiddleBlock);
522 
523   /// Create a new induction variable inside L.
524   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
525                                    Value *Step, Instruction *DL);
526 
527   /// Handle all cross-iteration phis in the header.
528   void fixCrossIterationPHIs();
529 
530   /// Fix a first-order recurrence. This is the second phase of vectorizing
531   /// this phi node.
532   void fixFirstOrderRecurrence(PHINode *Phi);
533 
534   /// Fix a reduction cross-iteration phi. This is the second phase of
535   /// vectorizing this phi node.
536   void fixReduction(PHINode *Phi);
537 
538   /// \brief The Loop exit block may have single value PHI nodes with some
539   /// incoming value. While vectorizing we only handled real values
540   /// that were defined inside the loop and we should have one value for
541   /// each predecessor of its parent basic block. See PR14725.
542   void fixLCSSAPHIs();
543 
544   /// Iteratively sink the scalarized operands of a predicated instruction into
545   /// the block that was created for it.
546   void sinkScalarOperands(Instruction *PredInst);
547 
548   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
549   /// represented as.
550   void truncateToMinimalBitwidths();
551 
552   /// Insert the new loop to the loop hierarchy and pass manager
553   /// and update the analysis passes.
554   void updateAnalysis();
555 
556   /// Create a broadcast instruction. This method generates a broadcast
557   /// instruction (shuffle) for loop invariant values and for the induction
558   /// value. If this is the induction variable then we extend it to N, N+1, ...
559   /// this is needed because each iteration in the loop corresponds to a SIMD
560   /// element.
561   virtual Value *getBroadcastInstrs(Value *V);
562 
563   /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
564   /// to each vector element of Val. The sequence starts at StartIndex.
565   /// \p Opcode is relevant for FP induction variable.
566   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
567                                Instruction::BinaryOps Opcode =
568                                Instruction::BinaryOpsEnd);
569 
570   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
571   /// variable on which to base the steps, \p Step is the size of the step, and
572   /// \p EntryVal is the value from the original loop that maps to the steps.
573   /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it
574   /// can be a truncate instruction).
575   void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal,
576                         const InductionDescriptor &ID);
577 
578   /// Create a vector induction phi node based on an existing scalar one. \p
579   /// EntryVal is the value from the original loop that maps to the vector phi
580   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
581   /// truncate instruction, instead of widening the original IV, we widen a
582   /// version of the IV truncated to \p EntryVal's type.
583   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
584                                        Value *Step, Instruction *EntryVal);
585 
586   /// Returns true if an instruction \p I should be scalarized instead of
587   /// vectorized for the chosen vectorization factor.
588   bool shouldScalarizeInstruction(Instruction *I) const;
589 
590   /// Returns true if we should generate a scalar version of \p IV.
591   bool needsScalarInduction(Instruction *IV) const;
592 
593   /// If there is a cast involved in the induction variable \p ID, which should
594   /// be ignored in the vectorized loop body, this function records the
595   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
596   /// cast. We had already proved that the casted Phi is equal to the uncasted
597   /// Phi in the vectorized loop (under a runtime guard), and therefore
598   /// there is no need to vectorize the cast - the same value can be used in the
599   /// vector loop for both the Phi and the cast.
600   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
601   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
602   void recordVectorLoopValueForInductionCast (const InductionDescriptor &ID,
603                                               Value *VectorLoopValue,
604                                               unsigned Part,
605                                               unsigned Lane = UINT_MAX);
606 
607   /// Generate a shuffle sequence that will reverse the vector Vec.
608   virtual Value *reverseVector(Value *Vec);
609 
610   /// Returns (and creates if needed) the original loop trip count.
611   Value *getOrCreateTripCount(Loop *NewLoop);
612 
613   /// Returns (and creates if needed) the trip count of the widened loop.
614   Value *getOrCreateVectorTripCount(Loop *NewLoop);
615 
616   /// Returns a bitcasted value to the requested vector type.
617   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
618   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
619                                 const DataLayout &DL);
620 
621   /// Emit a bypass check to see if the vector trip count is zero, including if
622   /// it overflows.
623   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
624 
625   /// Emit a bypass check to see if all of the SCEV assumptions we've
626   /// had to make are correct.
627   void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
628 
629   /// Emit bypass checks to check any memory assumptions we may have made.
630   void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
631 
632   /// Add additional metadata to \p To that was not present on \p Orig.
633   ///
634   /// Currently this is used to add the noalias annotations based on the
635   /// inserted memchecks.  Use this for instructions that are *cloned* into the
636   /// vector loop.
637   void addNewMetadata(Instruction *To, const Instruction *Orig);
638 
639   /// Add metadata from one instruction to another.
640   ///
641   /// This includes both the original MDs from \p From and additional ones (\see
642   /// addNewMetadata).  Use this for *newly created* instructions in the vector
643   /// loop.
644   void addMetadata(Instruction *To, Instruction *From);
645 
646   /// \brief Similar to the previous function but it adds the metadata to a
647   /// vector of instructions.
648   void addMetadata(ArrayRef<Value *> To, Instruction *From);
649 
650   /// The original loop.
651   Loop *OrigLoop;
652 
653   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
654   /// dynamic knowledge to simplify SCEV expressions and converts them to a
655   /// more usable form.
656   PredicatedScalarEvolution &PSE;
657 
658   /// Loop Info.
659   LoopInfo *LI;
660 
661   /// Dominator Tree.
662   DominatorTree *DT;
663 
664   /// Alias Analysis.
665   AliasAnalysis *AA;
666 
667   /// Target Library Info.
668   const TargetLibraryInfo *TLI;
669 
670   /// Target Transform Info.
671   const TargetTransformInfo *TTI;
672 
673   /// Assumption Cache.
674   AssumptionCache *AC;
675 
676   /// Interface to emit optimization remarks.
677   OptimizationRemarkEmitter *ORE;
678 
679   /// \brief LoopVersioning.  It's only set up (non-null) if memchecks were
680   /// used.
681   ///
682   /// This is currently only used to add no-alias metadata based on the
683   /// memchecks.  The actually versioning is performed manually.
684   std::unique_ptr<LoopVersioning> LVer;
685 
686   /// The vectorization SIMD factor to use. Each vector will have this many
687   /// vector elements.
688   unsigned VF;
689 
690   /// The vectorization unroll factor to use. Each scalar is vectorized to this
691   /// many different vector instructions.
692   unsigned UF;
693 
694   /// The builder that we use
695   IRBuilder<> Builder;
696 
697   // --- Vectorization state ---
698 
699   /// The vector-loop preheader.
700   BasicBlock *LoopVectorPreHeader;
701 
702   /// The scalar-loop preheader.
703   BasicBlock *LoopScalarPreHeader;
704 
705   /// Middle Block between the vector and the scalar.
706   BasicBlock *LoopMiddleBlock;
707 
708   /// The ExitBlock of the scalar loop.
709   BasicBlock *LoopExitBlock;
710 
711   /// The vector loop body.
712   BasicBlock *LoopVectorBody;
713 
714   /// The scalar loop body.
715   BasicBlock *LoopScalarBody;
716 
717   /// A list of all bypass blocks. The first block is the entry of the loop.
718   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
719 
720   /// The new Induction variable which was added to the new block.
721   PHINode *Induction = nullptr;
722 
723   /// The induction variable of the old basic block.
724   PHINode *OldInduction = nullptr;
725 
726   /// Maps values from the original loop to their corresponding values in the
727   /// vectorized loop. A key value can map to either vector values, scalar
728   /// values or both kinds of values, depending on whether the key was
729   /// vectorized and scalarized.
730   VectorizerValueMap VectorLoopValueMap;
731 
732   /// Store instructions that were predicated.
733   SmallVector<Instruction *, 4> PredicatedInstructions;
734 
735   /// Trip count of the original loop.
736   Value *TripCount = nullptr;
737 
738   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
739   Value *VectorTripCount = nullptr;
740 
741   /// The legality analysis.
742   LoopVectorizationLegality *Legal;
743 
744   /// The profitablity analysis.
745   LoopVectorizationCostModel *Cost;
746 
747   // Record whether runtime checks are added.
748   bool AddedSafetyChecks = false;
749 
750   // Holds the end values for each induction variable. We save the end values
751   // so we can later fix-up the external users of the induction variables.
752   DenseMap<PHINode *, Value *> IVEndValues;
753 };
754 
755 class InnerLoopUnroller : public InnerLoopVectorizer {
756 public:
757   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
758                     LoopInfo *LI, DominatorTree *DT,
759                     const TargetLibraryInfo *TLI,
760                     const TargetTransformInfo *TTI, AssumptionCache *AC,
761                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
762                     LoopVectorizationLegality *LVL,
763                     LoopVectorizationCostModel *CM)
764       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
765                             UnrollFactor, LVL, CM) {}
766 
767 private:
768   Value *getBroadcastInstrs(Value *V) override;
769   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
770                        Instruction::BinaryOps Opcode =
771                        Instruction::BinaryOpsEnd) override;
772   Value *reverseVector(Value *Vec) override;
773 };
774 
775 } // end namespace llvm
776 
777 /// \brief Look for a meaningful debug location on the instruction or it's
778 /// operands.
779 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
780   if (!I)
781     return I;
782 
783   DebugLoc Empty;
784   if (I->getDebugLoc() != Empty)
785     return I;
786 
787   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
788     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
789       if (OpInst->getDebugLoc() != Empty)
790         return OpInst;
791   }
792 
793   return I;
794 }
795 
796 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
797   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
798     const DILocation *DIL = Inst->getDebugLoc();
799     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
800         !isa<DbgInfoIntrinsic>(Inst))
801       B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF));
802     else
803       B.SetCurrentDebugLocation(DIL);
804   } else
805     B.SetCurrentDebugLocation(DebugLoc());
806 }
807 
808 #ifndef NDEBUG
809 /// \return string containing a file name and a line # for the given loop.
810 static std::string getDebugLocString(const Loop *L) {
811   std::string Result;
812   if (L) {
813     raw_string_ostream OS(Result);
814     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
815       LoopDbgLoc.print(OS);
816     else
817       // Just print the module name.
818       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
819     OS.flush();
820   }
821   return Result;
822 }
823 #endif
824 
825 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
826                                          const Instruction *Orig) {
827   // If the loop was versioned with memchecks, add the corresponding no-alias
828   // metadata.
829   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
830     LVer->annotateInstWithNoAlias(To, Orig);
831 }
832 
833 void InnerLoopVectorizer::addMetadata(Instruction *To,
834                                       Instruction *From) {
835   propagateMetadata(To, From);
836   addNewMetadata(To, From);
837 }
838 
839 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
840                                       Instruction *From) {
841   for (Value *V : To) {
842     if (Instruction *I = dyn_cast<Instruction>(V))
843       addMetadata(I, From);
844   }
845 }
846 
847 namespace llvm {
848 
849 /// \brief The group of interleaved loads/stores sharing the same stride and
850 /// close to each other.
851 ///
852 /// Each member in this group has an index starting from 0, and the largest
853 /// index should be less than interleaved factor, which is equal to the absolute
854 /// value of the access's stride.
855 ///
856 /// E.g. An interleaved load group of factor 4:
857 ///        for (unsigned i = 0; i < 1024; i+=4) {
858 ///          a = A[i];                           // Member of index 0
859 ///          b = A[i+1];                         // Member of index 1
860 ///          d = A[i+3];                         // Member of index 3
861 ///          ...
862 ///        }
863 ///
864 ///      An interleaved store group of factor 4:
865 ///        for (unsigned i = 0; i < 1024; i+=4) {
866 ///          ...
867 ///          A[i]   = a;                         // Member of index 0
868 ///          A[i+1] = b;                         // Member of index 1
869 ///          A[i+2] = c;                         // Member of index 2
870 ///          A[i+3] = d;                         // Member of index 3
871 ///        }
872 ///
873 /// Note: the interleaved load group could have gaps (missing members), but
874 /// the interleaved store group doesn't allow gaps.
875 class InterleaveGroup {
876 public:
877   InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
878       : Align(Align), InsertPos(Instr) {
879     assert(Align && "The alignment should be non-zero");
880 
881     Factor = std::abs(Stride);
882     assert(Factor > 1 && "Invalid interleave factor");
883 
884     Reverse = Stride < 0;
885     Members[0] = Instr;
886   }
887 
888   bool isReverse() const { return Reverse; }
889   unsigned getFactor() const { return Factor; }
890   unsigned getAlignment() const { return Align; }
891   unsigned getNumMembers() const { return Members.size(); }
892 
893   /// \brief Try to insert a new member \p Instr with index \p Index and
894   /// alignment \p NewAlign. The index is related to the leader and it could be
895   /// negative if it is the new leader.
896   ///
897   /// \returns false if the instruction doesn't belong to the group.
898   bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
899     assert(NewAlign && "The new member's alignment should be non-zero");
900 
901     int Key = Index + SmallestKey;
902 
903     // Skip if there is already a member with the same index.
904     if (Members.count(Key))
905       return false;
906 
907     if (Key > LargestKey) {
908       // The largest index is always less than the interleave factor.
909       if (Index >= static_cast<int>(Factor))
910         return false;
911 
912       LargestKey = Key;
913     } else if (Key < SmallestKey) {
914       // The largest index is always less than the interleave factor.
915       if (LargestKey - Key >= static_cast<int>(Factor))
916         return false;
917 
918       SmallestKey = Key;
919     }
920 
921     // It's always safe to select the minimum alignment.
922     Align = std::min(Align, NewAlign);
923     Members[Key] = Instr;
924     return true;
925   }
926 
927   /// \brief Get the member with the given index \p Index
928   ///
929   /// \returns nullptr if contains no such member.
930   Instruction *getMember(unsigned Index) const {
931     int Key = SmallestKey + Index;
932     if (!Members.count(Key))
933       return nullptr;
934 
935     return Members.find(Key)->second;
936   }
937 
938   /// \brief Get the index for the given member. Unlike the key in the member
939   /// map, the index starts from 0.
940   unsigned getIndex(Instruction *Instr) const {
941     for (auto I : Members)
942       if (I.second == Instr)
943         return I.first - SmallestKey;
944 
945     llvm_unreachable("InterleaveGroup contains no such member");
946   }
947 
948   Instruction *getInsertPos() const { return InsertPos; }
949   void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
950 
951   /// Add metadata (e.g. alias info) from the instructions in this group to \p
952   /// NewInst.
953   ///
954   /// FIXME: this function currently does not add noalias metadata a'la
955   /// addNewMedata.  To do that we need to compute the intersection of the
956   /// noalias info from all members.
957   void addMetadata(Instruction *NewInst) const {
958     SmallVector<Value *, 4> VL;
959     std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
960                    [](std::pair<int, Instruction *> p) { return p.second; });
961     propagateMetadata(NewInst, VL);
962   }
963 
964 private:
965   unsigned Factor; // Interleave Factor.
966   bool Reverse;
967   unsigned Align;
968   DenseMap<int, Instruction *> Members;
969   int SmallestKey = 0;
970   int LargestKey = 0;
971 
972   // To avoid breaking dependences, vectorized instructions of an interleave
973   // group should be inserted at either the first load or the last store in
974   // program order.
975   //
976   // E.g. %even = load i32             // Insert Position
977   //      %add = add i32 %even         // Use of %even
978   //      %odd = load i32
979   //
980   //      store i32 %even
981   //      %odd = add i32               // Def of %odd
982   //      store i32 %odd               // Insert Position
983   Instruction *InsertPos;
984 };
985 } // end namespace llvm
986 
987 namespace {
988 
989 /// \brief Drive the analysis of interleaved memory accesses in the loop.
990 ///
991 /// Use this class to analyze interleaved accesses only when we can vectorize
992 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
993 /// on interleaved accesses is unsafe.
994 ///
995 /// The analysis collects interleave groups and records the relationships
996 /// between the member and the group in a map.
997 class InterleavedAccessInfo {
998 public:
999   InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
1000                         DominatorTree *DT, LoopInfo *LI)
1001       : PSE(PSE), TheLoop(L), DT(DT), LI(LI) {}
1002 
1003   ~InterleavedAccessInfo() {
1004     SmallSet<InterleaveGroup *, 4> DelSet;
1005     // Avoid releasing a pointer twice.
1006     for (auto &I : InterleaveGroupMap)
1007       DelSet.insert(I.second);
1008     for (auto *Ptr : DelSet)
1009       delete Ptr;
1010   }
1011 
1012   /// \brief Analyze the interleaved accesses and collect them in interleave
1013   /// groups. Substitute symbolic strides using \p Strides.
1014   void analyzeInterleaving(const ValueToValueMap &Strides);
1015 
1016   /// \brief Check if \p Instr belongs to any interleave group.
1017   bool isInterleaved(Instruction *Instr) const {
1018     return InterleaveGroupMap.count(Instr);
1019   }
1020 
1021   /// \brief Get the interleave group that \p Instr belongs to.
1022   ///
1023   /// \returns nullptr if doesn't have such group.
1024   InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
1025     if (InterleaveGroupMap.count(Instr))
1026       return InterleaveGroupMap.find(Instr)->second;
1027     return nullptr;
1028   }
1029 
1030   /// \brief Returns true if an interleaved group that may access memory
1031   /// out-of-bounds requires a scalar epilogue iteration for correctness.
1032   bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
1033 
1034   /// \brief Initialize the LoopAccessInfo used for dependence checking.
1035   void setLAI(const LoopAccessInfo *Info) { LAI = Info; }
1036 
1037 private:
1038   /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
1039   /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
1040   /// The interleaved access analysis can also add new predicates (for example
1041   /// by versioning strides of pointers).
1042   PredicatedScalarEvolution &PSE;
1043 
1044   Loop *TheLoop;
1045   DominatorTree *DT;
1046   LoopInfo *LI;
1047   const LoopAccessInfo *LAI = nullptr;
1048 
1049   /// True if the loop may contain non-reversed interleaved groups with
1050   /// out-of-bounds accesses. We ensure we don't speculatively access memory
1051   /// out-of-bounds by executing at least one scalar epilogue iteration.
1052   bool RequiresScalarEpilogue = false;
1053 
1054   /// Holds the relationships between the members and the interleave group.
1055   DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
1056 
1057   /// Holds dependences among the memory accesses in the loop. It maps a source
1058   /// access to a set of dependent sink accesses.
1059   DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
1060 
1061   /// \brief The descriptor for a strided memory access.
1062   struct StrideDescriptor {
1063     StrideDescriptor() = default;
1064     StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
1065                      unsigned Align)
1066         : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
1067 
1068     // The access's stride. It is negative for a reverse access.
1069     int64_t Stride = 0;
1070 
1071     // The scalar expression of this access.
1072     const SCEV *Scev = nullptr;
1073 
1074     // The size of the memory object.
1075     uint64_t Size = 0;
1076 
1077     // The alignment of this access.
1078     unsigned Align = 0;
1079   };
1080 
1081   /// \brief A type for holding instructions and their stride descriptors.
1082   using StrideEntry = std::pair<Instruction *, StrideDescriptor>;
1083 
1084   /// \brief Create a new interleave group with the given instruction \p Instr,
1085   /// stride \p Stride and alignment \p Align.
1086   ///
1087   /// \returns the newly created interleave group.
1088   InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
1089                                          unsigned Align) {
1090     assert(!InterleaveGroupMap.count(Instr) &&
1091            "Already in an interleaved access group");
1092     InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
1093     return InterleaveGroupMap[Instr];
1094   }
1095 
1096   /// \brief Release the group and remove all the relationships.
1097   void releaseGroup(InterleaveGroup *Group) {
1098     for (unsigned i = 0; i < Group->getFactor(); i++)
1099       if (Instruction *Member = Group->getMember(i))
1100         InterleaveGroupMap.erase(Member);
1101 
1102     delete Group;
1103   }
1104 
1105   /// \brief Collect all the accesses with a constant stride in program order.
1106   void collectConstStrideAccesses(
1107       MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
1108       const ValueToValueMap &Strides);
1109 
1110   /// \brief Returns true if \p Stride is allowed in an interleaved group.
1111   static bool isStrided(int Stride) {
1112     unsigned Factor = std::abs(Stride);
1113     return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1114   }
1115 
1116   /// \brief Returns true if \p BB is a predicated block.
1117   bool isPredicated(BasicBlock *BB) const {
1118     return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1119   }
1120 
1121   /// \brief Returns true if LoopAccessInfo can be used for dependence queries.
1122   bool areDependencesValid() const {
1123     return LAI && LAI->getDepChecker().getDependences();
1124   }
1125 
1126   /// \brief Returns true if memory accesses \p A and \p B can be reordered, if
1127   /// necessary, when constructing interleaved groups.
1128   ///
1129   /// \p A must precede \p B in program order. We return false if reordering is
1130   /// not necessary or is prevented because \p A and \p B may be dependent.
1131   bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
1132                                                  StrideEntry *B) const {
1133     // Code motion for interleaved accesses can potentially hoist strided loads
1134     // and sink strided stores. The code below checks the legality of the
1135     // following two conditions:
1136     //
1137     // 1. Potentially moving a strided load (B) before any store (A) that
1138     //    precedes B, or
1139     //
1140     // 2. Potentially moving a strided store (A) after any load or store (B)
1141     //    that A precedes.
1142     //
1143     // It's legal to reorder A and B if we know there isn't a dependence from A
1144     // to B. Note that this determination is conservative since some
1145     // dependences could potentially be reordered safely.
1146 
1147     // A is potentially the source of a dependence.
1148     auto *Src = A->first;
1149     auto SrcDes = A->second;
1150 
1151     // B is potentially the sink of a dependence.
1152     auto *Sink = B->first;
1153     auto SinkDes = B->second;
1154 
1155     // Code motion for interleaved accesses can't violate WAR dependences.
1156     // Thus, reordering is legal if the source isn't a write.
1157     if (!Src->mayWriteToMemory())
1158       return true;
1159 
1160     // At least one of the accesses must be strided.
1161     if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1162       return true;
1163 
1164     // If dependence information is not available from LoopAccessInfo,
1165     // conservatively assume the instructions can't be reordered.
1166     if (!areDependencesValid())
1167       return false;
1168 
1169     // If we know there is a dependence from source to sink, assume the
1170     // instructions can't be reordered. Otherwise, reordering is legal.
1171     return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink);
1172   }
1173 
1174   /// \brief Collect the dependences from LoopAccessInfo.
1175   ///
1176   /// We process the dependences once during the interleaved access analysis to
1177   /// enable constant-time dependence queries.
1178   void collectDependences() {
1179     if (!areDependencesValid())
1180       return;
1181     auto *Deps = LAI->getDepChecker().getDependences();
1182     for (auto Dep : *Deps)
1183       Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
1184   }
1185 };
1186 
1187 /// Utility class for getting and setting loop vectorizer hints in the form
1188 /// of loop metadata.
1189 /// This class keeps a number of loop annotations locally (as member variables)
1190 /// and can, upon request, write them back as metadata on the loop. It will
1191 /// initially scan the loop for existing metadata, and will update the local
1192 /// values based on information in the loop.
1193 /// We cannot write all values to metadata, as the mere presence of some info,
1194 /// for example 'force', means a decision has been made. So, we need to be
1195 /// careful NOT to add them if the user hasn't specifically asked so.
1196 class LoopVectorizeHints {
1197   enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE, HK_ISVECTORIZED };
1198 
1199   /// Hint - associates name and validation with the hint value.
1200   struct Hint {
1201     const char *Name;
1202     unsigned Value; // This may have to change for non-numeric values.
1203     HintKind Kind;
1204 
1205     Hint(const char *Name, unsigned Value, HintKind Kind)
1206         : Name(Name), Value(Value), Kind(Kind) {}
1207 
1208     bool validate(unsigned Val) {
1209       switch (Kind) {
1210       case HK_WIDTH:
1211         return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1212       case HK_UNROLL:
1213         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1214       case HK_FORCE:
1215         return (Val <= 1);
1216       case HK_ISVECTORIZED:
1217         return (Val==0 || Val==1);
1218       }
1219       return false;
1220     }
1221   };
1222 
1223   /// Vectorization width.
1224   Hint Width;
1225 
1226   /// Vectorization interleave factor.
1227   Hint Interleave;
1228 
1229   /// Vectorization forced
1230   Hint Force;
1231 
1232   /// Already Vectorized
1233   Hint IsVectorized;
1234 
1235   /// Return the loop metadata prefix.
1236   static StringRef Prefix() { return "llvm.loop."; }
1237 
1238   /// True if there is any unsafe math in the loop.
1239   bool PotentiallyUnsafe = false;
1240 
1241 public:
1242   enum ForceKind {
1243     FK_Undefined = -1, ///< Not selected.
1244     FK_Disabled = 0,   ///< Forcing disabled.
1245     FK_Enabled = 1,    ///< Forcing enabled.
1246   };
1247 
1248   LoopVectorizeHints(const Loop *L, bool DisableInterleaving,
1249                      OptimizationRemarkEmitter &ORE)
1250       : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1251               HK_WIDTH),
1252         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1253         Force("vectorize.enable", FK_Undefined, HK_FORCE),
1254         IsVectorized("isvectorized", 0, HK_ISVECTORIZED), TheLoop(L), ORE(ORE) {
1255     // Populate values with existing loop metadata.
1256     getHintsFromMetadata();
1257 
1258     // force-vector-interleave overrides DisableInterleaving.
1259     if (VectorizerParams::isInterleaveForced())
1260       Interleave.Value = VectorizerParams::VectorizationInterleave;
1261 
1262     if (IsVectorized.Value != 1)
1263       // If the vectorization width and interleaving count are both 1 then
1264       // consider the loop to have been already vectorized because there's
1265       // nothing more that we can do.
1266       IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1;
1267     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1268           << "LV: Interleaving disabled by the pass manager\n");
1269   }
1270 
1271   /// Mark the loop L as already vectorized by setting the width to 1.
1272   void setAlreadyVectorized() {
1273     IsVectorized.Value = 1;
1274     Hint Hints[] = {IsVectorized};
1275     writeHintsToMetadata(Hints);
1276   }
1277 
1278   bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
1279     if (getForce() == LoopVectorizeHints::FK_Disabled) {
1280       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1281       emitRemarkWithHints();
1282       return false;
1283     }
1284 
1285     if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
1286       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1287       emitRemarkWithHints();
1288       return false;
1289     }
1290 
1291     if (getIsVectorized() == 1) {
1292       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1293       // FIXME: Add interleave.disable metadata. This will allow
1294       // vectorize.disable to be used without disabling the pass and errors
1295       // to differentiate between disabled vectorization and a width of 1.
1296       ORE.emit([&]() {
1297         return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
1298                                           "AllDisabled", L->getStartLoc(),
1299                                           L->getHeader())
1300                << "loop not vectorized: vectorization and interleaving are "
1301                   "explicitly disabled, or the loop has already been "
1302                   "vectorized";
1303       });
1304       return false;
1305     }
1306 
1307     return true;
1308   }
1309 
1310   /// Dumps all the hint information.
1311   void emitRemarkWithHints() const {
1312     using namespace ore;
1313 
1314     ORE.emit([&]() {
1315       if (Force.Value == LoopVectorizeHints::FK_Disabled)
1316         return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
1317                                         TheLoop->getStartLoc(),
1318                                         TheLoop->getHeader())
1319                << "loop not vectorized: vectorization is explicitly disabled";
1320       else {
1321         OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
1322                                    TheLoop->getStartLoc(),
1323                                    TheLoop->getHeader());
1324         R << "loop not vectorized";
1325         if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1326           R << " (Force=" << NV("Force", true);
1327           if (Width.Value != 0)
1328             R << ", Vector Width=" << NV("VectorWidth", Width.Value);
1329           if (Interleave.Value != 0)
1330             R << ", Interleave Count="
1331               << NV("InterleaveCount", Interleave.Value);
1332           R << ")";
1333         }
1334         return R;
1335       }
1336     });
1337   }
1338 
1339   unsigned getWidth() const { return Width.Value; }
1340   unsigned getInterleave() const { return Interleave.Value; }
1341   unsigned getIsVectorized() const { return IsVectorized.Value; }
1342   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1343 
1344   /// \brief If hints are provided that force vectorization, use the AlwaysPrint
1345   /// pass name to force the frontend to print the diagnostic.
1346   const char *vectorizeAnalysisPassName() const {
1347     if (getWidth() == 1)
1348       return LV_NAME;
1349     if (getForce() == LoopVectorizeHints::FK_Disabled)
1350       return LV_NAME;
1351     if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1352       return LV_NAME;
1353     return OptimizationRemarkAnalysis::AlwaysPrint;
1354   }
1355 
1356   bool allowReordering() const {
1357     // When enabling loop hints are provided we allow the vectorizer to change
1358     // the order of operations that is given by the scalar loop. This is not
1359     // enabled by default because can be unsafe or inefficient. For example,
1360     // reordering floating-point operations will change the way round-off
1361     // error accumulates in the loop.
1362     return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1363   }
1364 
1365   bool isPotentiallyUnsafe() const {
1366     // Avoid FP vectorization if the target is unsure about proper support.
1367     // This may be related to the SIMD unit in the target not handling
1368     // IEEE 754 FP ops properly, or bad single-to-double promotions.
1369     // Otherwise, a sequence of vectorized loops, even without reduction,
1370     // could lead to different end results on the destination vectors.
1371     return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
1372   }
1373 
1374   void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
1375 
1376 private:
1377   /// Find hints specified in the loop metadata and update local values.
1378   void getHintsFromMetadata() {
1379     MDNode *LoopID = TheLoop->getLoopID();
1380     if (!LoopID)
1381       return;
1382 
1383     // First operand should refer to the loop id itself.
1384     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1385     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1386 
1387     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1388       const MDString *S = nullptr;
1389       SmallVector<Metadata *, 4> Args;
1390 
1391       // The expected hint is either a MDString or a MDNode with the first
1392       // operand a MDString.
1393       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1394         if (!MD || MD->getNumOperands() == 0)
1395           continue;
1396         S = dyn_cast<MDString>(MD->getOperand(0));
1397         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1398           Args.push_back(MD->getOperand(i));
1399       } else {
1400         S = dyn_cast<MDString>(LoopID->getOperand(i));
1401         assert(Args.size() == 0 && "too many arguments for MDString");
1402       }
1403 
1404       if (!S)
1405         continue;
1406 
1407       // Check if the hint starts with the loop metadata prefix.
1408       StringRef Name = S->getString();
1409       if (Args.size() == 1)
1410         setHint(Name, Args[0]);
1411     }
1412   }
1413 
1414   /// Checks string hint with one operand and set value if valid.
1415   void setHint(StringRef Name, Metadata *Arg) {
1416     if (!Name.startswith(Prefix()))
1417       return;
1418     Name = Name.substr(Prefix().size(), StringRef::npos);
1419 
1420     const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1421     if (!C)
1422       return;
1423     unsigned Val = C->getZExtValue();
1424 
1425     Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized};
1426     for (auto H : Hints) {
1427       if (Name == H->Name) {
1428         if (H->validate(Val))
1429           H->Value = Val;
1430         else
1431           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1432         break;
1433       }
1434     }
1435   }
1436 
1437   /// Create a new hint from name / value pair.
1438   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1439     LLVMContext &Context = TheLoop->getHeader()->getContext();
1440     Metadata *MDs[] = {MDString::get(Context, Name),
1441                        ConstantAsMetadata::get(
1442                            ConstantInt::get(Type::getInt32Ty(Context), V))};
1443     return MDNode::get(Context, MDs);
1444   }
1445 
1446   /// Matches metadata with hint name.
1447   bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1448     MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
1449     if (!Name)
1450       return false;
1451 
1452     for (auto H : HintTypes)
1453       if (Name->getString().endswith(H.Name))
1454         return true;
1455     return false;
1456   }
1457 
1458   /// Sets current hints into loop metadata, keeping other values intact.
1459   void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1460     if (HintTypes.empty())
1461       return;
1462 
1463     // Reserve the first element to LoopID (see below).
1464     SmallVector<Metadata *, 4> MDs(1);
1465     // If the loop already has metadata, then ignore the existing operands.
1466     MDNode *LoopID = TheLoop->getLoopID();
1467     if (LoopID) {
1468       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1469         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1470         // If node in update list, ignore old value.
1471         if (!matchesHintMetadataName(Node, HintTypes))
1472           MDs.push_back(Node);
1473       }
1474     }
1475 
1476     // Now, add the missing hints.
1477     for (auto H : HintTypes)
1478       MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1479 
1480     // Replace current metadata node with new one.
1481     LLVMContext &Context = TheLoop->getHeader()->getContext();
1482     MDNode *NewLoopID = MDNode::get(Context, MDs);
1483     // Set operand 0 to refer to the loop id itself.
1484     NewLoopID->replaceOperandWith(0, NewLoopID);
1485 
1486     TheLoop->setLoopID(NewLoopID);
1487   }
1488 
1489   /// The loop these hints belong to.
1490   const Loop *TheLoop;
1491 
1492   /// Interface to emit optimization remarks.
1493   OptimizationRemarkEmitter &ORE;
1494 };
1495 
1496 } // end anonymous namespace
1497 
1498 static void emitMissedWarning(Function *F, Loop *L,
1499                               const LoopVectorizeHints &LH,
1500                               OptimizationRemarkEmitter *ORE) {
1501   LH.emitRemarkWithHints();
1502 
1503   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1504     if (LH.getWidth() != 1)
1505       ORE->emit(DiagnosticInfoOptimizationFailure(
1506                     DEBUG_TYPE, "FailedRequestedVectorization",
1507                     L->getStartLoc(), L->getHeader())
1508                 << "loop not vectorized: "
1509                 << "failed explicitly specified loop vectorization");
1510     else if (LH.getInterleave() != 1)
1511       ORE->emit(DiagnosticInfoOptimizationFailure(
1512                     DEBUG_TYPE, "FailedRequestedInterleaving", L->getStartLoc(),
1513                     L->getHeader())
1514                 << "loop not interleaved: "
1515                 << "failed explicitly specified loop interleaving");
1516   }
1517 }
1518 
1519 namespace llvm {
1520 
1521 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1522 /// to what vectorization factor.
1523 /// This class does not look at the profitability of vectorization, only the
1524 /// legality. This class has two main kinds of checks:
1525 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1526 ///   will change the order of memory accesses in a way that will change the
1527 ///   correctness of the program.
1528 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1529 /// checks for a number of different conditions, such as the availability of a
1530 /// single induction variable, that all types are supported and vectorize-able,
1531 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1532 /// This class is also used by InnerLoopVectorizer for identifying
1533 /// induction variable and the different reduction variables.
1534 class LoopVectorizationLegality {
1535 public:
1536   LoopVectorizationLegality(
1537       Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT,
1538       TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F,
1539       const TargetTransformInfo *TTI,
1540       std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI,
1541       OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R,
1542       LoopVectorizeHints *H, DemandedBits *DB, AssumptionCache *AC)
1543       : TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT), GetLAA(GetLAA),
1544         ORE(ORE), InterleaveInfo(PSE, L, DT, LI), Requirements(R), Hints(H),
1545         DB(DB), AC(AC) {}
1546 
1547   /// ReductionList contains the reduction descriptors for all
1548   /// of the reductions that were found in the loop.
1549   using ReductionList = DenseMap<PHINode *, RecurrenceDescriptor>;
1550 
1551   /// InductionList saves induction variables and maps them to the
1552   /// induction descriptor.
1553   using InductionList = MapVector<PHINode *, InductionDescriptor>;
1554 
1555   /// RecurrenceSet contains the phi nodes that are recurrences other than
1556   /// inductions and reductions.
1557   using RecurrenceSet = SmallPtrSet<const PHINode *, 8>;
1558 
1559   /// Returns true if it is legal to vectorize this loop.
1560   /// This does not mean that it is profitable to vectorize this
1561   /// loop, only that it is legal to do so.
1562   bool canVectorize();
1563 
1564   /// Returns the primary induction variable.
1565   PHINode *getPrimaryInduction() { return PrimaryInduction; }
1566 
1567   /// Returns the reduction variables found in the loop.
1568   ReductionList *getReductionVars() { return &Reductions; }
1569 
1570   /// Returns the induction variables found in the loop.
1571   InductionList *getInductionVars() { return &Inductions; }
1572 
1573   /// Return the first-order recurrences found in the loop.
1574   RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
1575 
1576   /// Return the set of instructions to sink to handle first-order recurrences.
1577   DenseMap<Instruction *, Instruction *> &getSinkAfter() { return SinkAfter; }
1578 
1579   /// Returns the widest induction type.
1580   Type *getWidestInductionType() { return WidestIndTy; }
1581 
1582   /// Returns True if V is a Phi node of an induction variable in this loop.
1583   bool isInductionPhi(const Value *V);
1584 
1585   /// Returns True if V is a cast that is part of an induction def-use chain,
1586   /// and had been proven to be redundant under a runtime guard (in other
1587   /// words, the cast has the same SCEV expression as the induction phi).
1588   bool isCastedInductionVariable(const Value *V);
1589 
1590   /// Returns True if V can be considered as an induction variable in this
1591   /// loop. V can be the induction phi, or some redundant cast in the def-use
1592   /// chain of the inducion phi.
1593   bool isInductionVariable(const Value *V);
1594 
1595   /// Returns True if PN is a reduction variable in this loop.
1596   bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
1597 
1598   /// Returns True if Phi is a first-order recurrence in this loop.
1599   bool isFirstOrderRecurrence(const PHINode *Phi);
1600 
1601   /// Return true if the block BB needs to be predicated in order for the loop
1602   /// to be vectorized.
1603   bool blockNeedsPredication(BasicBlock *BB);
1604 
1605   /// Check if this pointer is consecutive when vectorizing. This happens
1606   /// when the last index of the GEP is the induction variable, or that the
1607   /// pointer itself is an induction variable.
1608   /// This check allows us to vectorize A[idx] into a wide load/store.
1609   /// Returns:
1610   /// 0 - Stride is unknown or non-consecutive.
1611   /// 1 - Address is consecutive.
1612   /// -1 - Address is consecutive, and decreasing.
1613   /// NOTE: This method must only be used before modifying the original scalar
1614   /// loop. Do not use after invoking 'createVectorizedLoopSkeleton' (PR34965).
1615   int isConsecutivePtr(Value *Ptr);
1616 
1617   /// Returns true if the value V is uniform within the loop.
1618   bool isUniform(Value *V);
1619 
1620   /// Returns the information that we collected about runtime memory check.
1621   const RuntimePointerChecking *getRuntimePointerChecking() const {
1622     return LAI->getRuntimePointerChecking();
1623   }
1624 
1625   const LoopAccessInfo *getLAI() const { return LAI; }
1626 
1627   /// \brief Check if \p Instr belongs to any interleaved access group.
1628   bool isAccessInterleaved(Instruction *Instr) {
1629     return InterleaveInfo.isInterleaved(Instr);
1630   }
1631 
1632   /// \brief Get the interleaved access group that \p Instr belongs to.
1633   const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1634     return InterleaveInfo.getInterleaveGroup(Instr);
1635   }
1636 
1637   /// \brief Returns true if an interleaved group requires a scalar iteration
1638   /// to handle accesses with gaps.
1639   bool requiresScalarEpilogue() const {
1640     return InterleaveInfo.requiresScalarEpilogue();
1641   }
1642 
1643   unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1644 
1645   uint64_t getMaxSafeRegisterWidth() const {
1646 	  return LAI->getDepChecker().getMaxSafeRegisterWidth();
1647   }
1648 
1649   bool hasStride(Value *V) { return LAI->hasStride(V); }
1650 
1651   /// Returns true if the target machine supports masked store operation
1652   /// for the given \p DataType and kind of access to \p Ptr.
1653   bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1654     return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
1655   }
1656 
1657   /// Returns true if the target machine supports masked load operation
1658   /// for the given \p DataType and kind of access to \p Ptr.
1659   bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1660     return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
1661   }
1662 
1663   /// Returns true if the target machine supports masked scatter operation
1664   /// for the given \p DataType.
1665   bool isLegalMaskedScatter(Type *DataType) {
1666     return TTI->isLegalMaskedScatter(DataType);
1667   }
1668 
1669   /// Returns true if the target machine supports masked gather operation
1670   /// for the given \p DataType.
1671   bool isLegalMaskedGather(Type *DataType) {
1672     return TTI->isLegalMaskedGather(DataType);
1673   }
1674 
1675   /// Returns true if the target machine can represent \p V as a masked gather
1676   /// or scatter operation.
1677   bool isLegalGatherOrScatter(Value *V) {
1678     auto *LI = dyn_cast<LoadInst>(V);
1679     auto *SI = dyn_cast<StoreInst>(V);
1680     if (!LI && !SI)
1681       return false;
1682     auto *Ptr = getPointerOperand(V);
1683     auto *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1684     return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
1685   }
1686 
1687   /// Returns true if vector representation of the instruction \p I
1688   /// requires mask.
1689   bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
1690 
1691   unsigned getNumStores() const { return LAI->getNumStores(); }
1692   unsigned getNumLoads() const { return LAI->getNumLoads(); }
1693   unsigned getNumPredStores() const { return NumPredStores; }
1694 
1695   /// Returns true if \p I is an instruction that will be scalarized with
1696   /// predication. Such instructions include conditional stores and
1697   /// instructions that may divide by zero.
1698   bool isScalarWithPredication(Instruction *I);
1699 
1700   /// Returns true if \p I is a memory instruction with consecutive memory
1701   /// access that can be widened.
1702   bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
1703 
1704   // Returns true if the NoNaN attribute is set on the function.
1705   bool hasFunNoNaNAttr() const { return HasFunNoNaNAttr; }
1706 
1707 private:
1708   /// Check if a single basic block loop is vectorizable.
1709   /// At this point we know that this is a loop with a constant trip count
1710   /// and we only need to check individual instructions.
1711   bool canVectorizeInstrs();
1712 
1713   /// When we vectorize loops we may change the order in which
1714   /// we read and write from memory. This method checks if it is
1715   /// legal to vectorize the code, considering only memory constrains.
1716   /// Returns true if the loop is vectorizable
1717   bool canVectorizeMemory();
1718 
1719   /// Return true if we can vectorize this loop using the IF-conversion
1720   /// transformation.
1721   bool canVectorizeWithIfConvert();
1722 
1723   /// Return true if all of the instructions in the block can be speculatively
1724   /// executed. \p SafePtrs is a list of addresses that are known to be legal
1725   /// and we know that we can read from them without segfault.
1726   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1727 
1728   /// Updates the vectorization state by adding \p Phi to the inductions list.
1729   /// This can set \p Phi as the main induction of the loop if \p Phi is a
1730   /// better choice for the main induction than the existing one.
1731   void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID,
1732                        SmallPtrSetImpl<Value *> &AllowedExit);
1733 
1734   /// Create an analysis remark that explains why vectorization failed
1735   ///
1736   /// \p RemarkName is the identifier for the remark.  If \p I is passed it is
1737   /// an instruction that prevents vectorization.  Otherwise the loop is used
1738   /// for the location of the remark.  \return the remark object that can be
1739   /// streamed to.
1740   OptimizationRemarkAnalysis
1741   createMissedAnalysis(StringRef RemarkName, Instruction *I = nullptr) const {
1742     return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
1743                                   RemarkName, TheLoop, I);
1744   }
1745 
1746   /// \brief If an access has a symbolic strides, this maps the pointer value to
1747   /// the stride symbol.
1748   const ValueToValueMap *getSymbolicStrides() {
1749     // FIXME: Currently, the set of symbolic strides is sometimes queried before
1750     // it's collected.  This happens from canVectorizeWithIfConvert, when the
1751     // pointer is checked to reference consecutive elements suitable for a
1752     // masked access.
1753     return LAI ? &LAI->getSymbolicStrides() : nullptr;
1754   }
1755 
1756   unsigned NumPredStores = 0;
1757 
1758   /// The loop that we evaluate.
1759   Loop *TheLoop;
1760 
1761   /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
1762   /// Applies dynamic knowledge to simplify SCEV expressions in the context
1763   /// of existing SCEV assumptions. The analysis will also add a minimal set
1764   /// of new predicates if this is required to enable vectorization and
1765   /// unrolling.
1766   PredicatedScalarEvolution &PSE;
1767 
1768   /// Target Library Info.
1769   TargetLibraryInfo *TLI;
1770 
1771   /// Target Transform Info
1772   const TargetTransformInfo *TTI;
1773 
1774   /// Dominator Tree.
1775   DominatorTree *DT;
1776 
1777   // LoopAccess analysis.
1778   std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
1779 
1780   // And the loop-accesses info corresponding to this loop.  This pointer is
1781   // null until canVectorizeMemory sets it up.
1782   const LoopAccessInfo *LAI = nullptr;
1783 
1784   /// Interface to emit optimization remarks.
1785   OptimizationRemarkEmitter *ORE;
1786 
1787   /// The interleave access information contains groups of interleaved accesses
1788   /// with the same stride and close to each other.
1789   InterleavedAccessInfo InterleaveInfo;
1790 
1791   //  ---  vectorization state --- //
1792 
1793   /// Holds the primary induction variable. This is the counter of the
1794   /// loop.
1795   PHINode *PrimaryInduction = nullptr;
1796 
1797   /// Holds the reduction variables.
1798   ReductionList Reductions;
1799 
1800   /// Holds all of the induction variables that we found in the loop.
1801   /// Notice that inductions don't need to start at zero and that induction
1802   /// variables can be pointers.
1803   InductionList Inductions;
1804 
1805   /// Holds all the casts that participate in the update chain of the induction
1806   /// variables, and that have been proven to be redundant (possibly under a
1807   /// runtime guard). These casts can be ignored when creating the vectorized
1808   /// loop body.
1809   SmallPtrSet<Instruction *, 4> InductionCastsToIgnore;
1810 
1811   /// Holds the phi nodes that are first-order recurrences.
1812   RecurrenceSet FirstOrderRecurrences;
1813 
1814   /// Holds instructions that need to sink past other instructions to handle
1815   /// first-order recurrences.
1816   DenseMap<Instruction *, Instruction *> SinkAfter;
1817 
1818   /// Holds the widest induction type encountered.
1819   Type *WidestIndTy = nullptr;
1820 
1821   /// Allowed outside users. This holds the induction and reduction
1822   /// vars which can be accessed from outside the loop.
1823   SmallPtrSet<Value *, 4> AllowedExit;
1824 
1825   /// Can we assume the absence of NaNs.
1826   bool HasFunNoNaNAttr = false;
1827 
1828   /// Vectorization requirements that will go through late-evaluation.
1829   LoopVectorizationRequirements *Requirements;
1830 
1831   /// Used to emit an analysis of any legality issues.
1832   LoopVectorizeHints *Hints;
1833 
1834   /// The demanded bits analsyis is used to compute the minimum type size in
1835   /// which a reduction can be computed.
1836   DemandedBits *DB;
1837 
1838   /// The assumption cache analysis is used to compute the minimum type size in
1839   /// which a reduction can be computed.
1840   AssumptionCache *AC;
1841 
1842   /// While vectorizing these instructions we have to generate a
1843   /// call to the appropriate masked intrinsic
1844   SmallPtrSet<const Instruction *, 8> MaskedOp;
1845 };
1846 
1847 /// LoopVectorizationCostModel - estimates the expected speedups due to
1848 /// vectorization.
1849 /// In many cases vectorization is not profitable. This can happen because of
1850 /// a number of reasons. In this class we mainly attempt to predict the
1851 /// expected speedup/slowdowns due to the supported instruction set. We use the
1852 /// TargetTransformInfo to query the different backends for the cost of
1853 /// different operations.
1854 class LoopVectorizationCostModel {
1855 public:
1856   LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
1857                              LoopInfo *LI, LoopVectorizationLegality *Legal,
1858                              const TargetTransformInfo &TTI,
1859                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1860                              AssumptionCache *AC,
1861                              OptimizationRemarkEmitter *ORE, const Function *F,
1862                              const LoopVectorizeHints *Hints)
1863       : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1864         AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {}
1865 
1866   /// \return An upper bound for the vectorization factor, or None if
1867   /// vectorization should be avoided up front.
1868   Optional<unsigned> computeMaxVF(bool OptForSize);
1869 
1870   /// \return The most profitable vectorization factor and the cost of that VF.
1871   /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1872   /// then this vectorization factor will be selected if vectorization is
1873   /// possible.
1874   VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
1875 
1876   /// Setup cost-based decisions for user vectorization factor.
1877   void selectUserVectorizationFactor(unsigned UserVF) {
1878     collectUniformsAndScalars(UserVF);
1879     collectInstsToScalarize(UserVF);
1880   }
1881 
1882   /// \return The size (in bits) of the smallest and widest types in the code
1883   /// that needs to be vectorized. We ignore values that remain scalar such as
1884   /// 64 bit loop indices.
1885   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1886 
1887   /// \return The desired interleave count.
1888   /// If interleave count has been specified by metadata it will be returned.
1889   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1890   /// are the selected vectorization factor and the cost of the selected VF.
1891   unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1892                                  unsigned LoopCost);
1893 
1894   /// Memory access instruction may be vectorized in more than one way.
1895   /// Form of instruction after vectorization depends on cost.
1896   /// This function takes cost-based decisions for Load/Store instructions
1897   /// and collects them in a map. This decisions map is used for building
1898   /// the lists of loop-uniform and loop-scalar instructions.
1899   /// The calculated cost is saved with widening decision in order to
1900   /// avoid redundant calculations.
1901   void setCostBasedWideningDecision(unsigned VF);
1902 
1903   /// \brief A struct that represents some properties of the register usage
1904   /// of a loop.
1905   struct RegisterUsage {
1906     /// Holds the number of loop invariant values that are used in the loop.
1907     unsigned LoopInvariantRegs;
1908 
1909     /// Holds the maximum number of concurrent live intervals in the loop.
1910     unsigned MaxLocalUsers;
1911 
1912     /// Holds the number of instructions in the loop.
1913     unsigned NumInstructions;
1914   };
1915 
1916   /// \return Returns information about the register usages of the loop for the
1917   /// given vectorization factors.
1918   SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
1919 
1920   /// Collect values we want to ignore in the cost model.
1921   void collectValuesToIgnore();
1922 
1923   /// \returns The smallest bitwidth each instruction can be represented with.
1924   /// The vector equivalents of these instructions should be truncated to this
1925   /// type.
1926   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1927     return MinBWs;
1928   }
1929 
1930   /// \returns True if it is more profitable to scalarize instruction \p I for
1931   /// vectorization factor \p VF.
1932   bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
1933     assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.");
1934     auto Scalars = InstsToScalarize.find(VF);
1935     assert(Scalars != InstsToScalarize.end() &&
1936            "VF not yet analyzed for scalarization profitability");
1937     return Scalars->second.count(I);
1938   }
1939 
1940   /// Returns true if \p I is known to be uniform after vectorization.
1941   bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
1942     if (VF == 1)
1943       return true;
1944     assert(Uniforms.count(VF) && "VF not yet analyzed for uniformity");
1945     auto UniformsPerVF = Uniforms.find(VF);
1946     return UniformsPerVF->second.count(I);
1947   }
1948 
1949   /// Returns true if \p I is known to be scalar after vectorization.
1950   bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
1951     if (VF == 1)
1952       return true;
1953     assert(Scalars.count(VF) && "Scalar values are not calculated for VF");
1954     auto ScalarsPerVF = Scalars.find(VF);
1955     return ScalarsPerVF->second.count(I);
1956   }
1957 
1958   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1959   /// for vectorization factor \p VF.
1960   bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
1961     return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1962            !isScalarAfterVectorization(I, VF);
1963   }
1964 
1965   /// Decision that was taken during cost calculation for memory instruction.
1966   enum InstWidening {
1967     CM_Unknown,
1968     CM_Widen,         // For consecutive accesses with stride +1.
1969     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1970     CM_Interleave,
1971     CM_GatherScatter,
1972     CM_Scalarize
1973   };
1974 
1975   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1976   /// instruction \p I and vector width \p VF.
1977   void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
1978                            unsigned Cost) {
1979     assert(VF >= 2 && "Expected VF >=2");
1980     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1981   }
1982 
1983   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1984   /// interleaving group \p Grp and vector width \p VF.
1985   void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
1986                            InstWidening W, unsigned Cost) {
1987     assert(VF >= 2 && "Expected VF >=2");
1988     /// Broadcast this decicion to all instructions inside the group.
1989     /// But the cost will be assigned to one instruction only.
1990     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1991       if (auto *I = Grp->getMember(i)) {
1992         if (Grp->getInsertPos() == I)
1993           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1994         else
1995           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1996       }
1997     }
1998   }
1999 
2000   /// Return the cost model decision for the given instruction \p I and vector
2001   /// width \p VF. Return CM_Unknown if this instruction did not pass
2002   /// through the cost modeling.
2003   InstWidening getWideningDecision(Instruction *I, unsigned VF) {
2004     assert(VF >= 2 && "Expected VF >=2");
2005     std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
2006     auto Itr = WideningDecisions.find(InstOnVF);
2007     if (Itr == WideningDecisions.end())
2008       return CM_Unknown;
2009     return Itr->second.first;
2010   }
2011 
2012   /// Return the vectorization cost for the given instruction \p I and vector
2013   /// width \p VF.
2014   unsigned getWideningCost(Instruction *I, unsigned VF) {
2015     assert(VF >= 2 && "Expected VF >=2");
2016     std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
2017     assert(WideningDecisions.count(InstOnVF) && "The cost is not calculated");
2018     return WideningDecisions[InstOnVF].second;
2019   }
2020 
2021   /// Return True if instruction \p I is an optimizable truncate whose operand
2022   /// is an induction variable. Such a truncate will be removed by adding a new
2023   /// induction variable with the destination type.
2024   bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
2025     // If the instruction is not a truncate, return false.
2026     auto *Trunc = dyn_cast<TruncInst>(I);
2027     if (!Trunc)
2028       return false;
2029 
2030     // Get the source and destination types of the truncate.
2031     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
2032     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
2033 
2034     // If the truncate is free for the given types, return false. Replacing a
2035     // free truncate with an induction variable would add an induction variable
2036     // update instruction to each iteration of the loop. We exclude from this
2037     // check the primary induction variable since it will need an update
2038     // instruction regardless.
2039     Value *Op = Trunc->getOperand(0);
2040     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
2041       return false;
2042 
2043     // If the truncated value is not an induction variable, return false.
2044     return Legal->isInductionPhi(Op);
2045   }
2046 
2047   /// Collects the instructions to scalarize for each predicated instruction in
2048   /// the loop.
2049   void collectInstsToScalarize(unsigned VF);
2050 
2051   /// Collect Uniform and Scalar values for the given \p VF.
2052   /// The sets depend on CM decision for Load/Store instructions
2053   /// that may be vectorized as interleave, gather-scatter or scalarized.
2054   void collectUniformsAndScalars(unsigned VF) {
2055     // Do the analysis once.
2056     if (VF == 1 || Uniforms.count(VF))
2057       return;
2058     setCostBasedWideningDecision(VF);
2059     collectLoopUniforms(VF);
2060     collectLoopScalars(VF);
2061   }
2062 
2063 private:
2064   /// \return An upper bound for the vectorization factor, larger than zero.
2065   /// One is returned if vectorization should best be avoided due to cost.
2066   unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
2067 
2068   /// The vectorization cost is a combination of the cost itself and a boolean
2069   /// indicating whether any of the contributing operations will actually
2070   /// operate on
2071   /// vector values after type legalization in the backend. If this latter value
2072   /// is
2073   /// false, then all operations will be scalarized (i.e. no vectorization has
2074   /// actually taken place).
2075   using VectorizationCostTy = std::pair<unsigned, bool>;
2076 
2077   /// Returns the expected execution cost. The unit of the cost does
2078   /// not matter because we use the 'cost' units to compare different
2079   /// vector widths. The cost that is returned is *not* normalized by
2080   /// the factor width.
2081   VectorizationCostTy expectedCost(unsigned VF);
2082 
2083   /// Returns the execution time cost of an instruction for a given vector
2084   /// width. Vector width of one means scalar.
2085   VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
2086 
2087   /// The cost-computation logic from getInstructionCost which provides
2088   /// the vector type as an output parameter.
2089   unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
2090 
2091   /// Calculate vectorization cost of memory instruction \p I.
2092   unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
2093 
2094   /// The cost computation for scalarized memory instruction.
2095   unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
2096 
2097   /// The cost computation for interleaving group of memory instructions.
2098   unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
2099 
2100   /// The cost computation for Gather/Scatter instruction.
2101   unsigned getGatherScatterCost(Instruction *I, unsigned VF);
2102 
2103   /// The cost computation for widening instruction \p I with consecutive
2104   /// memory access.
2105   unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
2106 
2107   /// The cost calculation for Load instruction \p I with uniform pointer -
2108   /// scalar load + broadcast.
2109   unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
2110 
2111   /// Returns whether the instruction is a load or store and will be a emitted
2112   /// as a vector operation.
2113   bool isConsecutiveLoadOrStore(Instruction *I);
2114 
2115   /// Create an analysis remark that explains why vectorization failed
2116   ///
2117   /// \p RemarkName is the identifier for the remark.  \return the remark object
2118   /// that can be streamed to.
2119   OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
2120     return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
2121                                   RemarkName, TheLoop);
2122   }
2123 
2124   /// Map of scalar integer values to the smallest bitwidth they can be legally
2125   /// represented as. The vector equivalents of these values should be truncated
2126   /// to this type.
2127   MapVector<Instruction *, uint64_t> MinBWs;
2128 
2129   /// A type representing the costs for instructions if they were to be
2130   /// scalarized rather than vectorized. The entries are Instruction-Cost
2131   /// pairs.
2132   using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
2133 
2134   /// A set containing all BasicBlocks that are known to present after
2135   /// vectorization as a predicated block.
2136   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
2137 
2138   /// A map holding scalar costs for different vectorization factors. The
2139   /// presence of a cost for an instruction in the mapping indicates that the
2140   /// instruction will be scalarized when vectorizing with the associated
2141   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
2142   DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
2143 
2144   /// Holds the instructions known to be uniform after vectorization.
2145   /// The data is collected per VF.
2146   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
2147 
2148   /// Holds the instructions known to be scalar after vectorization.
2149   /// The data is collected per VF.
2150   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
2151 
2152   /// Holds the instructions (address computations) that are forced to be
2153   /// scalarized.
2154   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
2155 
2156   /// Returns the expected difference in cost from scalarizing the expression
2157   /// feeding a predicated instruction \p PredInst. The instructions to
2158   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
2159   /// non-negative return value implies the expression will be scalarized.
2160   /// Currently, only single-use chains are considered for scalarization.
2161   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
2162                               unsigned VF);
2163 
2164   /// Collect the instructions that are uniform after vectorization. An
2165   /// instruction is uniform if we represent it with a single scalar value in
2166   /// the vectorized loop corresponding to each vector iteration. Examples of
2167   /// uniform instructions include pointer operands of consecutive or
2168   /// interleaved memory accesses. Note that although uniformity implies an
2169   /// instruction will be scalar, the reverse is not true. In general, a
2170   /// scalarized instruction will be represented by VF scalar values in the
2171   /// vectorized loop, each corresponding to an iteration of the original
2172   /// scalar loop.
2173   void collectLoopUniforms(unsigned VF);
2174 
2175   /// Collect the instructions that are scalar after vectorization. An
2176   /// instruction is scalar if it is known to be uniform or will be scalarized
2177   /// during vectorization. Non-uniform scalarized instructions will be
2178   /// represented by VF values in the vectorized loop, each corresponding to an
2179   /// iteration of the original scalar loop.
2180   void collectLoopScalars(unsigned VF);
2181 
2182   /// Keeps cost model vectorization decision and cost for instructions.
2183   /// Right now it is used for memory instructions only.
2184   using DecisionList = DenseMap<std::pair<Instruction *, unsigned>,
2185                                 std::pair<InstWidening, unsigned>>;
2186 
2187   DecisionList WideningDecisions;
2188 
2189 public:
2190   /// The loop that we evaluate.
2191   Loop *TheLoop;
2192 
2193   /// Predicated scalar evolution analysis.
2194   PredicatedScalarEvolution &PSE;
2195 
2196   /// Loop Info analysis.
2197   LoopInfo *LI;
2198 
2199   /// Vectorization legality.
2200   LoopVectorizationLegality *Legal;
2201 
2202   /// Vector target information.
2203   const TargetTransformInfo &TTI;
2204 
2205   /// Target Library Info.
2206   const TargetLibraryInfo *TLI;
2207 
2208   /// Demanded bits analysis.
2209   DemandedBits *DB;
2210 
2211   /// Assumption cache.
2212   AssumptionCache *AC;
2213 
2214   /// Interface to emit optimization remarks.
2215   OptimizationRemarkEmitter *ORE;
2216 
2217   const Function *TheFunction;
2218 
2219   /// Loop Vectorize Hint.
2220   const LoopVectorizeHints *Hints;
2221 
2222   /// Values to ignore in the cost model.
2223   SmallPtrSet<const Value *, 16> ValuesToIgnore;
2224 
2225   /// Values to ignore in the cost model when VF > 1.
2226   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
2227 };
2228 
2229 } // end namespace llvm
2230 
2231 namespace {
2232 
2233 /// \brief This holds vectorization requirements that must be verified late in
2234 /// the process. The requirements are set by legalize and costmodel. Once
2235 /// vectorization has been determined to be possible and profitable the
2236 /// requirements can be verified by looking for metadata or compiler options.
2237 /// For example, some loops require FP commutativity which is only allowed if
2238 /// vectorization is explicitly specified or if the fast-math compiler option
2239 /// has been provided.
2240 /// Late evaluation of these requirements allows helpful diagnostics to be
2241 /// composed that tells the user what need to be done to vectorize the loop. For
2242 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
2243 /// evaluation should be used only when diagnostics can generated that can be
2244 /// followed by a non-expert user.
2245 class LoopVectorizationRequirements {
2246 public:
2247   LoopVectorizationRequirements(OptimizationRemarkEmitter &ORE) : ORE(ORE) {}
2248 
2249   void addUnsafeAlgebraInst(Instruction *I) {
2250     // First unsafe algebra instruction.
2251     if (!UnsafeAlgebraInst)
2252       UnsafeAlgebraInst = I;
2253   }
2254 
2255   void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
2256 
2257   bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
2258     const char *PassName = Hints.vectorizeAnalysisPassName();
2259     bool Failed = false;
2260     if (UnsafeAlgebraInst && !Hints.allowReordering()) {
2261       ORE.emit([&]() {
2262         return OptimizationRemarkAnalysisFPCommute(
2263                    PassName, "CantReorderFPOps",
2264                    UnsafeAlgebraInst->getDebugLoc(),
2265                    UnsafeAlgebraInst->getParent())
2266                << "loop not vectorized: cannot prove it is safe to reorder "
2267                   "floating-point operations";
2268       });
2269       Failed = true;
2270     }
2271 
2272     // Test if runtime memcheck thresholds are exceeded.
2273     bool PragmaThresholdReached =
2274         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
2275     bool ThresholdReached =
2276         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
2277     if ((ThresholdReached && !Hints.allowReordering()) ||
2278         PragmaThresholdReached) {
2279       ORE.emit([&]() {
2280         return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
2281                                                   L->getStartLoc(),
2282                                                   L->getHeader())
2283                << "loop not vectorized: cannot prove it is safe to reorder "
2284                   "memory operations";
2285       });
2286       DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
2287       Failed = true;
2288     }
2289 
2290     return Failed;
2291   }
2292 
2293 private:
2294   unsigned NumRuntimePointerChecks = 0;
2295   Instruction *UnsafeAlgebraInst = nullptr;
2296 
2297   /// Interface to emit optimization remarks.
2298   OptimizationRemarkEmitter &ORE;
2299 };
2300 
2301 } // end anonymous namespace
2302 
2303 static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
2304   if (L.empty()) {
2305     if (!hasCyclesInLoopBody(L))
2306       V.push_back(&L);
2307     return;
2308   }
2309   for (Loop *InnerL : L)
2310     addAcyclicInnerLoop(*InnerL, V);
2311 }
2312 
2313 namespace {
2314 
2315 /// The LoopVectorize Pass.
2316 struct LoopVectorize : public FunctionPass {
2317   /// Pass identification, replacement for typeid
2318   static char ID;
2319 
2320   LoopVectorizePass Impl;
2321 
2322   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
2323       : FunctionPass(ID) {
2324     Impl.DisableUnrolling = NoUnrolling;
2325     Impl.AlwaysVectorize = AlwaysVectorize;
2326     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2327   }
2328 
2329   bool runOnFunction(Function &F) override {
2330     if (skipFunction(F))
2331       return false;
2332 
2333     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2334     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2335     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2336     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2337     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2338     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2339     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2340     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2341     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2342     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2343     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2344     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2345 
2346     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2347         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2348 
2349     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2350                         GetLAA, *ORE);
2351   }
2352 
2353   void getAnalysisUsage(AnalysisUsage &AU) const override {
2354     AU.addRequired<AssumptionCacheTracker>();
2355     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2356     AU.addRequired<DominatorTreeWrapperPass>();
2357     AU.addRequired<LoopInfoWrapperPass>();
2358     AU.addRequired<ScalarEvolutionWrapperPass>();
2359     AU.addRequired<TargetTransformInfoWrapperPass>();
2360     AU.addRequired<AAResultsWrapperPass>();
2361     AU.addRequired<LoopAccessLegacyAnalysis>();
2362     AU.addRequired<DemandedBitsWrapperPass>();
2363     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2364     AU.addPreserved<LoopInfoWrapperPass>();
2365     AU.addPreserved<DominatorTreeWrapperPass>();
2366     AU.addPreserved<BasicAAWrapperPass>();
2367     AU.addPreserved<GlobalsAAWrapperPass>();
2368   }
2369 };
2370 
2371 } // end anonymous namespace
2372 
2373 //===----------------------------------------------------------------------===//
2374 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2375 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2376 //===----------------------------------------------------------------------===//
2377 
2378 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2379   // We need to place the broadcast of invariant variables outside the loop.
2380   Instruction *Instr = dyn_cast<Instruction>(V);
2381   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
2382   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
2383 
2384   // Place the code for broadcasting invariant variables in the new preheader.
2385   IRBuilder<>::InsertPointGuard Guard(Builder);
2386   if (Invariant)
2387     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2388 
2389   // Broadcast the scalar into all locations in the vector.
2390   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2391 
2392   return Shuf;
2393 }
2394 
2395 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2396     const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
2397   Value *Start = II.getStartValue();
2398 
2399   // Construct the initial value of the vector IV in the vector loop preheader
2400   auto CurrIP = Builder.saveIP();
2401   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2402   if (isa<TruncInst>(EntryVal)) {
2403     assert(Start->getType()->isIntegerTy() &&
2404            "Truncation requires an integer type");
2405     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2406     Step = Builder.CreateTrunc(Step, TruncType);
2407     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2408   }
2409   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2410   Value *SteppedStart =
2411       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2412 
2413   // We create vector phi nodes for both integer and floating-point induction
2414   // variables. Here, we determine the kind of arithmetic we will perform.
2415   Instruction::BinaryOps AddOp;
2416   Instruction::BinaryOps MulOp;
2417   if (Step->getType()->isIntegerTy()) {
2418     AddOp = Instruction::Add;
2419     MulOp = Instruction::Mul;
2420   } else {
2421     AddOp = II.getInductionOpcode();
2422     MulOp = Instruction::FMul;
2423   }
2424 
2425   // Multiply the vectorization factor by the step using integer or
2426   // floating-point arithmetic as appropriate.
2427   Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
2428   Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
2429 
2430   // Create a vector splat to use in the induction update.
2431   //
2432   // FIXME: If the step is non-constant, we create the vector splat with
2433   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2434   //        handle a constant vector splat.
2435   Value *SplatVF = isa<Constant>(Mul)
2436                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2437                        : Builder.CreateVectorSplat(VF, Mul);
2438   Builder.restoreIP(CurrIP);
2439 
2440   // We may need to add the step a number of times, depending on the unroll
2441   // factor. The last of those goes into the PHI.
2442   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2443                                     &*LoopVectorBody->getFirstInsertionPt());
2444   Instruction *LastInduction = VecInd;
2445   for (unsigned Part = 0; Part < UF; ++Part) {
2446     VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
2447 
2448     if (isa<TruncInst>(EntryVal))
2449       addMetadata(LastInduction, EntryVal);
2450     else
2451       recordVectorLoopValueForInductionCast(II, LastInduction, Part);
2452 
2453     LastInduction = cast<Instruction>(addFastMathFlag(
2454         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
2455   }
2456 
2457   // Move the last step to the end of the latch block. This ensures consistent
2458   // placement of all induction updates.
2459   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2460   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2461   auto *ICmp = cast<Instruction>(Br->getCondition());
2462   LastInduction->moveBefore(ICmp);
2463   LastInduction->setName("vec.ind.next");
2464 
2465   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2466   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2467 }
2468 
2469 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2470   return Cost->isScalarAfterVectorization(I, VF) ||
2471          Cost->isProfitableToScalarize(I, VF);
2472 }
2473 
2474 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2475   if (shouldScalarizeInstruction(IV))
2476     return true;
2477   auto isScalarInst = [&](User *U) -> bool {
2478     auto *I = cast<Instruction>(U);
2479     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2480   };
2481   return llvm::any_of(IV->users(), isScalarInst);
2482 }
2483 
2484 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2485     const InductionDescriptor &ID, Value *VectorLoopVal, unsigned Part,
2486     unsigned Lane) {
2487   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2488   if (Casts.empty())
2489     return;
2490   // Only the first Cast instruction in the Casts vector is of interest.
2491   // The rest of the Casts (if exist) have no uses outside the
2492   // induction update chain itself.
2493   Instruction *CastInst = *Casts.begin();
2494   if (Lane < UINT_MAX)
2495     VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
2496   else
2497     VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
2498 }
2499 
2500 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
2501   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2502          "Primary induction variable must have an integer type");
2503 
2504   auto II = Legal->getInductionVars()->find(IV);
2505   assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
2506 
2507   auto ID = II->second;
2508   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2509 
2510   // The scalar value to broadcast. This will be derived from the canonical
2511   // induction variable.
2512   Value *ScalarIV = nullptr;
2513 
2514   // The value from the original loop to which we are mapping the new induction
2515   // variable.
2516   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2517 
2518   // True if we have vectorized the induction variable.
2519   auto VectorizedIV = false;
2520 
2521   // Determine if we want a scalar version of the induction variable. This is
2522   // true if the induction variable itself is not widened, or if it has at
2523   // least one user in the loop that is not widened.
2524   auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
2525 
2526   // Generate code for the induction step. Note that induction steps are
2527   // required to be loop-invariant
2528   assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
2529          "Induction step should be loop invariant");
2530   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2531   Value *Step = nullptr;
2532   if (PSE.getSE()->isSCEVable(IV->getType())) {
2533     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2534     Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
2535                              LoopVectorPreHeader->getTerminator());
2536   } else {
2537     Step = cast<SCEVUnknown>(ID.getStep())->getValue();
2538   }
2539 
2540   // Try to create a new independent vector induction variable. If we can't
2541   // create the phi node, we will splat the scalar induction variable in each
2542   // loop iteration.
2543   if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
2544     createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2545     VectorizedIV = true;
2546   }
2547 
2548   // If we haven't yet vectorized the induction variable, or if we will create
2549   // a scalar one, we need to define the scalar induction variable and step
2550   // values. If we were given a truncation type, truncate the canonical
2551   // induction variable and step. Otherwise, derive these values from the
2552   // induction descriptor.
2553   if (!VectorizedIV || NeedsScalarIV) {
2554     ScalarIV = Induction;
2555     if (IV != OldInduction) {
2556       ScalarIV = IV->getType()->isIntegerTy()
2557                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2558                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2559                                           IV->getType());
2560       ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
2561       ScalarIV->setName("offset.idx");
2562     }
2563     if (Trunc) {
2564       auto *TruncType = cast<IntegerType>(Trunc->getType());
2565       assert(Step->getType()->isIntegerTy() &&
2566              "Truncation requires an integer step");
2567       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2568       Step = Builder.CreateTrunc(Step, TruncType);
2569     }
2570   }
2571 
2572   // If we haven't yet vectorized the induction variable, splat the scalar
2573   // induction variable, and build the necessary step vectors.
2574   // TODO: Don't do it unless the vectorized IV is really required.
2575   if (!VectorizedIV) {
2576     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2577     for (unsigned Part = 0; Part < UF; ++Part) {
2578       Value *EntryPart =
2579           getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
2580       VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
2581       if (Trunc)
2582         addMetadata(EntryPart, Trunc);
2583       else
2584         recordVectorLoopValueForInductionCast(ID, EntryPart, Part);
2585     }
2586   }
2587 
2588   // If an induction variable is only used for counting loop iterations or
2589   // calculating addresses, it doesn't need to be widened. Create scalar steps
2590   // that can be used by instructions we will later scalarize. Note that the
2591   // addition of the scalar steps will not increase the number of instructions
2592   // in the loop in the common case prior to InstCombine. We will be trading
2593   // one vector extract for each scalar step.
2594   if (NeedsScalarIV)
2595     buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2596 }
2597 
2598 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2599                                           Instruction::BinaryOps BinOp) {
2600   // Create and check the types.
2601   assert(Val->getType()->isVectorTy() && "Must be a vector");
2602   int VLen = Val->getType()->getVectorNumElements();
2603 
2604   Type *STy = Val->getType()->getScalarType();
2605   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2606          "Induction Step must be an integer or FP");
2607   assert(Step->getType() == STy && "Step has wrong type");
2608 
2609   SmallVector<Constant *, 8> Indices;
2610 
2611   if (STy->isIntegerTy()) {
2612     // Create a vector of consecutive numbers from zero to VF.
2613     for (int i = 0; i < VLen; ++i)
2614       Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2615 
2616     // Add the consecutive indices to the vector value.
2617     Constant *Cv = ConstantVector::get(Indices);
2618     assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2619     Step = Builder.CreateVectorSplat(VLen, Step);
2620     assert(Step->getType() == Val->getType() && "Invalid step vec");
2621     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2622     // which can be found from the original scalar operations.
2623     Step = Builder.CreateMul(Cv, Step);
2624     return Builder.CreateAdd(Val, Step, "induction");
2625   }
2626 
2627   // Floating point induction.
2628   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2629          "Binary Opcode should be specified for FP induction");
2630   // Create a vector of consecutive numbers from zero to VF.
2631   for (int i = 0; i < VLen; ++i)
2632     Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2633 
2634   // Add the consecutive indices to the vector value.
2635   Constant *Cv = ConstantVector::get(Indices);
2636 
2637   Step = Builder.CreateVectorSplat(VLen, Step);
2638 
2639   // Floating point operations had to be 'fast' to enable the induction.
2640   FastMathFlags Flags;
2641   Flags.setFast();
2642 
2643   Value *MulOp = Builder.CreateFMul(Cv, Step);
2644   if (isa<Instruction>(MulOp))
2645     // Have to check, MulOp may be a constant
2646     cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2647 
2648   Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2649   if (isa<Instruction>(BOp))
2650     cast<Instruction>(BOp)->setFastMathFlags(Flags);
2651   return BOp;
2652 }
2653 
2654 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2655                                            Value *EntryVal,
2656                                            const InductionDescriptor &ID) {
2657   // We shouldn't have to build scalar steps if we aren't vectorizing.
2658   assert(VF > 1 && "VF should be greater than one");
2659 
2660   // Get the value type and ensure it and the step have the same integer type.
2661   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2662   assert(ScalarIVTy == Step->getType() &&
2663          "Val and Step should have the same type");
2664 
2665   // We build scalar steps for both integer and floating-point induction
2666   // variables. Here, we determine the kind of arithmetic we will perform.
2667   Instruction::BinaryOps AddOp;
2668   Instruction::BinaryOps MulOp;
2669   if (ScalarIVTy->isIntegerTy()) {
2670     AddOp = Instruction::Add;
2671     MulOp = Instruction::Mul;
2672   } else {
2673     AddOp = ID.getInductionOpcode();
2674     MulOp = Instruction::FMul;
2675   }
2676 
2677   // Determine the number of scalars we need to generate for each unroll
2678   // iteration. If EntryVal is uniform, we only need to generate the first
2679   // lane. Otherwise, we generate all VF values.
2680   unsigned Lanes =
2681       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
2682                                                                          : VF;
2683   // Compute the scalar steps and save the results in VectorLoopValueMap.
2684   for (unsigned Part = 0; Part < UF; ++Part) {
2685     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2686       auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2687       auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2688       auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2689       VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
2690       recordVectorLoopValueForInductionCast(ID, Add, Part, Lane);
2691     }
2692   }
2693 }
2694 
2695 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2696   const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() :
2697     ValueToValueMap();
2698 
2699   int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
2700   if (Stride == 1 || Stride == -1)
2701     return Stride;
2702   return 0;
2703 }
2704 
2705 bool LoopVectorizationLegality::isUniform(Value *V) {
2706   return LAI->isUniform(V);
2707 }
2708 
2709 Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
2710   assert(V != Induction && "The new induction variable should not be used.");
2711   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2712   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2713 
2714   // If we have a stride that is replaced by one, do it here.
2715   if (Legal->hasStride(V))
2716     V = ConstantInt::get(V->getType(), 1);
2717 
2718   // If we have a vector mapped to this value, return it.
2719   if (VectorLoopValueMap.hasVectorValue(V, Part))
2720     return VectorLoopValueMap.getVectorValue(V, Part);
2721 
2722   // If the value has not been vectorized, check if it has been scalarized
2723   // instead. If it has been scalarized, and we actually need the value in
2724   // vector form, we will construct the vector values on demand.
2725   if (VectorLoopValueMap.hasAnyScalarValue(V)) {
2726     Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
2727 
2728     // If we've scalarized a value, that value should be an instruction.
2729     auto *I = cast<Instruction>(V);
2730 
2731     // If we aren't vectorizing, we can just copy the scalar map values over to
2732     // the vector map.
2733     if (VF == 1) {
2734       VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2735       return ScalarValue;
2736     }
2737 
2738     // Get the last scalar instruction we generated for V and Part. If the value
2739     // is known to be uniform after vectorization, this corresponds to lane zero
2740     // of the Part unroll iteration. Otherwise, the last instruction is the one
2741     // we created for the last vector lane of the Part unroll iteration.
2742     unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2743     auto *LastInst = cast<Instruction>(
2744         VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
2745 
2746     // Set the insert point after the last scalarized instruction. This ensures
2747     // the insertelement sequence will directly follow the scalar definitions.
2748     auto OldIP = Builder.saveIP();
2749     auto NewIP = std::next(BasicBlock::iterator(LastInst));
2750     Builder.SetInsertPoint(&*NewIP);
2751 
2752     // However, if we are vectorizing, we need to construct the vector values.
2753     // If the value is known to be uniform after vectorization, we can just
2754     // broadcast the scalar value corresponding to lane zero for each unroll
2755     // iteration. Otherwise, we construct the vector values using insertelement
2756     // instructions. Since the resulting vectors are stored in
2757     // VectorLoopValueMap, we will only generate the insertelements once.
2758     Value *VectorValue = nullptr;
2759     if (Cost->isUniformAfterVectorization(I, VF)) {
2760       VectorValue = getBroadcastInstrs(ScalarValue);
2761       VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2762     } else {
2763       // Initialize packing with insertelements to start from undef.
2764       Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
2765       VectorLoopValueMap.setVectorValue(V, Part, Undef);
2766       for (unsigned Lane = 0; Lane < VF; ++Lane)
2767         packScalarIntoVectorValue(V, {Part, Lane});
2768       VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
2769     }
2770     Builder.restoreIP(OldIP);
2771     return VectorValue;
2772   }
2773 
2774   // If this scalar is unknown, assume that it is a constant or that it is
2775   // loop invariant. Broadcast V and save the value for future uses.
2776   Value *B = getBroadcastInstrs(V);
2777   VectorLoopValueMap.setVectorValue(V, Part, B);
2778   return B;
2779 }
2780 
2781 Value *
2782 InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
2783                                             const VPIteration &Instance) {
2784   // If the value is not an instruction contained in the loop, it should
2785   // already be scalar.
2786   if (OrigLoop->isLoopInvariant(V))
2787     return V;
2788 
2789   assert(Instance.Lane > 0
2790              ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2791              : true && "Uniform values only have lane zero");
2792 
2793   // If the value from the original loop has not been vectorized, it is
2794   // represented by UF x VF scalar values in the new loop. Return the requested
2795   // scalar value.
2796   if (VectorLoopValueMap.hasScalarValue(V, Instance))
2797     return VectorLoopValueMap.getScalarValue(V, Instance);
2798 
2799   // If the value has not been scalarized, get its entry in VectorLoopValueMap
2800   // for the given unroll part. If this entry is not a vector type (i.e., the
2801   // vectorization factor is one), there is no need to generate an
2802   // extractelement instruction.
2803   auto *U = getOrCreateVectorValue(V, Instance.Part);
2804   if (!U->getType()->isVectorTy()) {
2805     assert(VF == 1 && "Value not scalarized has non-vector type");
2806     return U;
2807   }
2808 
2809   // Otherwise, the value from the original loop has been vectorized and is
2810   // represented by UF vector values. Extract and return the requested scalar
2811   // value from the appropriate vector lane.
2812   return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
2813 }
2814 
2815 void InnerLoopVectorizer::packScalarIntoVectorValue(
2816     Value *V, const VPIteration &Instance) {
2817   assert(V != Induction && "The new induction variable should not be used.");
2818   assert(!V->getType()->isVectorTy() && "Can't pack a vector");
2819   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2820 
2821   Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
2822   Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
2823   VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
2824                                             Builder.getInt32(Instance.Lane));
2825   VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
2826 }
2827 
2828 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2829   assert(Vec->getType()->isVectorTy() && "Invalid type");
2830   SmallVector<Constant *, 8> ShuffleMask;
2831   for (unsigned i = 0; i < VF; ++i)
2832     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2833 
2834   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2835                                      ConstantVector::get(ShuffleMask),
2836                                      "reverse");
2837 }
2838 
2839 // Try to vectorize the interleave group that \p Instr belongs to.
2840 //
2841 // E.g. Translate following interleaved load group (factor = 3):
2842 //   for (i = 0; i < N; i+=3) {
2843 //     R = Pic[i];             // Member of index 0
2844 //     G = Pic[i+1];           // Member of index 1
2845 //     B = Pic[i+2];           // Member of index 2
2846 //     ... // do something to R, G, B
2847 //   }
2848 // To:
2849 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2850 //   %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9>   ; R elements
2851 //   %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10>  ; G elements
2852 //   %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11>  ; B elements
2853 //
2854 // Or translate following interleaved store group (factor = 3):
2855 //   for (i = 0; i < N; i+=3) {
2856 //     ... do something to R, G, B
2857 //     Pic[i]   = R;           // Member of index 0
2858 //     Pic[i+1] = G;           // Member of index 1
2859 //     Pic[i+2] = B;           // Member of index 2
2860 //   }
2861 // To:
2862 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2863 //   %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2864 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2865 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2866 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2867 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2868   const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2869   assert(Group && "Fail to get an interleaved access group.");
2870 
2871   // Skip if current instruction is not the insert position.
2872   if (Instr != Group->getInsertPos())
2873     return;
2874 
2875   const DataLayout &DL = Instr->getModule()->getDataLayout();
2876   Value *Ptr = getPointerOperand(Instr);
2877 
2878   // Prepare for the vector type of the interleaved load/store.
2879   Type *ScalarTy = getMemInstValueType(Instr);
2880   unsigned InterleaveFactor = Group->getFactor();
2881   Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2882   Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
2883 
2884   // Prepare for the new pointers.
2885   setDebugLocFromInst(Builder, Ptr);
2886   SmallVector<Value *, 2> NewPtrs;
2887   unsigned Index = Group->getIndex(Instr);
2888 
2889   // If the group is reverse, adjust the index to refer to the last vector lane
2890   // instead of the first. We adjust the index from the first vector lane,
2891   // rather than directly getting the pointer for lane VF - 1, because the
2892   // pointer operand of the interleaved access is supposed to be uniform. For
2893   // uniform instructions, we're only required to generate a value for the
2894   // first vector lane in each unroll iteration.
2895   if (Group->isReverse())
2896     Index += (VF - 1) * Group->getFactor();
2897 
2898   for (unsigned Part = 0; Part < UF; Part++) {
2899     Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
2900 
2901     // Notice current instruction could be any index. Need to adjust the address
2902     // to the member of index 0.
2903     //
2904     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2905     //       b = A[i];       // Member of index 0
2906     // Current pointer is pointed to A[i+1], adjust it to A[i].
2907     //
2908     // E.g.  A[i+1] = a;     // Member of index 1
2909     //       A[i]   = b;     // Member of index 0
2910     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2911     // Current pointer is pointed to A[i+2], adjust it to A[i].
2912     NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2913 
2914     // Cast to the vector pointer type.
2915     NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2916   }
2917 
2918   setDebugLocFromInst(Builder, Instr);
2919   Value *UndefVec = UndefValue::get(VecTy);
2920 
2921   // Vectorize the interleaved load group.
2922   if (isa<LoadInst>(Instr)) {
2923     // For each unroll part, create a wide load for the group.
2924     SmallVector<Value *, 2> NewLoads;
2925     for (unsigned Part = 0; Part < UF; Part++) {
2926       auto *NewLoad = Builder.CreateAlignedLoad(
2927           NewPtrs[Part], Group->getAlignment(), "wide.vec");
2928       Group->addMetadata(NewLoad);
2929       NewLoads.push_back(NewLoad);
2930     }
2931 
2932     // For each member in the group, shuffle out the appropriate data from the
2933     // wide loads.
2934     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2935       Instruction *Member = Group->getMember(I);
2936 
2937       // Skip the gaps in the group.
2938       if (!Member)
2939         continue;
2940 
2941       Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2942       for (unsigned Part = 0; Part < UF; Part++) {
2943         Value *StridedVec = Builder.CreateShuffleVector(
2944             NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2945 
2946         // If this member has different type, cast the result type.
2947         if (Member->getType() != ScalarTy) {
2948           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2949           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2950         }
2951 
2952         if (Group->isReverse())
2953           StridedVec = reverseVector(StridedVec);
2954 
2955         VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2956       }
2957     }
2958     return;
2959   }
2960 
2961   // The sub vector type for current instruction.
2962   VectorType *SubVT = VectorType::get(ScalarTy, VF);
2963 
2964   // Vectorize the interleaved store group.
2965   for (unsigned Part = 0; Part < UF; Part++) {
2966     // Collect the stored vector from each member.
2967     SmallVector<Value *, 4> StoredVecs;
2968     for (unsigned i = 0; i < InterleaveFactor; i++) {
2969       // Interleaved store group doesn't allow a gap, so each index has a member
2970       Instruction *Member = Group->getMember(i);
2971       assert(Member && "Fail to get a member from an interleaved store group");
2972 
2973       Value *StoredVec = getOrCreateVectorValue(
2974           cast<StoreInst>(Member)->getValueOperand(), Part);
2975       if (Group->isReverse())
2976         StoredVec = reverseVector(StoredVec);
2977 
2978       // If this member has different type, cast it to a unified type.
2979 
2980       if (StoredVec->getType() != SubVT)
2981         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2982 
2983       StoredVecs.push_back(StoredVec);
2984     }
2985 
2986     // Concatenate all vectors into a wide vector.
2987     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2988 
2989     // Interleave the elements in the wide vector.
2990     Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2991     Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2992                                               "interleaved.vec");
2993 
2994     Instruction *NewStoreInstr =
2995         Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2996 
2997     Group->addMetadata(NewStoreInstr);
2998   }
2999 }
3000 
3001 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
3002                                                      VectorParts *BlockInMask) {
3003   // Attempt to issue a wide load.
3004   LoadInst *LI = dyn_cast<LoadInst>(Instr);
3005   StoreInst *SI = dyn_cast<StoreInst>(Instr);
3006 
3007   assert((LI || SI) && "Invalid Load/Store instruction");
3008 
3009   LoopVectorizationCostModel::InstWidening Decision =
3010       Cost->getWideningDecision(Instr, VF);
3011   assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
3012          "CM decision should be taken at this point");
3013   if (Decision == LoopVectorizationCostModel::CM_Interleave)
3014     return vectorizeInterleaveGroup(Instr);
3015 
3016   Type *ScalarDataTy = getMemInstValueType(Instr);
3017   Type *DataTy = VectorType::get(ScalarDataTy, VF);
3018   Value *Ptr = getPointerOperand(Instr);
3019   unsigned Alignment = getMemInstAlignment(Instr);
3020   // An alignment of 0 means target abi alignment. We need to use the scalar's
3021   // target abi alignment in such a case.
3022   const DataLayout &DL = Instr->getModule()->getDataLayout();
3023   if (!Alignment)
3024     Alignment = DL.getABITypeAlignment(ScalarDataTy);
3025   unsigned AddressSpace = getMemInstAddressSpace(Instr);
3026 
3027   // Determine if the pointer operand of the access is either consecutive or
3028   // reverse consecutive.
3029   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
3030   bool ConsecutiveStride =
3031       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
3032   bool CreateGatherScatter =
3033       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
3034 
3035   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
3036   // gather/scatter. Otherwise Decision should have been to Scalarize.
3037   assert((ConsecutiveStride || CreateGatherScatter) &&
3038          "The instruction should be scalarized");
3039 
3040   // Handle consecutive loads/stores.
3041   if (ConsecutiveStride)
3042     Ptr = getOrCreateScalarValue(Ptr, {0, 0});
3043 
3044   VectorParts Mask;
3045   bool isMaskRequired = BlockInMask;
3046   if (isMaskRequired)
3047     Mask = *BlockInMask;
3048 
3049   // Handle Stores:
3050   if (SI) {
3051     assert(!Legal->isUniform(SI->getPointerOperand()) &&
3052            "We do not allow storing to uniform addresses");
3053     setDebugLocFromInst(Builder, SI);
3054 
3055     for (unsigned Part = 0; Part < UF; ++Part) {
3056       Instruction *NewSI = nullptr;
3057       Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
3058       if (CreateGatherScatter) {
3059         Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
3060         Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3061         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
3062                                             MaskPart);
3063       } else {
3064         // Calculate the pointer for the specific unroll-part.
3065         Value *PartPtr =
3066             Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3067 
3068         if (Reverse) {
3069           // If we store to reverse consecutive memory locations, then we need
3070           // to reverse the order of elements in the stored value.
3071           StoredVal = reverseVector(StoredVal);
3072           // We don't want to update the value in the map as it might be used in
3073           // another expression. So don't call resetVectorValue(StoredVal).
3074 
3075           // If the address is consecutive but reversed, then the
3076           // wide store needs to start at the last vector element.
3077           PartPtr =
3078               Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3079           PartPtr =
3080               Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3081           if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
3082             Mask[Part] = reverseVector(Mask[Part]);
3083         }
3084 
3085         Value *VecPtr =
3086             Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3087 
3088         if (isMaskRequired)
3089           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
3090                                             Mask[Part]);
3091         else
3092           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
3093       }
3094       addMetadata(NewSI, SI);
3095     }
3096     return;
3097   }
3098 
3099   // Handle loads.
3100   assert(LI && "Must have a load instruction");
3101   setDebugLocFromInst(Builder, LI);
3102   for (unsigned Part = 0; Part < UF; ++Part) {
3103     Value *NewLI;
3104     if (CreateGatherScatter) {
3105       Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
3106       Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3107       NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
3108                                          nullptr, "wide.masked.gather");
3109       addMetadata(NewLI, LI);
3110     } else {
3111       // Calculate the pointer for the specific unroll-part.
3112       Value *PartPtr =
3113           Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3114 
3115       if (Reverse) {
3116         // If the address is consecutive but reversed, then the
3117         // wide load needs to start at the last vector element.
3118         PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3119         PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3120         if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
3121           Mask[Part] = reverseVector(Mask[Part]);
3122       }
3123 
3124       Value *VecPtr =
3125           Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3126       if (isMaskRequired)
3127         NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
3128                                          UndefValue::get(DataTy),
3129                                          "wide.masked.load");
3130       else
3131         NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
3132 
3133       // Add metadata to the load, but setVectorValue to the reverse shuffle.
3134       addMetadata(NewLI, LI);
3135       if (Reverse)
3136         NewLI = reverseVector(NewLI);
3137     }
3138     VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
3139   }
3140 }
3141 
3142 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
3143                                                const VPIteration &Instance,
3144                                                bool IfPredicateInstr) {
3145   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3146 
3147   setDebugLocFromInst(Builder, Instr);
3148 
3149   // Does this instruction return a value ?
3150   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3151 
3152   Instruction *Cloned = Instr->clone();
3153   if (!IsVoidRetTy)
3154     Cloned->setName(Instr->getName() + ".cloned");
3155 
3156   // Replace the operands of the cloned instructions with their scalar
3157   // equivalents in the new loop.
3158   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
3159     auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
3160     Cloned->setOperand(op, NewOp);
3161   }
3162   addNewMetadata(Cloned, Instr);
3163 
3164   // Place the cloned scalar in the new loop.
3165   Builder.Insert(Cloned);
3166 
3167   // Add the cloned scalar to the scalar map entry.
3168   VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
3169 
3170   // If we just cloned a new assumption, add it the assumption cache.
3171   if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
3172     if (II->getIntrinsicID() == Intrinsic::assume)
3173       AC->registerAssumption(II);
3174 
3175   // End if-block.
3176   if (IfPredicateInstr)
3177     PredicatedInstructions.push_back(Cloned);
3178 }
3179 
3180 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3181                                                       Value *End, Value *Step,
3182                                                       Instruction *DL) {
3183   BasicBlock *Header = L->getHeader();
3184   BasicBlock *Latch = L->getLoopLatch();
3185   // As we're just creating this loop, it's possible no latch exists
3186   // yet. If so, use the header as this will be a single block loop.
3187   if (!Latch)
3188     Latch = Header;
3189 
3190   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
3191   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3192   setDebugLocFromInst(Builder, OldInst);
3193   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
3194 
3195   Builder.SetInsertPoint(Latch->getTerminator());
3196   setDebugLocFromInst(Builder, OldInst);
3197 
3198   // Create i+1 and fill the PHINode.
3199   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
3200   Induction->addIncoming(Start, L->getLoopPreheader());
3201   Induction->addIncoming(Next, Latch);
3202   // Create the compare.
3203   Value *ICmp = Builder.CreateICmpEQ(Next, End);
3204   Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
3205 
3206   // Now we have two terminators. Remove the old one from the block.
3207   Latch->getTerminator()->eraseFromParent();
3208 
3209   return Induction;
3210 }
3211 
3212 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3213   if (TripCount)
3214     return TripCount;
3215 
3216   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3217   // Find the loop boundaries.
3218   ScalarEvolution *SE = PSE.getSE();
3219   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3220   assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
3221          "Invalid loop count");
3222 
3223   Type *IdxTy = Legal->getWidestInductionType();
3224 
3225   // The exit count might have the type of i64 while the phi is i32. This can
3226   // happen if we have an induction variable that is sign extended before the
3227   // compare. The only way that we get a backedge taken count is that the
3228   // induction variable was signed and as such will not overflow. In such a case
3229   // truncation is legal.
3230   if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
3231       IdxTy->getPrimitiveSizeInBits())
3232     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3233   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3234 
3235   // Get the total trip count from the count by adding 1.
3236   const SCEV *ExitCount = SE->getAddExpr(
3237       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3238 
3239   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3240 
3241   // Expand the trip count and place the new instructions in the preheader.
3242   // Notice that the pre-header does not change, only the loop body.
3243   SCEVExpander Exp(*SE, DL, "induction");
3244 
3245   // Count holds the overall loop count (N).
3246   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3247                                 L->getLoopPreheader()->getTerminator());
3248 
3249   if (TripCount->getType()->isPointerTy())
3250     TripCount =
3251         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3252                                     L->getLoopPreheader()->getTerminator());
3253 
3254   return TripCount;
3255 }
3256 
3257 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3258   if (VectorTripCount)
3259     return VectorTripCount;
3260 
3261   Value *TC = getOrCreateTripCount(L);
3262   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3263 
3264   // Now we need to generate the expression for the part of the loop that the
3265   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3266   // iterations are not required for correctness, or N - Step, otherwise. Step
3267   // is equal to the vectorization factor (number of SIMD elements) times the
3268   // unroll factor (number of SIMD instructions).
3269   Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
3270   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3271 
3272   // If there is a non-reversed interleaved group that may speculatively access
3273   // memory out-of-bounds, we need to ensure that there will be at least one
3274   // iteration of the scalar epilogue loop. Thus, if the step evenly divides
3275   // the trip count, we set the remainder to be equal to the step. If the step
3276   // does not evenly divide the trip count, no adjustment is necessary since
3277   // there will already be scalar iterations. Note that the minimum iterations
3278   // check ensures that N >= Step.
3279   if (VF > 1 && Legal->requiresScalarEpilogue()) {
3280     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3281     R = Builder.CreateSelect(IsZero, Step, R);
3282   }
3283 
3284   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3285 
3286   return VectorTripCount;
3287 }
3288 
3289 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3290                                                    const DataLayout &DL) {
3291   // Verify that V is a vector type with same number of elements as DstVTy.
3292   unsigned VF = DstVTy->getNumElements();
3293   VectorType *SrcVecTy = cast<VectorType>(V->getType());
3294   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3295   Type *SrcElemTy = SrcVecTy->getElementType();
3296   Type *DstElemTy = DstVTy->getElementType();
3297   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3298          "Vector elements must have same size");
3299 
3300   // Do a direct cast if element types are castable.
3301   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3302     return Builder.CreateBitOrPointerCast(V, DstVTy);
3303   }
3304   // V cannot be directly casted to desired vector type.
3305   // May happen when V is a floating point vector but DstVTy is a vector of
3306   // pointers or vice-versa. Handle this using a two-step bitcast using an
3307   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3308   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3309          "Only one type should be a pointer type");
3310   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3311          "Only one type should be a floating point type");
3312   Type *IntTy =
3313       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3314   VectorType *VecIntTy = VectorType::get(IntTy, VF);
3315   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3316   return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3317 }
3318 
3319 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3320                                                          BasicBlock *Bypass) {
3321   Value *Count = getOrCreateTripCount(L);
3322   BasicBlock *BB = L->getLoopPreheader();
3323   IRBuilder<> Builder(BB->getTerminator());
3324 
3325   // Generate code to check if the loop's trip count is less than VF * UF, or
3326   // equal to it in case a scalar epilogue is required; this implies that the
3327   // vector trip count is zero. This check also covers the case where adding one
3328   // to the backedge-taken count overflowed leading to an incorrect trip count
3329   // of zero. In this case we will also jump to the scalar loop.
3330   auto P = Legal->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
3331                                            : ICmpInst::ICMP_ULT;
3332   Value *CheckMinIters = Builder.CreateICmp(
3333       P, Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
3334 
3335   BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3336   // Update dominator tree immediately if the generated block is a
3337   // LoopBypassBlock because SCEV expansions to generate loop bypass
3338   // checks may query it before the current function is finished.
3339   DT->addNewBlock(NewBB, BB);
3340   if (L->getParentLoop())
3341     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3342   ReplaceInstWithInst(BB->getTerminator(),
3343                       BranchInst::Create(Bypass, NewBB, CheckMinIters));
3344   LoopBypassBlocks.push_back(BB);
3345 }
3346 
3347 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3348   BasicBlock *BB = L->getLoopPreheader();
3349 
3350   // Generate the code to check that the SCEV assumptions that we made.
3351   // We want the new basic block to start at the first instruction in a
3352   // sequence of instructions that form a check.
3353   SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
3354                    "scev.check");
3355   Value *SCEVCheck =
3356       Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
3357 
3358   if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
3359     if (C->isZero())
3360       return;
3361 
3362   // Create a new block containing the stride check.
3363   BB->setName("vector.scevcheck");
3364   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3365   // Update dominator tree immediately if the generated block is a
3366   // LoopBypassBlock because SCEV expansions to generate loop bypass
3367   // checks may query it before the current function is finished.
3368   DT->addNewBlock(NewBB, BB);
3369   if (L->getParentLoop())
3370     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3371   ReplaceInstWithInst(BB->getTerminator(),
3372                       BranchInst::Create(Bypass, NewBB, SCEVCheck));
3373   LoopBypassBlocks.push_back(BB);
3374   AddedSafetyChecks = true;
3375 }
3376 
3377 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
3378   BasicBlock *BB = L->getLoopPreheader();
3379 
3380   // Generate the code that checks in runtime if arrays overlap. We put the
3381   // checks into a separate block to make the more common case of few elements
3382   // faster.
3383   Instruction *FirstCheckInst;
3384   Instruction *MemRuntimeCheck;
3385   std::tie(FirstCheckInst, MemRuntimeCheck) =
3386       Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
3387   if (!MemRuntimeCheck)
3388     return;
3389 
3390   // Create a new block containing the memory check.
3391   BB->setName("vector.memcheck");
3392   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3393   // Update dominator tree immediately if the generated block is a
3394   // LoopBypassBlock because SCEV expansions to generate loop bypass
3395   // checks may query it before the current function is finished.
3396   DT->addNewBlock(NewBB, BB);
3397   if (L->getParentLoop())
3398     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3399   ReplaceInstWithInst(BB->getTerminator(),
3400                       BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
3401   LoopBypassBlocks.push_back(BB);
3402   AddedSafetyChecks = true;
3403 
3404   // We currently don't use LoopVersioning for the actual loop cloning but we
3405   // still use it to add the noalias metadata.
3406   LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
3407                                            PSE.getSE());
3408   LVer->prepareNoAliasMetadata();
3409 }
3410 
3411 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3412   /*
3413    In this function we generate a new loop. The new loop will contain
3414    the vectorized instructions while the old loop will continue to run the
3415    scalar remainder.
3416 
3417        [ ] <-- loop iteration number check.
3418     /   |
3419    /    v
3420   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3421   |  /  |
3422   | /   v
3423   ||   [ ]     <-- vector pre header.
3424   |/    |
3425   |     v
3426   |    [  ] \
3427   |    [  ]_|   <-- vector loop.
3428   |     |
3429   |     v
3430   |   -[ ]   <--- middle-block.
3431   |  /  |
3432   | /   v
3433   -|- >[ ]     <--- new preheader.
3434    |    |
3435    |    v
3436    |   [ ] \
3437    |   [ ]_|   <-- old scalar loop to handle remainder.
3438     \   |
3439      \  v
3440       >[ ]     <-- exit block.
3441    ...
3442    */
3443 
3444   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
3445   BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
3446   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
3447   assert(VectorPH && "Invalid loop structure");
3448   assert(ExitBlock && "Must have an exit block");
3449 
3450   // Some loops have a single integer induction variable, while other loops
3451   // don't. One example is c++ iterators that often have multiple pointer
3452   // induction variables. In the code below we also support a case where we
3453   // don't have a single induction variable.
3454   //
3455   // We try to obtain an induction variable from the original loop as hard
3456   // as possible. However if we don't find one that:
3457   //   - is an integer
3458   //   - counts from zero, stepping by one
3459   //   - is the size of the widest induction variable type
3460   // then we create a new one.
3461   OldInduction = Legal->getPrimaryInduction();
3462   Type *IdxTy = Legal->getWidestInductionType();
3463 
3464   // Split the single block loop into the two loop structure described above.
3465   BasicBlock *VecBody =
3466       VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
3467   BasicBlock *MiddleBlock =
3468       VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
3469   BasicBlock *ScalarPH =
3470       MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
3471 
3472   // Create and register the new vector loop.
3473   Loop *Lp = LI->AllocateLoop();
3474   Loop *ParentLoop = OrigLoop->getParentLoop();
3475 
3476   // Insert the new loop into the loop nest and register the new basic blocks
3477   // before calling any utilities such as SCEV that require valid LoopInfo.
3478   if (ParentLoop) {
3479     ParentLoop->addChildLoop(Lp);
3480     ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
3481     ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
3482   } else {
3483     LI->addTopLevelLoop(Lp);
3484   }
3485   Lp->addBasicBlockToLoop(VecBody, *LI);
3486 
3487   // Find the loop boundaries.
3488   Value *Count = getOrCreateTripCount(Lp);
3489 
3490   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3491 
3492   // Now, compare the new count to zero. If it is zero skip the vector loop and
3493   // jump to the scalar loop. This check also covers the case where the
3494   // backedge-taken count is uint##_max: adding one to it will overflow leading
3495   // to an incorrect trip count of zero. In this (rare) case we will also jump
3496   // to the scalar loop.
3497   emitMinimumIterationCountCheck(Lp, ScalarPH);
3498 
3499   // Generate the code to check any assumptions that we've made for SCEV
3500   // expressions.
3501   emitSCEVChecks(Lp, ScalarPH);
3502 
3503   // Generate the code that checks in runtime if arrays overlap. We put the
3504   // checks into a separate block to make the more common case of few elements
3505   // faster.
3506   emitMemRuntimeChecks(Lp, ScalarPH);
3507 
3508   // Generate the induction variable.
3509   // The loop step is equal to the vectorization factor (num of SIMD elements)
3510   // times the unroll factor (num of SIMD instructions).
3511   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3512   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
3513   Induction =
3514       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3515                               getDebugLocFromInstOrOperands(OldInduction));
3516 
3517   // We are going to resume the execution of the scalar loop.
3518   // Go over all of the induction variables that we found and fix the
3519   // PHIs that are left in the scalar version of the loop.
3520   // The starting values of PHI nodes depend on the counter of the last
3521   // iteration in the vectorized loop.
3522   // If we come from a bypass edge then we need to start from the original
3523   // start value.
3524 
3525   // This variable saves the new starting index for the scalar loop. It is used
3526   // to test if there are any tail iterations left once the vector loop has
3527   // completed.
3528   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
3529   for (auto &InductionEntry : *List) {
3530     PHINode *OrigPhi = InductionEntry.first;
3531     InductionDescriptor II = InductionEntry.second;
3532 
3533     // Create phi nodes to merge from the  backedge-taken check block.
3534     PHINode *BCResumeVal = PHINode::Create(
3535         OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
3536     Value *&EndValue = IVEndValues[OrigPhi];
3537     if (OrigPhi == OldInduction) {
3538       // We know what the end value is.
3539       EndValue = CountRoundDown;
3540     } else {
3541       IRBuilder<> B(Lp->getLoopPreheader()->getTerminator());
3542       Type *StepType = II.getStep()->getType();
3543       Instruction::CastOps CastOp =
3544         CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
3545       Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
3546       const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3547       EndValue = II.transform(B, CRD, PSE.getSE(), DL);
3548       EndValue->setName("ind.end");
3549     }
3550 
3551     // The new PHI merges the original incoming value, in case of a bypass,
3552     // or the value at the end of the vectorized loop.
3553     BCResumeVal->addIncoming(EndValue, MiddleBlock);
3554 
3555     // Fix the scalar body counter (PHI node).
3556     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
3557 
3558     // The old induction's phi node in the scalar body needs the truncated
3559     // value.
3560     for (BasicBlock *BB : LoopBypassBlocks)
3561       BCResumeVal->addIncoming(II.getStartValue(), BB);
3562     OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
3563   }
3564 
3565   // Add a check in the middle block to see if we have completed
3566   // all of the iterations in the first vector loop.
3567   // If (N - N%VF) == N, then we *don't* need to run the remainder.
3568   Value *CmpN =
3569       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
3570                       CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
3571   ReplaceInstWithInst(MiddleBlock->getTerminator(),
3572                       BranchInst::Create(ExitBlock, ScalarPH, CmpN));
3573 
3574   // Get ready to start creating new instructions into the vectorized body.
3575   Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
3576 
3577   // Save the state.
3578   LoopVectorPreHeader = Lp->getLoopPreheader();
3579   LoopScalarPreHeader = ScalarPH;
3580   LoopMiddleBlock = MiddleBlock;
3581   LoopExitBlock = ExitBlock;
3582   LoopVectorBody = VecBody;
3583   LoopScalarBody = OldBasicBlock;
3584 
3585   // Keep all loop hints from the original loop on the vector loop (we'll
3586   // replace the vectorizer-specific hints below).
3587   if (MDNode *LID = OrigLoop->getLoopID())
3588     Lp->setLoopID(LID);
3589 
3590   LoopVectorizeHints Hints(Lp, true, *ORE);
3591   Hints.setAlreadyVectorized();
3592 
3593   return LoopVectorPreHeader;
3594 }
3595 
3596 // Fix up external users of the induction variable. At this point, we are
3597 // in LCSSA form, with all external PHIs that use the IV having one input value,
3598 // coming from the remainder loop. We need those PHIs to also have a correct
3599 // value for the IV when arriving directly from the middle block.
3600 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3601                                        const InductionDescriptor &II,
3602                                        Value *CountRoundDown, Value *EndValue,
3603                                        BasicBlock *MiddleBlock) {
3604   // There are two kinds of external IV usages - those that use the value
3605   // computed in the last iteration (the PHI) and those that use the penultimate
3606   // value (the value that feeds into the phi from the loop latch).
3607   // We allow both, but they, obviously, have different values.
3608 
3609   assert(OrigLoop->getExitBlock() && "Expected a single exit block");
3610 
3611   DenseMap<Value *, Value *> MissingVals;
3612 
3613   // An external user of the last iteration's value should see the value that
3614   // the remainder loop uses to initialize its own IV.
3615   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3616   for (User *U : PostInc->users()) {
3617     Instruction *UI = cast<Instruction>(U);
3618     if (!OrigLoop->contains(UI)) {
3619       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3620       MissingVals[UI] = EndValue;
3621     }
3622   }
3623 
3624   // An external user of the penultimate value need to see EndValue - Step.
3625   // The simplest way to get this is to recompute it from the constituent SCEVs,
3626   // that is Start + (Step * (CRD - 1)).
3627   for (User *U : OrigPhi->users()) {
3628     auto *UI = cast<Instruction>(U);
3629     if (!OrigLoop->contains(UI)) {
3630       const DataLayout &DL =
3631           OrigLoop->getHeader()->getModule()->getDataLayout();
3632       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3633 
3634       IRBuilder<> B(MiddleBlock->getTerminator());
3635       Value *CountMinusOne = B.CreateSub(
3636           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3637       Value *CMO =
3638           !II.getStep()->getType()->isIntegerTy()
3639               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3640                              II.getStep()->getType())
3641               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3642       CMO->setName("cast.cmo");
3643       Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3644       Escape->setName("ind.escape");
3645       MissingVals[UI] = Escape;
3646     }
3647   }
3648 
3649   for (auto &I : MissingVals) {
3650     PHINode *PHI = cast<PHINode>(I.first);
3651     // One corner case we have to handle is two IVs "chasing" each-other,
3652     // that is %IV2 = phi [...], [ %IV1, %latch ]
3653     // In this case, if IV1 has an external use, we need to avoid adding both
3654     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3655     // don't already have an incoming value for the middle block.
3656     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3657       PHI->addIncoming(I.second, MiddleBlock);
3658   }
3659 }
3660 
3661 namespace {
3662 
3663 struct CSEDenseMapInfo {
3664   static bool canHandle(const Instruction *I) {
3665     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3666            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3667   }
3668 
3669   static inline Instruction *getEmptyKey() {
3670     return DenseMapInfo<Instruction *>::getEmptyKey();
3671   }
3672 
3673   static inline Instruction *getTombstoneKey() {
3674     return DenseMapInfo<Instruction *>::getTombstoneKey();
3675   }
3676 
3677   static unsigned getHashValue(const Instruction *I) {
3678     assert(canHandle(I) && "Unknown instruction!");
3679     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3680                                                            I->value_op_end()));
3681   }
3682 
3683   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3684     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3685         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3686       return LHS == RHS;
3687     return LHS->isIdenticalTo(RHS);
3688   }
3689 };
3690 
3691 } // end anonymous namespace
3692 
3693 ///\brief Perform cse of induction variable instructions.
3694 static void cse(BasicBlock *BB) {
3695   // Perform simple cse.
3696   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3697   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3698     Instruction *In = &*I++;
3699 
3700     if (!CSEDenseMapInfo::canHandle(In))
3701       continue;
3702 
3703     // Check if we can replace this instruction with any of the
3704     // visited instructions.
3705     if (Instruction *V = CSEMap.lookup(In)) {
3706       In->replaceAllUsesWith(V);
3707       In->eraseFromParent();
3708       continue;
3709     }
3710 
3711     CSEMap[In] = In;
3712   }
3713 }
3714 
3715 /// \brief Estimate the overhead of scalarizing an instruction. This is a
3716 /// convenience wrapper for the type-based getScalarizationOverhead API.
3717 static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
3718                                          const TargetTransformInfo &TTI) {
3719   if (VF == 1)
3720     return 0;
3721 
3722   unsigned Cost = 0;
3723   Type *RetTy = ToVectorTy(I->getType(), VF);
3724   if (!RetTy->isVoidTy() &&
3725       (!isa<LoadInst>(I) ||
3726        !TTI.supportsEfficientVectorElementLoadStore()))
3727     Cost += TTI.getScalarizationOverhead(RetTy, true, false);
3728 
3729   if (CallInst *CI = dyn_cast<CallInst>(I)) {
3730     SmallVector<const Value *, 4> Operands(CI->arg_operands());
3731     Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3732   }
3733   else if (!isa<StoreInst>(I) ||
3734            !TTI.supportsEfficientVectorElementLoadStore()) {
3735     SmallVector<const Value *, 4> Operands(I->operand_values());
3736     Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3737   }
3738 
3739   return Cost;
3740 }
3741 
3742 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3743 // Return the cost of the instruction, including scalarization overhead if it's
3744 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3745 // i.e. either vector version isn't available, or is too expensive.
3746 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3747                                   const TargetTransformInfo &TTI,
3748                                   const TargetLibraryInfo *TLI,
3749                                   bool &NeedToScalarize) {
3750   Function *F = CI->getCalledFunction();
3751   StringRef FnName = CI->getCalledFunction()->getName();
3752   Type *ScalarRetTy = CI->getType();
3753   SmallVector<Type *, 4> Tys, ScalarTys;
3754   for (auto &ArgOp : CI->arg_operands())
3755     ScalarTys.push_back(ArgOp->getType());
3756 
3757   // Estimate cost of scalarized vector call. The source operands are assumed
3758   // to be vectors, so we need to extract individual elements from there,
3759   // execute VF scalar calls, and then gather the result into the vector return
3760   // value.
3761   unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3762   if (VF == 1)
3763     return ScalarCallCost;
3764 
3765   // Compute corresponding vector type for return value and arguments.
3766   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3767   for (Type *ScalarTy : ScalarTys)
3768     Tys.push_back(ToVectorTy(ScalarTy, VF));
3769 
3770   // Compute costs of unpacking argument values for the scalar calls and
3771   // packing the return values to a vector.
3772   unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3773 
3774   unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3775 
3776   // If we can't emit a vector call for this function, then the currently found
3777   // cost is the cost we need to return.
3778   NeedToScalarize = true;
3779   if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3780     return Cost;
3781 
3782   // If the corresponding vector cost is cheaper, return its cost.
3783   unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3784   if (VectorCallCost < Cost) {
3785     NeedToScalarize = false;
3786     return VectorCallCost;
3787   }
3788   return Cost;
3789 }
3790 
3791 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3792 // factor VF.  Return the cost of the instruction, including scalarization
3793 // overhead if it's needed.
3794 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3795                                        const TargetTransformInfo &TTI,
3796                                        const TargetLibraryInfo *TLI) {
3797   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3798   assert(ID && "Expected intrinsic call!");
3799 
3800   FastMathFlags FMF;
3801   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3802     FMF = FPMO->getFastMathFlags();
3803 
3804   SmallVector<Value *, 4> Operands(CI->arg_operands());
3805   return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3806 }
3807 
3808 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3809   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3810   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3811   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3812 }
3813 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3814   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3815   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3816   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3817 }
3818 
3819 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3820   // For every instruction `I` in MinBWs, truncate the operands, create a
3821   // truncated version of `I` and reextend its result. InstCombine runs
3822   // later and will remove any ext/trunc pairs.
3823   SmallPtrSet<Value *, 4> Erased;
3824   for (const auto &KV : Cost->getMinimalBitwidths()) {
3825     // If the value wasn't vectorized, we must maintain the original scalar
3826     // type. The absence of the value from VectorLoopValueMap indicates that it
3827     // wasn't vectorized.
3828     if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3829       continue;
3830     for (unsigned Part = 0; Part < UF; ++Part) {
3831       Value *I = getOrCreateVectorValue(KV.first, Part);
3832       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3833         continue;
3834       Type *OriginalTy = I->getType();
3835       Type *ScalarTruncatedTy =
3836           IntegerType::get(OriginalTy->getContext(), KV.second);
3837       Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3838                                           OriginalTy->getVectorNumElements());
3839       if (TruncatedTy == OriginalTy)
3840         continue;
3841 
3842       IRBuilder<> B(cast<Instruction>(I));
3843       auto ShrinkOperand = [&](Value *V) -> Value * {
3844         if (auto *ZI = dyn_cast<ZExtInst>(V))
3845           if (ZI->getSrcTy() == TruncatedTy)
3846             return ZI->getOperand(0);
3847         return B.CreateZExtOrTrunc(V, TruncatedTy);
3848       };
3849 
3850       // The actual instruction modification depends on the instruction type,
3851       // unfortunately.
3852       Value *NewI = nullptr;
3853       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3854         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3855                              ShrinkOperand(BO->getOperand(1)));
3856 
3857         // Any wrapping introduced by shrinking this operation shouldn't be
3858         // considered undefined behavior. So, we can't unconditionally copy
3859         // arithmetic wrapping flags to NewI.
3860         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3861       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3862         NewI =
3863             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3864                          ShrinkOperand(CI->getOperand(1)));
3865       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3866         NewI = B.CreateSelect(SI->getCondition(),
3867                               ShrinkOperand(SI->getTrueValue()),
3868                               ShrinkOperand(SI->getFalseValue()));
3869       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3870         switch (CI->getOpcode()) {
3871         default:
3872           llvm_unreachable("Unhandled cast!");
3873         case Instruction::Trunc:
3874           NewI = ShrinkOperand(CI->getOperand(0));
3875           break;
3876         case Instruction::SExt:
3877           NewI = B.CreateSExtOrTrunc(
3878               CI->getOperand(0),
3879               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3880           break;
3881         case Instruction::ZExt:
3882           NewI = B.CreateZExtOrTrunc(
3883               CI->getOperand(0),
3884               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3885           break;
3886         }
3887       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3888         auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3889         auto *O0 = B.CreateZExtOrTrunc(
3890             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3891         auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3892         auto *O1 = B.CreateZExtOrTrunc(
3893             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3894 
3895         NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3896       } else if (isa<LoadInst>(I)) {
3897         // Don't do anything with the operands, just extend the result.
3898         continue;
3899       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3900         auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3901         auto *O0 = B.CreateZExtOrTrunc(
3902             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3903         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3904         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3905       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3906         auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3907         auto *O0 = B.CreateZExtOrTrunc(
3908             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3909         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3910       } else {
3911         llvm_unreachable("Unhandled instruction type!");
3912       }
3913 
3914       // Lastly, extend the result.
3915       NewI->takeName(cast<Instruction>(I));
3916       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3917       I->replaceAllUsesWith(Res);
3918       cast<Instruction>(I)->eraseFromParent();
3919       Erased.insert(I);
3920       VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3921     }
3922   }
3923 
3924   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3925   for (const auto &KV : Cost->getMinimalBitwidths()) {
3926     // If the value wasn't vectorized, we must maintain the original scalar
3927     // type. The absence of the value from VectorLoopValueMap indicates that it
3928     // wasn't vectorized.
3929     if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3930       continue;
3931     for (unsigned Part = 0; Part < UF; ++Part) {
3932       Value *I = getOrCreateVectorValue(KV.first, Part);
3933       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3934       if (Inst && Inst->use_empty()) {
3935         Value *NewI = Inst->getOperand(0);
3936         Inst->eraseFromParent();
3937         VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3938       }
3939     }
3940   }
3941 }
3942 
3943 void InnerLoopVectorizer::fixVectorizedLoop() {
3944   // Insert truncates and extends for any truncated instructions as hints to
3945   // InstCombine.
3946   if (VF > 1)
3947     truncateToMinimalBitwidths();
3948 
3949   // At this point every instruction in the original loop is widened to a
3950   // vector form. Now we need to fix the recurrences in the loop. These PHI
3951   // nodes are currently empty because we did not want to introduce cycles.
3952   // This is the second stage of vectorizing recurrences.
3953   fixCrossIterationPHIs();
3954 
3955   // Update the dominator tree.
3956   //
3957   // FIXME: After creating the structure of the new loop, the dominator tree is
3958   //        no longer up-to-date, and it remains that way until we update it
3959   //        here. An out-of-date dominator tree is problematic for SCEV,
3960   //        because SCEVExpander uses it to guide code generation. The
3961   //        vectorizer use SCEVExpanders in several places. Instead, we should
3962   //        keep the dominator tree up-to-date as we go.
3963   updateAnalysis();
3964 
3965   // Fix-up external users of the induction variables.
3966   for (auto &Entry : *Legal->getInductionVars())
3967     fixupIVUsers(Entry.first, Entry.second,
3968                  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3969                  IVEndValues[Entry.first], LoopMiddleBlock);
3970 
3971   fixLCSSAPHIs();
3972   for (Instruction *PI : PredicatedInstructions)
3973     sinkScalarOperands(&*PI);
3974 
3975   // Remove redundant induction instructions.
3976   cse(LoopVectorBody);
3977 }
3978 
3979 void InnerLoopVectorizer::fixCrossIterationPHIs() {
3980   // In order to support recurrences we need to be able to vectorize Phi nodes.
3981   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3982   // stage #2: We now need to fix the recurrences by adding incoming edges to
3983   // the currently empty PHI nodes. At this point every instruction in the
3984   // original loop is widened to a vector form so we can use them to construct
3985   // the incoming edges.
3986   for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
3987     // Handle first-order recurrences and reductions that need to be fixed.
3988     if (Legal->isFirstOrderRecurrence(&Phi))
3989       fixFirstOrderRecurrence(&Phi);
3990     else if (Legal->isReductionVariable(&Phi))
3991       fixReduction(&Phi);
3992   }
3993 }
3994 
3995 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3996   // This is the second phase of vectorizing first-order recurrences. An
3997   // overview of the transformation is described below. Suppose we have the
3998   // following loop.
3999   //
4000   //   for (int i = 0; i < n; ++i)
4001   //     b[i] = a[i] - a[i - 1];
4002   //
4003   // There is a first-order recurrence on "a". For this loop, the shorthand
4004   // scalar IR looks like:
4005   //
4006   //   scalar.ph:
4007   //     s_init = a[-1]
4008   //     br scalar.body
4009   //
4010   //   scalar.body:
4011   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4012   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4013   //     s2 = a[i]
4014   //     b[i] = s2 - s1
4015   //     br cond, scalar.body, ...
4016   //
4017   // In this example, s1 is a recurrence because it's value depends on the
4018   // previous iteration. In the first phase of vectorization, we created a
4019   // temporary value for s1. We now complete the vectorization and produce the
4020   // shorthand vector IR shown below (for VF = 4, UF = 1).
4021   //
4022   //   vector.ph:
4023   //     v_init = vector(..., ..., ..., a[-1])
4024   //     br vector.body
4025   //
4026   //   vector.body
4027   //     i = phi [0, vector.ph], [i+4, vector.body]
4028   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4029   //     v2 = a[i, i+1, i+2, i+3];
4030   //     v3 = vector(v1(3), v2(0, 1, 2))
4031   //     b[i, i+1, i+2, i+3] = v2 - v3
4032   //     br cond, vector.body, middle.block
4033   //
4034   //   middle.block:
4035   //     x = v2(3)
4036   //     br scalar.ph
4037   //
4038   //   scalar.ph:
4039   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4040   //     br scalar.body
4041   //
4042   // After execution completes the vector loop, we extract the next value of
4043   // the recurrence (x) to use as the initial value in the scalar loop.
4044 
4045   // Get the original loop preheader and single loop latch.
4046   auto *Preheader = OrigLoop->getLoopPreheader();
4047   auto *Latch = OrigLoop->getLoopLatch();
4048 
4049   // Get the initial and previous values of the scalar recurrence.
4050   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4051   auto *Previous = Phi->getIncomingValueForBlock(Latch);
4052 
4053   // Create a vector from the initial value.
4054   auto *VectorInit = ScalarInit;
4055   if (VF > 1) {
4056     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4057     VectorInit = Builder.CreateInsertElement(
4058         UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
4059         Builder.getInt32(VF - 1), "vector.recur.init");
4060   }
4061 
4062   // We constructed a temporary phi node in the first phase of vectorization.
4063   // This phi node will eventually be deleted.
4064   Builder.SetInsertPoint(
4065       cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
4066 
4067   // Create a phi node for the new recurrence. The current value will either be
4068   // the initial value inserted into a vector or loop-varying vector value.
4069   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4070   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4071 
4072   // Get the vectorized previous value of the last part UF - 1. It appears last
4073   // among all unrolled iterations, due to the order of their construction.
4074   Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
4075 
4076   // Set the insertion point after the previous value if it is an instruction.
4077   // Note that the previous value may have been constant-folded so it is not
4078   // guaranteed to be an instruction in the vector loop. Also, if the previous
4079   // value is a phi node, we should insert after all the phi nodes to avoid
4080   // breaking basic block verification.
4081   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
4082       isa<PHINode>(PreviousLastPart))
4083     Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
4084   else
4085     Builder.SetInsertPoint(
4086         &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
4087 
4088   // We will construct a vector for the recurrence by combining the values for
4089   // the current and previous iterations. This is the required shuffle mask.
4090   SmallVector<Constant *, 8> ShuffleMask(VF);
4091   ShuffleMask[0] = Builder.getInt32(VF - 1);
4092   for (unsigned I = 1; I < VF; ++I)
4093     ShuffleMask[I] = Builder.getInt32(I + VF - 1);
4094 
4095   // The vector from which to take the initial value for the current iteration
4096   // (actual or unrolled). Initially, this is the vector phi node.
4097   Value *Incoming = VecPhi;
4098 
4099   // Shuffle the current and previous vector and update the vector parts.
4100   for (unsigned Part = 0; Part < UF; ++Part) {
4101     Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
4102     Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
4103     auto *Shuffle =
4104         VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
4105                                              ConstantVector::get(ShuffleMask))
4106                : Incoming;
4107     PhiPart->replaceAllUsesWith(Shuffle);
4108     cast<Instruction>(PhiPart)->eraseFromParent();
4109     VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
4110     Incoming = PreviousPart;
4111   }
4112 
4113   // Fix the latch value of the new recurrence in the vector loop.
4114   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4115 
4116   // Extract the last vector element in the middle block. This will be the
4117   // initial value for the recurrence when jumping to the scalar loop.
4118   auto *ExtractForScalar = Incoming;
4119   if (VF > 1) {
4120     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4121     ExtractForScalar = Builder.CreateExtractElement(
4122         ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
4123   }
4124   // Extract the second last element in the middle block if the
4125   // Phi is used outside the loop. We need to extract the phi itself
4126   // and not the last element (the phi update in the current iteration). This
4127   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4128   // when the scalar loop is not run at all.
4129   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4130   if (VF > 1)
4131     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4132         Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
4133   // When loop is unrolled without vectorizing, initialize
4134   // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
4135   // `Incoming`. This is analogous to the vectorized case above: extracting the
4136   // second last element when VF > 1.
4137   else if (UF > 1)
4138     ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
4139 
4140   // Fix the initial value of the original recurrence in the scalar loop.
4141   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4142   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4143   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4144     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4145     Start->addIncoming(Incoming, BB);
4146   }
4147 
4148   Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
4149   Phi->setName("scalar.recur");
4150 
4151   // Finally, fix users of the recurrence outside the loop. The users will need
4152   // either the last value of the scalar recurrence or the last value of the
4153   // vector recurrence we extracted in the middle block. Since the loop is in
4154   // LCSSA form, we just need to find the phi node for the original scalar
4155   // recurrence in the exit block, and then add an edge for the middle block.
4156   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4157     if (LCSSAPhi.getIncomingValue(0) == Phi) {
4158       LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4159       break;
4160     }
4161   }
4162 }
4163 
4164 void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
4165   Constant *Zero = Builder.getInt32(0);
4166 
4167   // Get it's reduction variable descriptor.
4168   assert(Legal->isReductionVariable(Phi) &&
4169          "Unable to find the reduction variable");
4170   RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
4171 
4172   RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
4173   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4174   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4175   RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
4176     RdxDesc.getMinMaxRecurrenceKind();
4177   setDebugLocFromInst(Builder, ReductionStartValue);
4178 
4179   // We need to generate a reduction vector from the incoming scalar.
4180   // To do so, we need to generate the 'identity' vector and override
4181   // one of the elements with the incoming scalar reduction. We need
4182   // to do it in the vector-loop preheader.
4183   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4184 
4185   // This is the vector-clone of the value that leaves the loop.
4186   Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
4187 
4188   // Find the reduction identity variable. Zero for addition, or, xor,
4189   // one for multiplication, -1 for And.
4190   Value *Identity;
4191   Value *VectorStart;
4192   if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
4193       RK == RecurrenceDescriptor::RK_FloatMinMax) {
4194     // MinMax reduction have the start value as their identify.
4195     if (VF == 1) {
4196       VectorStart = Identity = ReductionStartValue;
4197     } else {
4198       VectorStart = Identity =
4199         Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
4200     }
4201   } else {
4202     // Handle other reduction kinds:
4203     Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
4204         RK, VecTy->getScalarType());
4205     if (VF == 1) {
4206       Identity = Iden;
4207       // This vector is the Identity vector where the first element is the
4208       // incoming scalar reduction.
4209       VectorStart = ReductionStartValue;
4210     } else {
4211       Identity = ConstantVector::getSplat(VF, Iden);
4212 
4213       // This vector is the Identity vector where the first element is the
4214       // incoming scalar reduction.
4215       VectorStart =
4216         Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
4217     }
4218   }
4219 
4220   // Fix the vector-loop phi.
4221 
4222   // Reductions do not have to start at zero. They can start with
4223   // any loop invariant values.
4224   BasicBlock *Latch = OrigLoop->getLoopLatch();
4225   Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
4226   for (unsigned Part = 0; Part < UF; ++Part) {
4227     Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
4228     Value *Val = getOrCreateVectorValue(LoopVal, Part);
4229     // Make sure to add the reduction stat value only to the
4230     // first unroll part.
4231     Value *StartVal = (Part == 0) ? VectorStart : Identity;
4232     cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
4233     cast<PHINode>(VecRdxPhi)
4234       ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4235   }
4236 
4237   // Before each round, move the insertion point right between
4238   // the PHIs and the values we are going to write.
4239   // This allows us to write both PHINodes and the extractelement
4240   // instructions.
4241   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4242 
4243   setDebugLocFromInst(Builder, LoopExitInst);
4244 
4245   // If the vector reduction can be performed in a smaller type, we truncate
4246   // then extend the loop exit value to enable InstCombine to evaluate the
4247   // entire expression in the smaller type.
4248   if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
4249     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4250     Builder.SetInsertPoint(
4251         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4252     VectorParts RdxParts(UF);
4253     for (unsigned Part = 0; Part < UF; ++Part) {
4254       RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4255       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4256       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4257                                         : Builder.CreateZExt(Trunc, VecTy);
4258       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4259            UI != RdxParts[Part]->user_end();)
4260         if (*UI != Trunc) {
4261           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4262           RdxParts[Part] = Extnd;
4263         } else {
4264           ++UI;
4265         }
4266     }
4267     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4268     for (unsigned Part = 0; Part < UF; ++Part) {
4269       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4270       VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
4271     }
4272   }
4273 
4274   // Reduce all of the unrolled parts into a single vector.
4275   Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
4276   unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
4277   setDebugLocFromInst(Builder, ReducedPartRdx);
4278   for (unsigned Part = 1; Part < UF; ++Part) {
4279     Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4280     if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4281       // Floating point operations had to be 'fast' to enable the reduction.
4282       ReducedPartRdx = addFastMathFlag(
4283           Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
4284                               ReducedPartRdx, "bin.rdx"));
4285     else
4286       ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
4287           Builder, MinMaxKind, ReducedPartRdx, RdxPart);
4288   }
4289 
4290   if (VF > 1) {
4291     bool NoNaN = Legal->hasFunNoNaNAttr();
4292     ReducedPartRdx =
4293         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
4294     // If the reduction can be performed in a smaller type, we need to extend
4295     // the reduction to the wider type before we branch to the original loop.
4296     if (Phi->getType() != RdxDesc.getRecurrenceType())
4297       ReducedPartRdx =
4298         RdxDesc.isSigned()
4299         ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
4300         : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
4301   }
4302 
4303   // Create a phi node that merges control-flow from the backedge-taken check
4304   // block and the middle block.
4305   PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
4306                                         LoopScalarPreHeader->getTerminator());
4307   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4308     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4309   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4310 
4311   // Now, we need to fix the users of the reduction variable
4312   // inside and outside of the scalar remainder loop.
4313   // We know that the loop is in LCSSA form. We need to update the
4314   // PHI nodes in the exit blocks.
4315   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4316     // All PHINodes need to have a single entry edge, or two if
4317     // we already fixed them.
4318     assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
4319 
4320     // We found a reduction value exit-PHI. Update it with the
4321     // incoming bypass edge.
4322     if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
4323       LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4324   } // end of the LCSSA phi scan.
4325 
4326     // Fix the scalar loop reduction variable with the incoming reduction sum
4327     // from the vector body and from the backedge value.
4328   int IncomingEdgeBlockIdx =
4329     Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4330   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4331   // Pick the other block.
4332   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4333   Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4334   Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4335 }
4336 
4337 void InnerLoopVectorizer::fixLCSSAPHIs() {
4338   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4339     if (LCSSAPhi.getNumIncomingValues() == 1) {
4340       assert(OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) &&
4341              "Incoming value isn't loop invariant");
4342       LCSSAPhi.addIncoming(LCSSAPhi.getIncomingValue(0), LoopMiddleBlock);
4343     }
4344   }
4345 }
4346 
4347 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4348   // The basic block and loop containing the predicated instruction.
4349   auto *PredBB = PredInst->getParent();
4350   auto *VectorLoop = LI->getLoopFor(PredBB);
4351 
4352   // Initialize a worklist with the operands of the predicated instruction.
4353   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4354 
4355   // Holds instructions that we need to analyze again. An instruction may be
4356   // reanalyzed if we don't yet know if we can sink it or not.
4357   SmallVector<Instruction *, 8> InstsToReanalyze;
4358 
4359   // Returns true if a given use occurs in the predicated block. Phi nodes use
4360   // their operands in their corresponding predecessor blocks.
4361   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4362     auto *I = cast<Instruction>(U.getUser());
4363     BasicBlock *BB = I->getParent();
4364     if (auto *Phi = dyn_cast<PHINode>(I))
4365       BB = Phi->getIncomingBlock(
4366           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4367     return BB == PredBB;
4368   };
4369 
4370   // Iteratively sink the scalarized operands of the predicated instruction
4371   // into the block we created for it. When an instruction is sunk, it's
4372   // operands are then added to the worklist. The algorithm ends after one pass
4373   // through the worklist doesn't sink a single instruction.
4374   bool Changed;
4375   do {
4376     // Add the instructions that need to be reanalyzed to the worklist, and
4377     // reset the changed indicator.
4378     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4379     InstsToReanalyze.clear();
4380     Changed = false;
4381 
4382     while (!Worklist.empty()) {
4383       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4384 
4385       // We can't sink an instruction if it is a phi node, is already in the
4386       // predicated block, is not in the loop, or may have side effects.
4387       if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4388           !VectorLoop->contains(I) || I->mayHaveSideEffects())
4389         continue;
4390 
4391       // It's legal to sink the instruction if all its uses occur in the
4392       // predicated block. Otherwise, there's nothing to do yet, and we may
4393       // need to reanalyze the instruction.
4394       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4395         InstsToReanalyze.push_back(I);
4396         continue;
4397       }
4398 
4399       // Move the instruction to the beginning of the predicated block, and add
4400       // it's operands to the worklist.
4401       I->moveBefore(&*PredBB->getFirstInsertionPt());
4402       Worklist.insert(I->op_begin(), I->op_end());
4403 
4404       // The sinking may have enabled other instructions to be sunk, so we will
4405       // need to iterate.
4406       Changed = true;
4407     }
4408   } while (Changed);
4409 }
4410 
4411 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
4412                                               unsigned VF) {
4413   assert(PN->getParent() == OrigLoop->getHeader() &&
4414          "Non-header phis should have been handled elsewhere");
4415 
4416   PHINode *P = cast<PHINode>(PN);
4417   // In order to support recurrences we need to be able to vectorize Phi nodes.
4418   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4419   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4420   // this value when we vectorize all of the instructions that use the PHI.
4421   if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4422     for (unsigned Part = 0; Part < UF; ++Part) {
4423       // This is phase one of vectorizing PHIs.
4424       Type *VecTy =
4425           (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4426       Value *EntryPart = PHINode::Create(
4427           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4428       VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
4429     }
4430     return;
4431   }
4432 
4433   setDebugLocFromInst(Builder, P);
4434 
4435   // This PHINode must be an induction variable.
4436   // Make sure that we know about it.
4437   assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
4438 
4439   InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4440   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4441 
4442   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4443   // which can be found from the original scalar operations.
4444   switch (II.getKind()) {
4445   case InductionDescriptor::IK_NoInduction:
4446     llvm_unreachable("Unknown induction");
4447   case InductionDescriptor::IK_IntInduction:
4448   case InductionDescriptor::IK_FpInduction:
4449     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4450   case InductionDescriptor::IK_PtrInduction: {
4451     // Handle the pointer induction variable case.
4452     assert(P->getType()->isPointerTy() && "Unexpected type.");
4453     // This is the normalized GEP that starts counting at zero.
4454     Value *PtrInd = Induction;
4455     PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4456     // Determine the number of scalars we need to generate for each unroll
4457     // iteration. If the instruction is uniform, we only need to generate the
4458     // first lane. Otherwise, we generate all VF values.
4459     unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
4460     // These are the scalar results. Notice that we don't generate vector GEPs
4461     // because scalar GEPs result in better code.
4462     for (unsigned Part = 0; Part < UF; ++Part) {
4463       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4464         Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
4465         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4466         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4467         SclrGep->setName("next.gep");
4468         VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
4469       }
4470     }
4471     return;
4472   }
4473   }
4474 }
4475 
4476 /// A helper function for checking whether an integer division-related
4477 /// instruction may divide by zero (in which case it must be predicated if
4478 /// executed conditionally in the scalar code).
4479 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4480 /// Non-zero divisors that are non compile-time constants will not be
4481 /// converted into multiplication, so we will still end up scalarizing
4482 /// the division, but can do so w/o predication.
4483 static bool mayDivideByZero(Instruction &I) {
4484   assert((I.getOpcode() == Instruction::UDiv ||
4485           I.getOpcode() == Instruction::SDiv ||
4486           I.getOpcode() == Instruction::URem ||
4487           I.getOpcode() == Instruction::SRem) &&
4488          "Unexpected instruction");
4489   Value *Divisor = I.getOperand(1);
4490   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4491   return !CInt || CInt->isZero();
4492 }
4493 
4494 void InnerLoopVectorizer::widenInstruction(Instruction &I) {
4495   switch (I.getOpcode()) {
4496   case Instruction::Br:
4497   case Instruction::PHI:
4498     llvm_unreachable("This instruction is handled by a different recipe.");
4499   case Instruction::GetElementPtr: {
4500     // Construct a vector GEP by widening the operands of the scalar GEP as
4501     // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4502     // results in a vector of pointers when at least one operand of the GEP
4503     // is vector-typed. Thus, to keep the representation compact, we only use
4504     // vector-typed operands for loop-varying values.
4505     auto *GEP = cast<GetElementPtrInst>(&I);
4506 
4507     if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
4508       // If we are vectorizing, but the GEP has only loop-invariant operands,
4509       // the GEP we build (by only using vector-typed operands for
4510       // loop-varying values) would be a scalar pointer. Thus, to ensure we
4511       // produce a vector of pointers, we need to either arbitrarily pick an
4512       // operand to broadcast, or broadcast a clone of the original GEP.
4513       // Here, we broadcast a clone of the original.
4514       //
4515       // TODO: If at some point we decide to scalarize instructions having
4516       //       loop-invariant operands, this special case will no longer be
4517       //       required. We would add the scalarization decision to
4518       //       collectLoopScalars() and teach getVectorValue() to broadcast
4519       //       the lane-zero scalar value.
4520       auto *Clone = Builder.Insert(GEP->clone());
4521       for (unsigned Part = 0; Part < UF; ++Part) {
4522         Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4523         VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
4524         addMetadata(EntryPart, GEP);
4525       }
4526     } else {
4527       // If the GEP has at least one loop-varying operand, we are sure to
4528       // produce a vector of pointers. But if we are only unrolling, we want
4529       // to produce a scalar GEP for each unroll part. Thus, the GEP we
4530       // produce with the code below will be scalar (if VF == 1) or vector
4531       // (otherwise). Note that for the unroll-only case, we still maintain
4532       // values in the vector mapping with initVector, as we do for other
4533       // instructions.
4534       for (unsigned Part = 0; Part < UF; ++Part) {
4535         // The pointer operand of the new GEP. If it's loop-invariant, we
4536         // won't broadcast it.
4537         auto *Ptr =
4538             OrigLoop->isLoopInvariant(GEP->getPointerOperand())
4539                 ? GEP->getPointerOperand()
4540                 : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
4541 
4542         // Collect all the indices for the new GEP. If any index is
4543         // loop-invariant, we won't broadcast it.
4544         SmallVector<Value *, 4> Indices;
4545         for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
4546           if (OrigLoop->isLoopInvariant(U.get()))
4547             Indices.push_back(U.get());
4548           else
4549             Indices.push_back(getOrCreateVectorValue(U.get(), Part));
4550         }
4551 
4552         // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4553         // but it should be a vector, otherwise.
4554         auto *NewGEP = GEP->isInBounds()
4555                            ? Builder.CreateInBoundsGEP(Ptr, Indices)
4556                            : Builder.CreateGEP(Ptr, Indices);
4557         assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
4558                "NewGEP is not a pointer vector");
4559         VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
4560         addMetadata(NewGEP, GEP);
4561       }
4562     }
4563 
4564     break;
4565   }
4566   case Instruction::UDiv:
4567   case Instruction::SDiv:
4568   case Instruction::SRem:
4569   case Instruction::URem:
4570   case Instruction::Add:
4571   case Instruction::FAdd:
4572   case Instruction::Sub:
4573   case Instruction::FSub:
4574   case Instruction::Mul:
4575   case Instruction::FMul:
4576   case Instruction::FDiv:
4577   case Instruction::FRem:
4578   case Instruction::Shl:
4579   case Instruction::LShr:
4580   case Instruction::AShr:
4581   case Instruction::And:
4582   case Instruction::Or:
4583   case Instruction::Xor: {
4584     // Just widen binops.
4585     auto *BinOp = cast<BinaryOperator>(&I);
4586     setDebugLocFromInst(Builder, BinOp);
4587 
4588     for (unsigned Part = 0; Part < UF; ++Part) {
4589       Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
4590       Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
4591       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
4592 
4593       if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4594         VecOp->copyIRFlags(BinOp);
4595 
4596       // Use this vector value for all users of the original instruction.
4597       VectorLoopValueMap.setVectorValue(&I, Part, V);
4598       addMetadata(V, BinOp);
4599     }
4600 
4601     break;
4602   }
4603   case Instruction::Select: {
4604     // Widen selects.
4605     // If the selector is loop invariant we can create a select
4606     // instruction with a scalar condition. Otherwise, use vector-select.
4607     auto *SE = PSE.getSE();
4608     bool InvariantCond =
4609         SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
4610     setDebugLocFromInst(Builder, &I);
4611 
4612     // The condition can be loop invariant  but still defined inside the
4613     // loop. This means that we can't just use the original 'cond' value.
4614     // We have to take the 'vectorized' value and pick the first lane.
4615     // Instcombine will make this a no-op.
4616 
4617     auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
4618 
4619     for (unsigned Part = 0; Part < UF; ++Part) {
4620       Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
4621       Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
4622       Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
4623       Value *Sel =
4624           Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
4625       VectorLoopValueMap.setVectorValue(&I, Part, Sel);
4626       addMetadata(Sel, &I);
4627     }
4628 
4629     break;
4630   }
4631 
4632   case Instruction::ICmp:
4633   case Instruction::FCmp: {
4634     // Widen compares. Generate vector compares.
4635     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4636     auto *Cmp = dyn_cast<CmpInst>(&I);
4637     setDebugLocFromInst(Builder, Cmp);
4638     for (unsigned Part = 0; Part < UF; ++Part) {
4639       Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
4640       Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
4641       Value *C = nullptr;
4642       if (FCmp) {
4643         // Propagate fast math flags.
4644         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4645         Builder.setFastMathFlags(Cmp->getFastMathFlags());
4646         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4647       } else {
4648         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4649       }
4650       VectorLoopValueMap.setVectorValue(&I, Part, C);
4651       addMetadata(C, &I);
4652     }
4653 
4654     break;
4655   }
4656 
4657   case Instruction::ZExt:
4658   case Instruction::SExt:
4659   case Instruction::FPToUI:
4660   case Instruction::FPToSI:
4661   case Instruction::FPExt:
4662   case Instruction::PtrToInt:
4663   case Instruction::IntToPtr:
4664   case Instruction::SIToFP:
4665   case Instruction::UIToFP:
4666   case Instruction::Trunc:
4667   case Instruction::FPTrunc:
4668   case Instruction::BitCast: {
4669     auto *CI = dyn_cast<CastInst>(&I);
4670     setDebugLocFromInst(Builder, CI);
4671 
4672     /// Vectorize casts.
4673     Type *DestTy =
4674         (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4675 
4676     for (unsigned Part = 0; Part < UF; ++Part) {
4677       Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
4678       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4679       VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4680       addMetadata(Cast, &I);
4681     }
4682     break;
4683   }
4684 
4685   case Instruction::Call: {
4686     // Ignore dbg intrinsics.
4687     if (isa<DbgInfoIntrinsic>(I))
4688       break;
4689     setDebugLocFromInst(Builder, &I);
4690 
4691     Module *M = I.getParent()->getParent()->getParent();
4692     auto *CI = cast<CallInst>(&I);
4693 
4694     StringRef FnName = CI->getCalledFunction()->getName();
4695     Function *F = CI->getCalledFunction();
4696     Type *RetTy = ToVectorTy(CI->getType(), VF);
4697     SmallVector<Type *, 4> Tys;
4698     for (Value *ArgOperand : CI->arg_operands())
4699       Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4700 
4701     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4702 
4703     // The flag shows whether we use Intrinsic or a usual Call for vectorized
4704     // version of the instruction.
4705     // Is it beneficial to perform intrinsic call compared to lib call?
4706     bool NeedToScalarize;
4707     unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4708     bool UseVectorIntrinsic =
4709         ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4710     assert((UseVectorIntrinsic || !NeedToScalarize) &&
4711            "Instruction should be scalarized elsewhere.");
4712 
4713     for (unsigned Part = 0; Part < UF; ++Part) {
4714       SmallVector<Value *, 4> Args;
4715       for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4716         Value *Arg = CI->getArgOperand(i);
4717         // Some intrinsics have a scalar argument - don't replace it with a
4718         // vector.
4719         if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
4720           Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
4721         Args.push_back(Arg);
4722       }
4723 
4724       Function *VectorF;
4725       if (UseVectorIntrinsic) {
4726         // Use vector version of the intrinsic.
4727         Type *TysForDecl[] = {CI->getType()};
4728         if (VF > 1)
4729           TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4730         VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4731       } else {
4732         // Use vector version of the library call.
4733         StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4734         assert(!VFnName.empty() && "Vector function name is empty.");
4735         VectorF = M->getFunction(VFnName);
4736         if (!VectorF) {
4737           // Generate a declaration
4738           FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4739           VectorF =
4740               Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4741           VectorF->copyAttributesFrom(F);
4742         }
4743       }
4744       assert(VectorF && "Can't create vector function.");
4745 
4746       SmallVector<OperandBundleDef, 1> OpBundles;
4747       CI->getOperandBundlesAsDefs(OpBundles);
4748       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4749 
4750       if (isa<FPMathOperator>(V))
4751         V->copyFastMathFlags(CI);
4752 
4753       VectorLoopValueMap.setVectorValue(&I, Part, V);
4754       addMetadata(V, &I);
4755     }
4756 
4757     break;
4758   }
4759 
4760   default:
4761     // This instruction is not vectorized by simple widening.
4762     DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
4763     llvm_unreachable("Unhandled instruction!");
4764   } // end of switch.
4765 }
4766 
4767 void InnerLoopVectorizer::updateAnalysis() {
4768   // Forget the original basic block.
4769   PSE.getSE()->forgetLoop(OrigLoop);
4770 
4771   // Update the dominator tree information.
4772   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
4773          "Entry does not dominate exit.");
4774 
4775   DT->addNewBlock(LoopMiddleBlock,
4776                   LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4777   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
4778   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
4779   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
4780   DEBUG(DT->verifyDomTree());
4781 }
4782 
4783 /// \brief Check whether it is safe to if-convert this phi node.
4784 ///
4785 /// Phi nodes with constant expressions that can trap are not safe to if
4786 /// convert.
4787 static bool canIfConvertPHINodes(BasicBlock *BB) {
4788   for (PHINode &Phi : BB->phis()) {
4789     for (Value *V : Phi.incoming_values())
4790       if (auto *C = dyn_cast<Constant>(V))
4791         if (C->canTrap())
4792           return false;
4793   }
4794   return true;
4795 }
4796 
4797 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
4798   if (!EnableIfConversion) {
4799     ORE->emit(createMissedAnalysis("IfConversionDisabled")
4800               << "if-conversion is disabled");
4801     return false;
4802   }
4803 
4804   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
4805 
4806   // A list of pointers that we can safely read and write to.
4807   SmallPtrSet<Value *, 8> SafePointes;
4808 
4809   // Collect safe addresses.
4810   for (BasicBlock *BB : TheLoop->blocks()) {
4811     if (blockNeedsPredication(BB))
4812       continue;
4813 
4814     for (Instruction &I : *BB)
4815       if (auto *Ptr = getPointerOperand(&I))
4816         SafePointes.insert(Ptr);
4817   }
4818 
4819   // Collect the blocks that need predication.
4820   BasicBlock *Header = TheLoop->getHeader();
4821   for (BasicBlock *BB : TheLoop->blocks()) {
4822     // We don't support switch statements inside loops.
4823     if (!isa<BranchInst>(BB->getTerminator())) {
4824       ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
4825                 << "loop contains a switch statement");
4826       return false;
4827     }
4828 
4829     // We must be able to predicate all blocks that need to be predicated.
4830     if (blockNeedsPredication(BB)) {
4831       if (!blockCanBePredicated(BB, SafePointes)) {
4832         ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
4833                   << "control flow cannot be substituted for a select");
4834         return false;
4835       }
4836     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4837       ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
4838                 << "control flow cannot be substituted for a select");
4839       return false;
4840     }
4841   }
4842 
4843   // We can if-convert this loop.
4844   return true;
4845 }
4846 
4847 bool LoopVectorizationLegality::canVectorize() {
4848   // Store the result and return it at the end instead of exiting early, in case
4849   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
4850   bool Result = true;
4851 
4852   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
4853   // We must have a loop in canonical form. Loops with indirectbr in them cannot
4854   // be canonicalized.
4855   if (!TheLoop->getLoopPreheader()) {
4856     DEBUG(dbgs() << "LV: Loop doesn't have a legal pre-header.\n");
4857     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4858               << "loop control flow is not understood by vectorizer");
4859     if (DoExtraAnalysis)
4860       Result = false;
4861     else
4862       return false;
4863   }
4864 
4865   // FIXME: The code is currently dead, since the loop gets sent to
4866   // LoopVectorizationLegality is already an innermost loop.
4867   //
4868   // We can only vectorize innermost loops.
4869   if (!TheLoop->empty()) {
4870     ORE->emit(createMissedAnalysis("NotInnermostLoop")
4871               << "loop is not the innermost loop");
4872     if (DoExtraAnalysis)
4873       Result = false;
4874     else
4875       return false;
4876   }
4877 
4878   // We must have a single backedge.
4879   if (TheLoop->getNumBackEdges() != 1) {
4880     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4881               << "loop control flow is not understood by vectorizer");
4882     if (DoExtraAnalysis)
4883       Result = false;
4884     else
4885       return false;
4886   }
4887 
4888   // We must have a single exiting block.
4889   if (!TheLoop->getExitingBlock()) {
4890     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4891               << "loop control flow is not understood by vectorizer");
4892     if (DoExtraAnalysis)
4893       Result = false;
4894     else
4895       return false;
4896   }
4897 
4898   // We only handle bottom-tested loops, i.e. loop in which the condition is
4899   // checked at the end of each iteration. With that we can assume that all
4900   // instructions in the loop are executed the same number of times.
4901   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
4902     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4903               << "loop control flow is not understood by vectorizer");
4904     if (DoExtraAnalysis)
4905       Result = false;
4906     else
4907       return false;
4908   }
4909 
4910   // We need to have a loop header.
4911   DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
4912                << '\n');
4913 
4914   // Check if we can if-convert non-single-bb loops.
4915   unsigned NumBlocks = TheLoop->getNumBlocks();
4916   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
4917     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
4918     if (DoExtraAnalysis)
4919       Result = false;
4920     else
4921       return false;
4922   }
4923 
4924   // Check if we can vectorize the instructions and CFG in this loop.
4925   if (!canVectorizeInstrs()) {
4926     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
4927     if (DoExtraAnalysis)
4928       Result = false;
4929     else
4930       return false;
4931   }
4932 
4933   // Go over each instruction and look at memory deps.
4934   if (!canVectorizeMemory()) {
4935     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
4936     if (DoExtraAnalysis)
4937       Result = false;
4938     else
4939       return false;
4940   }
4941 
4942   DEBUG(dbgs() << "LV: We can vectorize this loop"
4943                << (LAI->getRuntimePointerChecking()->Need
4944                        ? " (with a runtime bound check)"
4945                        : "")
4946                << "!\n");
4947 
4948   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4949 
4950   // If an override option has been passed in for interleaved accesses, use it.
4951   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4952     UseInterleaved = EnableInterleavedMemAccesses;
4953 
4954   // Analyze interleaved memory accesses.
4955   if (UseInterleaved)
4956     InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
4957 
4958   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
4959   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
4960     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
4961 
4962   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
4963     ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
4964               << "Too many SCEV assumptions need to be made and checked "
4965               << "at runtime");
4966     DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
4967     if (DoExtraAnalysis)
4968       Result = false;
4969     else
4970       return false;
4971   }
4972 
4973   // Okay! We've done all the tests. If any have failed, return false. Otherwise
4974   // we can vectorize, and at this point we don't have any other mem analysis
4975   // which may limit our maximum vectorization factor, so just return true with
4976   // no restrictions.
4977   return Result;
4978 }
4979 
4980 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4981   if (Ty->isPointerTy())
4982     return DL.getIntPtrType(Ty);
4983 
4984   // It is possible that char's or short's overflow when we ask for the loop's
4985   // trip count, work around this by changing the type size.
4986   if (Ty->getScalarSizeInBits() < 32)
4987     return Type::getInt32Ty(Ty->getContext());
4988 
4989   return Ty;
4990 }
4991 
4992 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4993   Ty0 = convertPointerToIntegerType(DL, Ty0);
4994   Ty1 = convertPointerToIntegerType(DL, Ty1);
4995   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4996     return Ty0;
4997   return Ty1;
4998 }
4999 
5000 /// \brief Check that the instruction has outside loop users and is not an
5001 /// identified reduction variable.
5002 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
5003                                SmallPtrSetImpl<Value *> &AllowedExit) {
5004   // Reduction and Induction instructions are allowed to have exit users. All
5005   // other instructions must not have external users.
5006   if (!AllowedExit.count(Inst))
5007     // Check that all of the users of the loop are inside the BB.
5008     for (User *U : Inst->users()) {
5009       Instruction *UI = cast<Instruction>(U);
5010       // This user may be a reduction exit value.
5011       if (!TheLoop->contains(UI)) {
5012         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
5013         return true;
5014       }
5015     }
5016   return false;
5017 }
5018 
5019 void LoopVectorizationLegality::addInductionPhi(
5020     PHINode *Phi, const InductionDescriptor &ID,
5021     SmallPtrSetImpl<Value *> &AllowedExit) {
5022   Inductions[Phi] = ID;
5023 
5024   // In case this induction also comes with casts that we know we can ignore
5025   // in the vectorized loop body, record them here. All casts could be recorded
5026   // here for ignoring, but suffices to record only the first (as it is the
5027   // only one that may bw used outside the cast sequence).
5028   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
5029   if (!Casts.empty())
5030     InductionCastsToIgnore.insert(*Casts.begin());
5031 
5032   Type *PhiTy = Phi->getType();
5033   const DataLayout &DL = Phi->getModule()->getDataLayout();
5034 
5035   // Get the widest type.
5036   if (!PhiTy->isFloatingPointTy()) {
5037     if (!WidestIndTy)
5038       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
5039     else
5040       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
5041   }
5042 
5043   // Int inductions are special because we only allow one IV.
5044   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
5045       ID.getConstIntStepValue() &&
5046       ID.getConstIntStepValue()->isOne() &&
5047       isa<Constant>(ID.getStartValue()) &&
5048       cast<Constant>(ID.getStartValue())->isNullValue()) {
5049 
5050     // Use the phi node with the widest type as induction. Use the last
5051     // one if there are multiple (no good reason for doing this other
5052     // than it is expedient). We've checked that it begins at zero and
5053     // steps by one, so this is a canonical induction variable.
5054     if (!PrimaryInduction || PhiTy == WidestIndTy)
5055       PrimaryInduction = Phi;
5056   }
5057 
5058   // Both the PHI node itself, and the "post-increment" value feeding
5059   // back into the PHI node may have external users.
5060   // We can allow those uses, except if the SCEVs we have for them rely
5061   // on predicates that only hold within the loop, since allowing the exit
5062   // currently means re-using this SCEV outside the loop.
5063   if (PSE.getUnionPredicate().isAlwaysTrue()) {
5064     AllowedExit.insert(Phi);
5065     AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
5066   }
5067 
5068   DEBUG(dbgs() << "LV: Found an induction variable.\n");
5069 }
5070 
5071 bool LoopVectorizationLegality::canVectorizeInstrs() {
5072   BasicBlock *Header = TheLoop->getHeader();
5073 
5074   // Look for the attribute signaling the absence of NaNs.
5075   Function &F = *Header->getParent();
5076   HasFunNoNaNAttr =
5077       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
5078 
5079   // For each block in the loop.
5080   for (BasicBlock *BB : TheLoop->blocks()) {
5081     // Scan the instructions in the block and look for hazards.
5082     for (Instruction &I : *BB) {
5083       if (auto *Phi = dyn_cast<PHINode>(&I)) {
5084         Type *PhiTy = Phi->getType();
5085         // Check that this PHI type is allowed.
5086         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
5087             !PhiTy->isPointerTy()) {
5088           ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5089                     << "loop control flow is not understood by vectorizer");
5090           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
5091           return false;
5092         }
5093 
5094         // If this PHINode is not in the header block, then we know that we
5095         // can convert it to select during if-conversion. No need to check if
5096         // the PHIs in this block are induction or reduction variables.
5097         if (BB != Header) {
5098           // Check that this instruction has no outside users or is an
5099           // identified reduction value with an outside user.
5100           if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
5101             continue;
5102           ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi)
5103                     << "value could not be identified as "
5104                        "an induction or reduction variable");
5105           return false;
5106         }
5107 
5108         // We only allow if-converted PHIs with exactly two incoming values.
5109         if (Phi->getNumIncomingValues() != 2) {
5110           ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5111                     << "control flow not understood by vectorizer");
5112           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
5113           return false;
5114         }
5115 
5116         RecurrenceDescriptor RedDes;
5117         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
5118                                                  DT)) {
5119           if (RedDes.hasUnsafeAlgebra())
5120             Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
5121           AllowedExit.insert(RedDes.getLoopExitInstr());
5122           Reductions[Phi] = RedDes;
5123           continue;
5124         }
5125 
5126         InductionDescriptor ID;
5127         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
5128           addInductionPhi(Phi, ID, AllowedExit);
5129           if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
5130             Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
5131           continue;
5132         }
5133 
5134         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
5135                                                          SinkAfter, DT)) {
5136           FirstOrderRecurrences.insert(Phi);
5137           continue;
5138         }
5139 
5140         // As a last resort, coerce the PHI to a AddRec expression
5141         // and re-try classifying it a an induction PHI.
5142         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
5143           addInductionPhi(Phi, ID, AllowedExit);
5144           continue;
5145         }
5146 
5147         ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
5148                   << "value that could not be identified as "
5149                      "reduction is used outside the loop");
5150         DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
5151         return false;
5152       } // end of PHI handling
5153 
5154       // We handle calls that:
5155       //   * Are debug info intrinsics.
5156       //   * Have a mapping to an IR intrinsic.
5157       //   * Have a vector version available.
5158       auto *CI = dyn_cast<CallInst>(&I);
5159       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
5160           !isa<DbgInfoIntrinsic>(CI) &&
5161           !(CI->getCalledFunction() && TLI &&
5162             TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
5163         ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
5164                   << "call instruction cannot be vectorized");
5165         DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
5166         return false;
5167       }
5168 
5169       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
5170       // second argument is the same (i.e. loop invariant)
5171       if (CI && hasVectorInstrinsicScalarOpd(
5172                     getVectorIntrinsicIDForCall(CI, TLI), 1)) {
5173         auto *SE = PSE.getSE();
5174         if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
5175           ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
5176                     << "intrinsic instruction cannot be vectorized");
5177           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
5178           return false;
5179         }
5180       }
5181 
5182       // Check that the instruction return type is vectorizable.
5183       // Also, we can't vectorize extractelement instructions.
5184       if ((!VectorType::isValidElementType(I.getType()) &&
5185            !I.getType()->isVoidTy()) ||
5186           isa<ExtractElementInst>(I)) {
5187         ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
5188                   << "instruction return type cannot be vectorized");
5189         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
5190         return false;
5191       }
5192 
5193       // Check that the stored type is vectorizable.
5194       if (auto *ST = dyn_cast<StoreInst>(&I)) {
5195         Type *T = ST->getValueOperand()->getType();
5196         if (!VectorType::isValidElementType(T)) {
5197           ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
5198                     << "store instruction cannot be vectorized");
5199           return false;
5200         }
5201 
5202         // FP instructions can allow unsafe algebra, thus vectorizable by
5203         // non-IEEE-754 compliant SIMD units.
5204         // This applies to floating-point math operations and calls, not memory
5205         // operations, shuffles, or casts, as they don't change precision or
5206         // semantics.
5207       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
5208                  !I.isFast()) {
5209         DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
5210         Hints->setPotentiallyUnsafe();
5211       }
5212 
5213       // Reduction instructions are allowed to have exit users.
5214       // All other instructions must not have external users.
5215       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
5216         ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
5217                   << "value cannot be used outside the loop");
5218         return false;
5219       }
5220     } // next instr.
5221   }
5222 
5223   if (!PrimaryInduction) {
5224     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
5225     if (Inductions.empty()) {
5226       ORE->emit(createMissedAnalysis("NoInductionVariable")
5227                 << "loop induction variable could not be identified");
5228       return false;
5229     }
5230   }
5231 
5232   // Now we know the widest induction type, check if our found induction
5233   // is the same size. If it's not, unset it here and InnerLoopVectorizer
5234   // will create another.
5235   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
5236     PrimaryInduction = nullptr;
5237 
5238   return true;
5239 }
5240 
5241 void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
5242   // We should not collect Scalars more than once per VF. Right now, this
5243   // function is called from collectUniformsAndScalars(), which already does
5244   // this check. Collecting Scalars for VF=1 does not make any sense.
5245   assert(VF >= 2 && !Scalars.count(VF) &&
5246          "This function should not be visited twice for the same VF");
5247 
5248   SmallSetVector<Instruction *, 8> Worklist;
5249 
5250   // These sets are used to seed the analysis with pointers used by memory
5251   // accesses that will remain scalar.
5252   SmallSetVector<Instruction *, 8> ScalarPtrs;
5253   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5254 
5255   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5256   // The pointer operands of loads and stores will be scalar as long as the
5257   // memory access is not a gather or scatter operation. The value operand of a
5258   // store will remain scalar if the store is scalarized.
5259   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5260     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5261     assert(WideningDecision != CM_Unknown &&
5262            "Widening decision should be ready at this moment");
5263     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5264       if (Ptr == Store->getValueOperand())
5265         return WideningDecision == CM_Scalarize;
5266     assert(Ptr == getPointerOperand(MemAccess) &&
5267            "Ptr is neither a value or pointer operand");
5268     return WideningDecision != CM_GatherScatter;
5269   };
5270 
5271   // A helper that returns true if the given value is a bitcast or
5272   // getelementptr instruction contained in the loop.
5273   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5274     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5275             isa<GetElementPtrInst>(V)) &&
5276            !TheLoop->isLoopInvariant(V);
5277   };
5278 
5279   // A helper that evaluates a memory access's use of a pointer. If the use
5280   // will be a scalar use, and the pointer is only used by memory accesses, we
5281   // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
5282   // PossibleNonScalarPtrs.
5283   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5284     // We only care about bitcast and getelementptr instructions contained in
5285     // the loop.
5286     if (!isLoopVaryingBitCastOrGEP(Ptr))
5287       return;
5288 
5289     // If the pointer has already been identified as scalar (e.g., if it was
5290     // also identified as uniform), there's nothing to do.
5291     auto *I = cast<Instruction>(Ptr);
5292     if (Worklist.count(I))
5293       return;
5294 
5295     // If the use of the pointer will be a scalar use, and all users of the
5296     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5297     // place the pointer in PossibleNonScalarPtrs.
5298     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5299           return isa<LoadInst>(U) || isa<StoreInst>(U);
5300         }))
5301       ScalarPtrs.insert(I);
5302     else
5303       PossibleNonScalarPtrs.insert(I);
5304   };
5305 
5306   // We seed the scalars analysis with three classes of instructions: (1)
5307   // instructions marked uniform-after-vectorization, (2) bitcast and
5308   // getelementptr instructions used by memory accesses requiring a scalar use,
5309   // and (3) pointer induction variables and their update instructions (we
5310   // currently only scalarize these).
5311   //
5312   // (1) Add to the worklist all instructions that have been identified as
5313   // uniform-after-vectorization.
5314   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5315 
5316   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5317   // memory accesses requiring a scalar use. The pointer operands of loads and
5318   // stores will be scalar as long as the memory accesses is not a gather or
5319   // scatter operation. The value operand of a store will remain scalar if the
5320   // store is scalarized.
5321   for (auto *BB : TheLoop->blocks())
5322     for (auto &I : *BB) {
5323       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5324         evaluatePtrUse(Load, Load->getPointerOperand());
5325       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5326         evaluatePtrUse(Store, Store->getPointerOperand());
5327         evaluatePtrUse(Store, Store->getValueOperand());
5328       }
5329     }
5330   for (auto *I : ScalarPtrs)
5331     if (!PossibleNonScalarPtrs.count(I)) {
5332       DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5333       Worklist.insert(I);
5334     }
5335 
5336   // (3) Add to the worklist all pointer induction variables and their update
5337   // instructions.
5338   //
5339   // TODO: Once we are able to vectorize pointer induction variables we should
5340   //       no longer insert them into the worklist here.
5341   auto *Latch = TheLoop->getLoopLatch();
5342   for (auto &Induction : *Legal->getInductionVars()) {
5343     auto *Ind = Induction.first;
5344     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5345     if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
5346       continue;
5347     Worklist.insert(Ind);
5348     Worklist.insert(IndUpdate);
5349     DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5350     DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n");
5351   }
5352 
5353   // Insert the forced scalars.
5354   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5355   // induction variable when the PHI user is scalarized.
5356   if (ForcedScalars.count(VF))
5357     for (auto *I : ForcedScalars.find(VF)->second)
5358       Worklist.insert(I);
5359 
5360   // Expand the worklist by looking through any bitcasts and getelementptr
5361   // instructions we've already identified as scalar. This is similar to the
5362   // expansion step in collectLoopUniforms(); however, here we're only
5363   // expanding to include additional bitcasts and getelementptr instructions.
5364   unsigned Idx = 0;
5365   while (Idx != Worklist.size()) {
5366     Instruction *Dst = Worklist[Idx++];
5367     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5368       continue;
5369     auto *Src = cast<Instruction>(Dst->getOperand(0));
5370     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5371           auto *J = cast<Instruction>(U);
5372           return !TheLoop->contains(J) || Worklist.count(J) ||
5373                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5374                   isScalarUse(J, Src));
5375         })) {
5376       Worklist.insert(Src);
5377       DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5378     }
5379   }
5380 
5381   // An induction variable will remain scalar if all users of the induction
5382   // variable and induction variable update remain scalar.
5383   for (auto &Induction : *Legal->getInductionVars()) {
5384     auto *Ind = Induction.first;
5385     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5386 
5387     // We already considered pointer induction variables, so there's no reason
5388     // to look at their users again.
5389     //
5390     // TODO: Once we are able to vectorize pointer induction variables we
5391     //       should no longer skip over them here.
5392     if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
5393       continue;
5394 
5395     // Determine if all users of the induction variable are scalar after
5396     // vectorization.
5397     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5398       auto *I = cast<Instruction>(U);
5399       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5400     });
5401     if (!ScalarInd)
5402       continue;
5403 
5404     // Determine if all users of the induction variable update instruction are
5405     // scalar after vectorization.
5406     auto ScalarIndUpdate =
5407         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5408           auto *I = cast<Instruction>(U);
5409           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5410         });
5411     if (!ScalarIndUpdate)
5412       continue;
5413 
5414     // The induction variable and its update instruction will remain scalar.
5415     Worklist.insert(Ind);
5416     Worklist.insert(IndUpdate);
5417     DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5418     DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n");
5419   }
5420 
5421   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5422 }
5423 
5424 bool LoopVectorizationLegality::isScalarWithPredication(Instruction *I) {
5425   if (!blockNeedsPredication(I->getParent()))
5426     return false;
5427   switch(I->getOpcode()) {
5428   default:
5429     break;
5430   case Instruction::Store:
5431     return !isMaskRequired(I);
5432   case Instruction::UDiv:
5433   case Instruction::SDiv:
5434   case Instruction::SRem:
5435   case Instruction::URem:
5436     return mayDivideByZero(*I);
5437   }
5438   return false;
5439 }
5440 
5441 bool LoopVectorizationLegality::memoryInstructionCanBeWidened(Instruction *I,
5442                                                               unsigned VF) {
5443   // Get and ensure we have a valid memory instruction.
5444   LoadInst *LI = dyn_cast<LoadInst>(I);
5445   StoreInst *SI = dyn_cast<StoreInst>(I);
5446   assert((LI || SI) && "Invalid memory instruction");
5447 
5448   auto *Ptr = getPointerOperand(I);
5449 
5450   // In order to be widened, the pointer should be consecutive, first of all.
5451   if (!isConsecutivePtr(Ptr))
5452     return false;
5453 
5454   // If the instruction is a store located in a predicated block, it will be
5455   // scalarized.
5456   if (isScalarWithPredication(I))
5457     return false;
5458 
5459   // If the instruction's allocated size doesn't equal it's type size, it
5460   // requires padding and will be scalarized.
5461   auto &DL = I->getModule()->getDataLayout();
5462   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5463   if (hasIrregularType(ScalarTy, DL, VF))
5464     return false;
5465 
5466   return true;
5467 }
5468 
5469 void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
5470   // We should not collect Uniforms more than once per VF. Right now,
5471   // this function is called from collectUniformsAndScalars(), which
5472   // already does this check. Collecting Uniforms for VF=1 does not make any
5473   // sense.
5474 
5475   assert(VF >= 2 && !Uniforms.count(VF) &&
5476          "This function should not be visited twice for the same VF");
5477 
5478   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5479   // not analyze again.  Uniforms.count(VF) will return 1.
5480   Uniforms[VF].clear();
5481 
5482   // We now know that the loop is vectorizable!
5483   // Collect instructions inside the loop that will remain uniform after
5484   // vectorization.
5485 
5486   // Global values, params and instructions outside of current loop are out of
5487   // scope.
5488   auto isOutOfScope = [&](Value *V) -> bool {
5489     Instruction *I = dyn_cast<Instruction>(V);
5490     return (!I || !TheLoop->contains(I));
5491   };
5492 
5493   SetVector<Instruction *> Worklist;
5494   BasicBlock *Latch = TheLoop->getLoopLatch();
5495 
5496   // Start with the conditional branch. If the branch condition is an
5497   // instruction contained in the loop that is only used by the branch, it is
5498   // uniform.
5499   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5500   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
5501     Worklist.insert(Cmp);
5502     DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
5503   }
5504 
5505   // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
5506   // are pointers that are treated like consecutive pointers during
5507   // vectorization. The pointer operands of interleaved accesses are an
5508   // example.
5509   SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
5510 
5511   // Holds pointer operands of instructions that are possibly non-uniform.
5512   SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
5513 
5514   auto isUniformDecision = [&](Instruction *I, unsigned VF) {
5515     InstWidening WideningDecision = getWideningDecision(I, VF);
5516     assert(WideningDecision != CM_Unknown &&
5517            "Widening decision should be ready at this moment");
5518 
5519     return (WideningDecision == CM_Widen ||
5520             WideningDecision == CM_Widen_Reverse ||
5521             WideningDecision == CM_Interleave);
5522   };
5523   // Iterate over the instructions in the loop, and collect all
5524   // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
5525   // that a consecutive-like pointer operand will be scalarized, we collect it
5526   // in PossibleNonUniformPtrs instead. We use two sets here because a single
5527   // getelementptr instruction can be used by both vectorized and scalarized
5528   // memory instructions. For example, if a loop loads and stores from the same
5529   // location, but the store is conditional, the store will be scalarized, and
5530   // the getelementptr won't remain uniform.
5531   for (auto *BB : TheLoop->blocks())
5532     for (auto &I : *BB) {
5533       // If there's no pointer operand, there's nothing to do.
5534       auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I));
5535       if (!Ptr)
5536         continue;
5537 
5538       // True if all users of Ptr are memory accesses that have Ptr as their
5539       // pointer operand.
5540       auto UsersAreMemAccesses =
5541           llvm::all_of(Ptr->users(), [&](User *U) -> bool {
5542             return getPointerOperand(U) == Ptr;
5543           });
5544 
5545       // Ensure the memory instruction will not be scalarized or used by
5546       // gather/scatter, making its pointer operand non-uniform. If the pointer
5547       // operand is used by any instruction other than a memory access, we
5548       // conservatively assume the pointer operand may be non-uniform.
5549       if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5550         PossibleNonUniformPtrs.insert(Ptr);
5551 
5552       // If the memory instruction will be vectorized and its pointer operand
5553       // is consecutive-like, or interleaving - the pointer operand should
5554       // remain uniform.
5555       else
5556         ConsecutiveLikePtrs.insert(Ptr);
5557     }
5558 
5559   // Add to the Worklist all consecutive and consecutive-like pointers that
5560   // aren't also identified as possibly non-uniform.
5561   for (auto *V : ConsecutiveLikePtrs)
5562     if (!PossibleNonUniformPtrs.count(V)) {
5563       DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
5564       Worklist.insert(V);
5565     }
5566 
5567   // Expand Worklist in topological order: whenever a new instruction
5568   // is added , its users should be either already inside Worklist, or
5569   // out of scope. It ensures a uniform instruction will only be used
5570   // by uniform instructions or out of scope instructions.
5571   unsigned idx = 0;
5572   while (idx != Worklist.size()) {
5573     Instruction *I = Worklist[idx++];
5574 
5575     for (auto OV : I->operand_values()) {
5576       if (isOutOfScope(OV))
5577         continue;
5578       auto *OI = cast<Instruction>(OV);
5579       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5580             auto *J = cast<Instruction>(U);
5581             return !TheLoop->contains(J) || Worklist.count(J) ||
5582                    (OI == getPointerOperand(J) && isUniformDecision(J, VF));
5583           })) {
5584         Worklist.insert(OI);
5585         DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
5586       }
5587     }
5588   }
5589 
5590   // Returns true if Ptr is the pointer operand of a memory access instruction
5591   // I, and I is known to not require scalarization.
5592   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5593     return getPointerOperand(I) == Ptr && isUniformDecision(I, VF);
5594   };
5595 
5596   // For an instruction to be added into Worklist above, all its users inside
5597   // the loop should also be in Worklist. However, this condition cannot be
5598   // true for phi nodes that form a cyclic dependence. We must process phi
5599   // nodes separately. An induction variable will remain uniform if all users
5600   // of the induction variable and induction variable update remain uniform.
5601   // The code below handles both pointer and non-pointer induction variables.
5602   for (auto &Induction : *Legal->getInductionVars()) {
5603     auto *Ind = Induction.first;
5604     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5605 
5606     // Determine if all users of the induction variable are uniform after
5607     // vectorization.
5608     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5609       auto *I = cast<Instruction>(U);
5610       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5611              isVectorizedMemAccessUse(I, Ind);
5612     });
5613     if (!UniformInd)
5614       continue;
5615 
5616     // Determine if all users of the induction variable update instruction are
5617     // uniform after vectorization.
5618     auto UniformIndUpdate =
5619         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5620           auto *I = cast<Instruction>(U);
5621           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5622                  isVectorizedMemAccessUse(I, IndUpdate);
5623         });
5624     if (!UniformIndUpdate)
5625       continue;
5626 
5627     // The induction variable and its update instruction will remain uniform.
5628     Worklist.insert(Ind);
5629     Worklist.insert(IndUpdate);
5630     DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
5631     DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n");
5632   }
5633 
5634   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5635 }
5636 
5637 bool LoopVectorizationLegality::canVectorizeMemory() {
5638   LAI = &(*GetLAA)(*TheLoop);
5639   InterleaveInfo.setLAI(LAI);
5640   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
5641   if (LAR) {
5642     ORE->emit([&]() {
5643       return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
5644                                         "loop not vectorized: ", *LAR);
5645     });
5646   }
5647   if (!LAI->canVectorizeMemory())
5648     return false;
5649 
5650   if (LAI->hasStoreToLoopInvariantAddress()) {
5651     ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
5652               << "write to a loop invariant address could not be vectorized");
5653     DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
5654     return false;
5655   }
5656 
5657   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
5658   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
5659 
5660   return true;
5661 }
5662 
5663 bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
5664   Value *In0 = const_cast<Value *>(V);
5665   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5666   if (!PN)
5667     return false;
5668 
5669   return Inductions.count(PN);
5670 }
5671 
5672 bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) {
5673   auto *Inst = dyn_cast<Instruction>(V);
5674   return (Inst && InductionCastsToIgnore.count(Inst));
5675 }
5676 
5677 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5678   return isInductionPhi(V) || isCastedInductionVariable(V);
5679 }
5680 
5681 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
5682   return FirstOrderRecurrences.count(Phi);
5683 }
5684 
5685 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5686   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
5687 }
5688 
5689 bool LoopVectorizationLegality::blockCanBePredicated(
5690     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
5691   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
5692 
5693   for (Instruction &I : *BB) {
5694     // Check that we don't have a constant expression that can trap as operand.
5695     for (Value *Operand : I.operands()) {
5696       if (auto *C = dyn_cast<Constant>(Operand))
5697         if (C->canTrap())
5698           return false;
5699     }
5700     // We might be able to hoist the load.
5701     if (I.mayReadFromMemory()) {
5702       auto *LI = dyn_cast<LoadInst>(&I);
5703       if (!LI)
5704         return false;
5705       if (!SafePtrs.count(LI->getPointerOperand())) {
5706         if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) ||
5707             isLegalMaskedGather(LI->getType())) {
5708           MaskedOp.insert(LI);
5709           continue;
5710         }
5711         // !llvm.mem.parallel_loop_access implies if-conversion safety.
5712         if (IsAnnotatedParallel)
5713           continue;
5714         return false;
5715       }
5716     }
5717 
5718     if (I.mayWriteToMemory()) {
5719       auto *SI = dyn_cast<StoreInst>(&I);
5720       // We only support predication of stores in basic blocks with one
5721       // predecessor.
5722       if (!SI)
5723         return false;
5724 
5725       // Build a masked store if it is legal for the target.
5726       if (isLegalMaskedStore(SI->getValueOperand()->getType(),
5727                              SI->getPointerOperand()) ||
5728           isLegalMaskedScatter(SI->getValueOperand()->getType())) {
5729         MaskedOp.insert(SI);
5730         continue;
5731       }
5732 
5733       bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
5734       bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
5735 
5736       if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
5737           !isSinglePredecessor)
5738         return false;
5739     }
5740     if (I.mayThrow())
5741       return false;
5742   }
5743 
5744   return true;
5745 }
5746 
5747 void InterleavedAccessInfo::collectConstStrideAccesses(
5748     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
5749     const ValueToValueMap &Strides) {
5750   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
5751 
5752   // Since it's desired that the load/store instructions be maintained in
5753   // "program order" for the interleaved access analysis, we have to visit the
5754   // blocks in the loop in reverse postorder (i.e., in a topological order).
5755   // Such an ordering will ensure that any load/store that may be executed
5756   // before a second load/store will precede the second load/store in
5757   // AccessStrideInfo.
5758   LoopBlocksDFS DFS(TheLoop);
5759   DFS.perform(LI);
5760   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
5761     for (auto &I : *BB) {
5762       auto *LI = dyn_cast<LoadInst>(&I);
5763       auto *SI = dyn_cast<StoreInst>(&I);
5764       if (!LI && !SI)
5765         continue;
5766 
5767       Value *Ptr = getPointerOperand(&I);
5768       // We don't check wrapping here because we don't know yet if Ptr will be
5769       // part of a full group or a group with gaps. Checking wrapping for all
5770       // pointers (even those that end up in groups with no gaps) will be overly
5771       // conservative. For full groups, wrapping should be ok since if we would
5772       // wrap around the address space we would do a memory access at nullptr
5773       // even without the transformation. The wrapping checks are therefore
5774       // deferred until after we've formed the interleaved groups.
5775       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
5776                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
5777 
5778       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
5779       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
5780       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
5781 
5782       // An alignment of 0 means target ABI alignment.
5783       unsigned Align = getMemInstAlignment(&I);
5784       if (!Align)
5785         Align = DL.getABITypeAlignment(PtrTy->getElementType());
5786 
5787       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
5788     }
5789 }
5790 
5791 // Analyze interleaved accesses and collect them into interleaved load and
5792 // store groups.
5793 //
5794 // When generating code for an interleaved load group, we effectively hoist all
5795 // loads in the group to the location of the first load in program order. When
5796 // generating code for an interleaved store group, we sink all stores to the
5797 // location of the last store. This code motion can change the order of load
5798 // and store instructions and may break dependences.
5799 //
5800 // The code generation strategy mentioned above ensures that we won't violate
5801 // any write-after-read (WAR) dependences.
5802 //
5803 // E.g., for the WAR dependence:  a = A[i];      // (1)
5804 //                                A[i] = b;      // (2)
5805 //
5806 // The store group of (2) is always inserted at or below (2), and the load
5807 // group of (1) is always inserted at or above (1). Thus, the instructions will
5808 // never be reordered. All other dependences are checked to ensure the
5809 // correctness of the instruction reordering.
5810 //
5811 // The algorithm visits all memory accesses in the loop in bottom-up program
5812 // order. Program order is established by traversing the blocks in the loop in
5813 // reverse postorder when collecting the accesses.
5814 //
5815 // We visit the memory accesses in bottom-up order because it can simplify the
5816 // construction of store groups in the presence of write-after-write (WAW)
5817 // dependences.
5818 //
5819 // E.g., for the WAW dependence:  A[i] = a;      // (1)
5820 //                                A[i] = b;      // (2)
5821 //                                A[i + 1] = c;  // (3)
5822 //
5823 // We will first create a store group with (3) and (2). (1) can't be added to
5824 // this group because it and (2) are dependent. However, (1) can be grouped
5825 // with other accesses that may precede it in program order. Note that a
5826 // bottom-up order does not imply that WAW dependences should not be checked.
5827 void InterleavedAccessInfo::analyzeInterleaving(
5828     const ValueToValueMap &Strides) {
5829   DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
5830 
5831   // Holds all accesses with a constant stride.
5832   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
5833   collectConstStrideAccesses(AccessStrideInfo, Strides);
5834 
5835   if (AccessStrideInfo.empty())
5836     return;
5837 
5838   // Collect the dependences in the loop.
5839   collectDependences();
5840 
5841   // Holds all interleaved store groups temporarily.
5842   SmallSetVector<InterleaveGroup *, 4> StoreGroups;
5843   // Holds all interleaved load groups temporarily.
5844   SmallSetVector<InterleaveGroup *, 4> LoadGroups;
5845 
5846   // Search in bottom-up program order for pairs of accesses (A and B) that can
5847   // form interleaved load or store groups. In the algorithm below, access A
5848   // precedes access B in program order. We initialize a group for B in the
5849   // outer loop of the algorithm, and then in the inner loop, we attempt to
5850   // insert each A into B's group if:
5851   //
5852   //  1. A and B have the same stride,
5853   //  2. A and B have the same memory object size, and
5854   //  3. A belongs in B's group according to its distance from B.
5855   //
5856   // Special care is taken to ensure group formation will not break any
5857   // dependences.
5858   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
5859        BI != E; ++BI) {
5860     Instruction *B = BI->first;
5861     StrideDescriptor DesB = BI->second;
5862 
5863     // Initialize a group for B if it has an allowable stride. Even if we don't
5864     // create a group for B, we continue with the bottom-up algorithm to ensure
5865     // we don't break any of B's dependences.
5866     InterleaveGroup *Group = nullptr;
5867     if (isStrided(DesB.Stride)) {
5868       Group = getInterleaveGroup(B);
5869       if (!Group) {
5870         DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n');
5871         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
5872       }
5873       if (B->mayWriteToMemory())
5874         StoreGroups.insert(Group);
5875       else
5876         LoadGroups.insert(Group);
5877     }
5878 
5879     for (auto AI = std::next(BI); AI != E; ++AI) {
5880       Instruction *A = AI->first;
5881       StrideDescriptor DesA = AI->second;
5882 
5883       // Our code motion strategy implies that we can't have dependences
5884       // between accesses in an interleaved group and other accesses located
5885       // between the first and last member of the group. Note that this also
5886       // means that a group can't have more than one member at a given offset.
5887       // The accesses in a group can have dependences with other accesses, but
5888       // we must ensure we don't extend the boundaries of the group such that
5889       // we encompass those dependent accesses.
5890       //
5891       // For example, assume we have the sequence of accesses shown below in a
5892       // stride-2 loop:
5893       //
5894       //  (1, 2) is a group | A[i]   = a;  // (1)
5895       //                    | A[i-1] = b;  // (2) |
5896       //                      A[i-3] = c;  // (3)
5897       //                      A[i]   = d;  // (4) | (2, 4) is not a group
5898       //
5899       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
5900       // but not with (4). If we did, the dependent access (3) would be within
5901       // the boundaries of the (2, 4) group.
5902       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
5903         // If a dependence exists and A is already in a group, we know that A
5904         // must be a store since A precedes B and WAR dependences are allowed.
5905         // Thus, A would be sunk below B. We release A's group to prevent this
5906         // illegal code motion. A will then be free to form another group with
5907         // instructions that precede it.
5908         if (isInterleaved(A)) {
5909           InterleaveGroup *StoreGroup = getInterleaveGroup(A);
5910           StoreGroups.remove(StoreGroup);
5911           releaseGroup(StoreGroup);
5912         }
5913 
5914         // If a dependence exists and A is not already in a group (or it was
5915         // and we just released it), B might be hoisted above A (if B is a
5916         // load) or another store might be sunk below A (if B is a store). In
5917         // either case, we can't add additional instructions to B's group. B
5918         // will only form a group with instructions that it precedes.
5919         break;
5920       }
5921 
5922       // At this point, we've checked for illegal code motion. If either A or B
5923       // isn't strided, there's nothing left to do.
5924       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
5925         continue;
5926 
5927       // Ignore A if it's already in a group or isn't the same kind of memory
5928       // operation as B.
5929       // Note that mayReadFromMemory() isn't mutually exclusive to mayWriteToMemory
5930       // in the case of atomic loads. We shouldn't see those here, canVectorizeMemory()
5931       // should have returned false - except for the case we asked for optimization
5932       // remarks.
5933       if (isInterleaved(A) || (A->mayReadFromMemory() != B->mayReadFromMemory())
5934           || (A->mayWriteToMemory() != B->mayWriteToMemory()))
5935         continue;
5936 
5937       // Check rules 1 and 2. Ignore A if its stride or size is different from
5938       // that of B.
5939       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
5940         continue;
5941 
5942       // Ignore A if the memory object of A and B don't belong to the same
5943       // address space
5944       if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B))
5945         continue;
5946 
5947       // Calculate the distance from A to B.
5948       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
5949           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
5950       if (!DistToB)
5951         continue;
5952       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
5953 
5954       // Check rule 3. Ignore A if its distance to B is not a multiple of the
5955       // size.
5956       if (DistanceToB % static_cast<int64_t>(DesB.Size))
5957         continue;
5958 
5959       // Ignore A if either A or B is in a predicated block. Although we
5960       // currently prevent group formation for predicated accesses, we may be
5961       // able to relax this limitation in the future once we handle more
5962       // complicated blocks.
5963       if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
5964         continue;
5965 
5966       // The index of A is the index of B plus A's distance to B in multiples
5967       // of the size.
5968       int IndexA =
5969           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
5970 
5971       // Try to insert A into B's group.
5972       if (Group->insertMember(A, IndexA, DesA.Align)) {
5973         DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
5974                      << "    into the interleave group with" << *B << '\n');
5975         InterleaveGroupMap[A] = Group;
5976 
5977         // Set the first load in program order as the insert position.
5978         if (A->mayReadFromMemory())
5979           Group->setInsertPos(A);
5980       }
5981     } // Iteration over A accesses.
5982   } // Iteration over B accesses.
5983 
5984   // Remove interleaved store groups with gaps.
5985   for (InterleaveGroup *Group : StoreGroups)
5986     if (Group->getNumMembers() != Group->getFactor()) {
5987       DEBUG(dbgs() << "LV: Invalidate candidate interleaved store group due "
5988                       "to gaps.\n");
5989       releaseGroup(Group);
5990     }
5991   // Remove interleaved groups with gaps (currently only loads) whose memory
5992   // accesses may wrap around. We have to revisit the getPtrStride analysis,
5993   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
5994   // not check wrapping (see documentation there).
5995   // FORNOW we use Assume=false;
5996   // TODO: Change to Assume=true but making sure we don't exceed the threshold
5997   // of runtime SCEV assumptions checks (thereby potentially failing to
5998   // vectorize altogether).
5999   // Additional optional optimizations:
6000   // TODO: If we are peeling the loop and we know that the first pointer doesn't
6001   // wrap then we can deduce that all pointers in the group don't wrap.
6002   // This means that we can forcefully peel the loop in order to only have to
6003   // check the first pointer for no-wrap. When we'll change to use Assume=true
6004   // we'll only need at most one runtime check per interleaved group.
6005   for (InterleaveGroup *Group : LoadGroups) {
6006     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
6007     // load would wrap around the address space we would do a memory access at
6008     // nullptr even without the transformation.
6009     if (Group->getNumMembers() == Group->getFactor())
6010       continue;
6011 
6012     // Case 2: If first and last members of the group don't wrap this implies
6013     // that all the pointers in the group don't wrap.
6014     // So we check only group member 0 (which is always guaranteed to exist),
6015     // and group member Factor - 1; If the latter doesn't exist we rely on
6016     // peeling (if it is a non-reveresed accsess -- see Case 3).
6017     Value *FirstMemberPtr = getPointerOperand(Group->getMember(0));
6018     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
6019                       /*ShouldCheckWrap=*/true)) {
6020       DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6021                       "first group member potentially pointer-wrapping.\n");
6022       releaseGroup(Group);
6023       continue;
6024     }
6025     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
6026     if (LastMember) {
6027       Value *LastMemberPtr = getPointerOperand(LastMember);
6028       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
6029                         /*ShouldCheckWrap=*/true)) {
6030         DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6031                         "last group member potentially pointer-wrapping.\n");
6032         releaseGroup(Group);
6033       }
6034     } else {
6035       // Case 3: A non-reversed interleaved load group with gaps: We need
6036       // to execute at least one scalar epilogue iteration. This will ensure
6037       // we don't speculatively access memory out-of-bounds. We only need
6038       // to look for a member at index factor - 1, since every group must have
6039       // a member at index zero.
6040       if (Group->isReverse()) {
6041         DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6042                         "a reverse access with gaps.\n");
6043         releaseGroup(Group);
6044         continue;
6045       }
6046       DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
6047       RequiresScalarEpilogue = true;
6048     }
6049   }
6050 }
6051 
6052 Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
6053   if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
6054     ORE->emit(createMissedAnalysis("ConditionalStore")
6055               << "store that is conditionally executed prevents vectorization");
6056     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
6057     return None;
6058   }
6059 
6060   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
6061     // TODO: It may by useful to do since it's still likely to be dynamically
6062     // uniform if the target can skip.
6063     DEBUG(dbgs() << "LV: Not inserting runtime ptr check for divergent target");
6064 
6065     ORE->emit(
6066       createMissedAnalysis("CantVersionLoopWithDivergentTarget")
6067       << "runtime pointer checks needed. Not enabled for divergent target");
6068 
6069     return None;
6070   }
6071 
6072   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6073   if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
6074     return computeFeasibleMaxVF(OptForSize, TC);
6075 
6076   if (Legal->getRuntimePointerChecking()->Need) {
6077     ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
6078               << "runtime pointer checks needed. Enable vectorization of this "
6079                  "loop with '#pragma clang loop vectorize(enable)' when "
6080                  "compiling with -Os/-Oz");
6081     DEBUG(dbgs()
6082           << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
6083     return None;
6084   }
6085 
6086   // If we optimize the program for size, avoid creating the tail loop.
6087   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
6088 
6089   // If we don't know the precise trip count, don't try to vectorize.
6090   if (TC < 2) {
6091     ORE->emit(
6092         createMissedAnalysis("UnknownLoopCountComplexCFG")
6093         << "unable to calculate the loop count due to complex control flow");
6094     DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6095     return None;
6096   }
6097 
6098   unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
6099 
6100   if (TC % MaxVF != 0) {
6101     // If the trip count that we found modulo the vectorization factor is not
6102     // zero then we require a tail.
6103     // FIXME: look for a smaller MaxVF that does divide TC rather than give up.
6104     // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a
6105     //        smaller MaxVF that does not require a scalar epilog.
6106 
6107     ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
6108               << "cannot optimize for size and vectorize at the "
6109                  "same time. Enable vectorization of this loop "
6110                  "with '#pragma clang loop vectorize(enable)' "
6111                  "when compiling with -Os/-Oz");
6112     DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6113     return None;
6114   }
6115 
6116   return MaxVF;
6117 }
6118 
6119 unsigned
6120 LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize,
6121                                                  unsigned ConstTripCount) {
6122   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
6123   unsigned SmallestType, WidestType;
6124   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
6125   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
6126 
6127   // Get the maximum safe dependence distance in bits computed by LAA.
6128   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
6129   // the memory accesses that is most restrictive (involved in the smallest
6130   // dependence distance).
6131   unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
6132 
6133   WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
6134 
6135   unsigned MaxVectorSize = WidestRegister / WidestType;
6136 
6137   DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
6138                << WidestType << " bits.\n");
6139   DEBUG(dbgs() << "LV: The Widest register safe to use is: " << WidestRegister
6140                << " bits.\n");
6141 
6142   assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
6143                                 " into one vector!");
6144   if (MaxVectorSize == 0) {
6145     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
6146     MaxVectorSize = 1;
6147     return MaxVectorSize;
6148   } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
6149              isPowerOf2_32(ConstTripCount)) {
6150     // We need to clamp the VF to be the ConstTripCount. There is no point in
6151     // choosing a higher viable VF as done in the loop below.
6152     DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
6153                  << ConstTripCount << "\n");
6154     MaxVectorSize = ConstTripCount;
6155     return MaxVectorSize;
6156   }
6157 
6158   unsigned MaxVF = MaxVectorSize;
6159   if (MaximizeBandwidth && !OptForSize) {
6160     // Collect all viable vectorization factors larger than the default MaxVF
6161     // (i.e. MaxVectorSize).
6162     SmallVector<unsigned, 8> VFs;
6163     unsigned NewMaxVectorSize = WidestRegister / SmallestType;
6164     for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
6165       VFs.push_back(VS);
6166 
6167     // For each VF calculate its register usage.
6168     auto RUs = calculateRegisterUsage(VFs);
6169 
6170     // Select the largest VF which doesn't require more registers than existing
6171     // ones.
6172     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
6173     for (int i = RUs.size() - 1; i >= 0; --i) {
6174       if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
6175         MaxVF = VFs[i];
6176         break;
6177       }
6178     }
6179   }
6180   return MaxVF;
6181 }
6182 
6183 VectorizationFactor
6184 LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
6185   float Cost = expectedCost(1).first;
6186 #ifndef NDEBUG
6187   const float ScalarCost = Cost;
6188 #endif /* NDEBUG */
6189   unsigned Width = 1;
6190   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
6191 
6192   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6193   // Ignore scalar width, because the user explicitly wants vectorization.
6194   if (ForceVectorization && MaxVF > 1) {
6195     Width = 2;
6196     Cost = expectedCost(Width).first / (float)Width;
6197   }
6198 
6199   for (unsigned i = 2; i <= MaxVF; i *= 2) {
6200     // Notice that the vector loop needs to be executed less times, so
6201     // we need to divide the cost of the vector loops by the width of
6202     // the vector elements.
6203     VectorizationCostTy C = expectedCost(i);
6204     float VectorCost = C.first / (float)i;
6205     DEBUG(dbgs() << "LV: Vector loop of width " << i
6206                  << " costs: " << (int)VectorCost << ".\n");
6207     if (!C.second && !ForceVectorization) {
6208       DEBUG(
6209           dbgs() << "LV: Not considering vector loop of width " << i
6210                  << " because it will not generate any vector instructions.\n");
6211       continue;
6212     }
6213     if (VectorCost < Cost) {
6214       Cost = VectorCost;
6215       Width = i;
6216     }
6217   }
6218 
6219   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
6220         << "LV: Vectorization seems to be not beneficial, "
6221         << "but was forced by a user.\n");
6222   DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
6223   VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
6224   return Factor;
6225 }
6226 
6227 std::pair<unsigned, unsigned>
6228 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6229   unsigned MinWidth = -1U;
6230   unsigned MaxWidth = 8;
6231   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6232 
6233   // For each block.
6234   for (BasicBlock *BB : TheLoop->blocks()) {
6235     // For each instruction in the loop.
6236     for (Instruction &I : *BB) {
6237       Type *T = I.getType();
6238 
6239       // Skip ignored values.
6240       if (ValuesToIgnore.count(&I))
6241         continue;
6242 
6243       // Only examine Loads, Stores and PHINodes.
6244       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6245         continue;
6246 
6247       // Examine PHI nodes that are reduction variables. Update the type to
6248       // account for the recurrence type.
6249       if (auto *PN = dyn_cast<PHINode>(&I)) {
6250         if (!Legal->isReductionVariable(PN))
6251           continue;
6252         RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
6253         T = RdxDesc.getRecurrenceType();
6254       }
6255 
6256       // Examine the stored values.
6257       if (auto *ST = dyn_cast<StoreInst>(&I))
6258         T = ST->getValueOperand()->getType();
6259 
6260       // Ignore loaded pointer types and stored pointer types that are not
6261       // vectorizable.
6262       //
6263       // FIXME: The check here attempts to predict whether a load or store will
6264       //        be vectorized. We only know this for certain after a VF has
6265       //        been selected. Here, we assume that if an access can be
6266       //        vectorized, it will be. We should also look at extending this
6267       //        optimization to non-pointer types.
6268       //
6269       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6270           !Legal->isAccessInterleaved(&I) && !Legal->isLegalGatherOrScatter(&I))
6271         continue;
6272 
6273       MinWidth = std::min(MinWidth,
6274                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6275       MaxWidth = std::max(MaxWidth,
6276                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6277     }
6278   }
6279 
6280   return {MinWidth, MaxWidth};
6281 }
6282 
6283 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
6284                                                            unsigned VF,
6285                                                            unsigned LoopCost) {
6286   // -- The interleave heuristics --
6287   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6288   // There are many micro-architectural considerations that we can't predict
6289   // at this level. For example, frontend pressure (on decode or fetch) due to
6290   // code size, or the number and capabilities of the execution ports.
6291   //
6292   // We use the following heuristics to select the interleave count:
6293   // 1. If the code has reductions, then we interleave to break the cross
6294   // iteration dependency.
6295   // 2. If the loop is really small, then we interleave to reduce the loop
6296   // overhead.
6297   // 3. We don't interleave if we think that we will spill registers to memory
6298   // due to the increased register pressure.
6299 
6300   // When we optimize for size, we don't interleave.
6301   if (OptForSize)
6302     return 1;
6303 
6304   // We used the distance for the interleave count.
6305   if (Legal->getMaxSafeDepDistBytes() != -1U)
6306     return 1;
6307 
6308   // Do not interleave loops with a relatively small trip count.
6309   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6310   if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
6311     return 1;
6312 
6313   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
6314   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6315                << " registers\n");
6316 
6317   if (VF == 1) {
6318     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6319       TargetNumRegisters = ForceTargetNumScalarRegs;
6320   } else {
6321     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6322       TargetNumRegisters = ForceTargetNumVectorRegs;
6323   }
6324 
6325   RegisterUsage R = calculateRegisterUsage({VF})[0];
6326   // We divide by these constants so assume that we have at least one
6327   // instruction that uses at least one register.
6328   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
6329   R.NumInstructions = std::max(R.NumInstructions, 1U);
6330 
6331   // We calculate the interleave count using the following formula.
6332   // Subtract the number of loop invariants from the number of available
6333   // registers. These registers are used by all of the interleaved instances.
6334   // Next, divide the remaining registers by the number of registers that is
6335   // required by the loop, in order to estimate how many parallel instances
6336   // fit without causing spills. All of this is rounded down if necessary to be
6337   // a power of two. We want power of two interleave count to simplify any
6338   // addressing operations or alignment considerations.
6339   unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
6340                               R.MaxLocalUsers);
6341 
6342   // Don't count the induction variable as interleaved.
6343   if (EnableIndVarRegisterHeur)
6344     IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
6345                        std::max(1U, (R.MaxLocalUsers - 1)));
6346 
6347   // Clamp the interleave ranges to reasonable counts.
6348   unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
6349 
6350   // Check if the user has overridden the max.
6351   if (VF == 1) {
6352     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6353       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6354   } else {
6355     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6356       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6357   }
6358 
6359   // If we did not calculate the cost for VF (because the user selected the VF)
6360   // then we calculate the cost of VF here.
6361   if (LoopCost == 0)
6362     LoopCost = expectedCost(VF).first;
6363 
6364   // Clamp the calculated IC to be between the 1 and the max interleave count
6365   // that the target allows.
6366   if (IC > MaxInterleaveCount)
6367     IC = MaxInterleaveCount;
6368   else if (IC < 1)
6369     IC = 1;
6370 
6371   // Interleave if we vectorized this loop and there is a reduction that could
6372   // benefit from interleaving.
6373   if (VF > 1 && !Legal->getReductionVars()->empty()) {
6374     DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6375     return IC;
6376   }
6377 
6378   // Note that if we've already vectorized the loop we will have done the
6379   // runtime check and so interleaving won't require further checks.
6380   bool InterleavingRequiresRuntimePointerCheck =
6381       (VF == 1 && Legal->getRuntimePointerChecking()->Need);
6382 
6383   // We want to interleave small loops in order to reduce the loop overhead and
6384   // potentially expose ILP opportunities.
6385   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
6386   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6387     // We assume that the cost overhead is 1 and we use the cost model
6388     // to estimate the cost of the loop and interleave until the cost of the
6389     // loop overhead is about 5% of the cost of the loop.
6390     unsigned SmallIC =
6391         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6392 
6393     // Interleave until store/load ports (estimated by max interleave count) are
6394     // saturated.
6395     unsigned NumStores = Legal->getNumStores();
6396     unsigned NumLoads = Legal->getNumLoads();
6397     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6398     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6399 
6400     // If we have a scalar reduction (vector reductions are already dealt with
6401     // by this point), we can increase the critical path length if the loop
6402     // we're interleaving is inside another loop. Limit, by default to 2, so the
6403     // critical path only gets increased by one reduction operation.
6404     if (!Legal->getReductionVars()->empty() && TheLoop->getLoopDepth() > 1) {
6405       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6406       SmallIC = std::min(SmallIC, F);
6407       StoresIC = std::min(StoresIC, F);
6408       LoadsIC = std::min(LoadsIC, F);
6409     }
6410 
6411     if (EnableLoadStoreRuntimeInterleave &&
6412         std::max(StoresIC, LoadsIC) > SmallIC) {
6413       DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6414       return std::max(StoresIC, LoadsIC);
6415     }
6416 
6417     DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6418     return SmallIC;
6419   }
6420 
6421   // Interleave if this is a large loop (small loops are already dealt with by
6422   // this point) that could benefit from interleaving.
6423   bool HasReductions = !Legal->getReductionVars()->empty();
6424   if (TTI.enableAggressiveInterleaving(HasReductions)) {
6425     DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6426     return IC;
6427   }
6428 
6429   DEBUG(dbgs() << "LV: Not Interleaving.\n");
6430   return 1;
6431 }
6432 
6433 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6434 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
6435   // This function calculates the register usage by measuring the highest number
6436   // of values that are alive at a single location. Obviously, this is a very
6437   // rough estimation. We scan the loop in a topological order in order and
6438   // assign a number to each instruction. We use RPO to ensure that defs are
6439   // met before their users. We assume that each instruction that has in-loop
6440   // users starts an interval. We record every time that an in-loop value is
6441   // used, so we have a list of the first and last occurrences of each
6442   // instruction. Next, we transpose this data structure into a multi map that
6443   // holds the list of intervals that *end* at a specific location. This multi
6444   // map allows us to perform a linear search. We scan the instructions linearly
6445   // and record each time that a new interval starts, by placing it in a set.
6446   // If we find this value in the multi-map then we remove it from the set.
6447   // The max register usage is the maximum size of the set.
6448   // We also search for instructions that are defined outside the loop, but are
6449   // used inside the loop. We need this number separately from the max-interval
6450   // usage number because when we unroll, loop-invariant values do not take
6451   // more register.
6452   LoopBlocksDFS DFS(TheLoop);
6453   DFS.perform(LI);
6454 
6455   RegisterUsage RU;
6456   RU.NumInstructions = 0;
6457 
6458   // Each 'key' in the map opens a new interval. The values
6459   // of the map are the index of the 'last seen' usage of the
6460   // instruction that is the key.
6461   using IntervalMap = DenseMap<Instruction *, unsigned>;
6462 
6463   // Maps instruction to its index.
6464   DenseMap<unsigned, Instruction *> IdxToInstr;
6465   // Marks the end of each interval.
6466   IntervalMap EndPoint;
6467   // Saves the list of instruction indices that are used in the loop.
6468   SmallSet<Instruction *, 8> Ends;
6469   // Saves the list of values that are used in the loop but are
6470   // defined outside the loop, such as arguments and constants.
6471   SmallPtrSet<Value *, 8> LoopInvariants;
6472 
6473   unsigned Index = 0;
6474   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6475     RU.NumInstructions += BB->size();
6476     for (Instruction &I : *BB) {
6477       IdxToInstr[Index++] = &I;
6478 
6479       // Save the end location of each USE.
6480       for (Value *U : I.operands()) {
6481         auto *Instr = dyn_cast<Instruction>(U);
6482 
6483         // Ignore non-instruction values such as arguments, constants, etc.
6484         if (!Instr)
6485           continue;
6486 
6487         // If this instruction is outside the loop then record it and continue.
6488         if (!TheLoop->contains(Instr)) {
6489           LoopInvariants.insert(Instr);
6490           continue;
6491         }
6492 
6493         // Overwrite previous end points.
6494         EndPoint[Instr] = Index;
6495         Ends.insert(Instr);
6496       }
6497     }
6498   }
6499 
6500   // Saves the list of intervals that end with the index in 'key'.
6501   using InstrList = SmallVector<Instruction *, 2>;
6502   DenseMap<unsigned, InstrList> TransposeEnds;
6503 
6504   // Transpose the EndPoints to a list of values that end at each index.
6505   for (auto &Interval : EndPoint)
6506     TransposeEnds[Interval.second].push_back(Interval.first);
6507 
6508   SmallSet<Instruction *, 8> OpenIntervals;
6509 
6510   // Get the size of the widest register.
6511   unsigned MaxSafeDepDist = -1U;
6512   if (Legal->getMaxSafeDepDistBytes() != -1U)
6513     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
6514   unsigned WidestRegister =
6515       std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
6516   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6517 
6518   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6519   SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
6520 
6521   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6522 
6523   // A lambda that gets the register usage for the given type and VF.
6524   auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
6525     if (Ty->isTokenTy())
6526       return 0U;
6527     unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
6528     return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
6529   };
6530 
6531   for (unsigned int i = 0; i < Index; ++i) {
6532     Instruction *I = IdxToInstr[i];
6533 
6534     // Remove all of the instructions that end at this location.
6535     InstrList &List = TransposeEnds[i];
6536     for (Instruction *ToRemove : List)
6537       OpenIntervals.erase(ToRemove);
6538 
6539     // Ignore instructions that are never used within the loop.
6540     if (!Ends.count(I))
6541       continue;
6542 
6543     // Skip ignored values.
6544     if (ValuesToIgnore.count(I))
6545       continue;
6546 
6547     // For each VF find the maximum usage of registers.
6548     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6549       if (VFs[j] == 1) {
6550         MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
6551         continue;
6552       }
6553       collectUniformsAndScalars(VFs[j]);
6554       // Count the number of live intervals.
6555       unsigned RegUsage = 0;
6556       for (auto Inst : OpenIntervals) {
6557         // Skip ignored values for VF > 1.
6558         if (VecValuesToIgnore.count(Inst) ||
6559             isScalarAfterVectorization(Inst, VFs[j]))
6560           continue;
6561         RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
6562       }
6563       MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
6564     }
6565 
6566     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6567                  << OpenIntervals.size() << '\n');
6568 
6569     // Add the current instruction to the list of open intervals.
6570     OpenIntervals.insert(I);
6571   }
6572 
6573   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6574     unsigned Invariant = 0;
6575     if (VFs[i] == 1)
6576       Invariant = LoopInvariants.size();
6577     else {
6578       for (auto Inst : LoopInvariants)
6579         Invariant += GetRegUsage(Inst->getType(), VFs[i]);
6580     }
6581 
6582     DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
6583     DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
6584     DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
6585     DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
6586 
6587     RU.LoopInvariantRegs = Invariant;
6588     RU.MaxLocalUsers = MaxUsages[i];
6589     RUs[i] = RU;
6590   }
6591 
6592   return RUs;
6593 }
6594 
6595 void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
6596   // If we aren't vectorizing the loop, or if we've already collected the
6597   // instructions to scalarize, there's nothing to do. Collection may already
6598   // have occurred if we have a user-selected VF and are now computing the
6599   // expected cost for interleaving.
6600   if (VF < 2 || InstsToScalarize.count(VF))
6601     return;
6602 
6603   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6604   // not profitable to scalarize any instructions, the presence of VF in the
6605   // map will indicate that we've analyzed it already.
6606   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6607 
6608   // Find all the instructions that are scalar with predication in the loop and
6609   // determine if it would be better to not if-convert the blocks they are in.
6610   // If so, we also record the instructions to scalarize.
6611   for (BasicBlock *BB : TheLoop->blocks()) {
6612     if (!Legal->blockNeedsPredication(BB))
6613       continue;
6614     for (Instruction &I : *BB)
6615       if (Legal->isScalarWithPredication(&I)) {
6616         ScalarCostsTy ScalarCosts;
6617         if (computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6618           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6619 
6620         // Remember that BB will remain after vectorization.
6621         PredicatedBBsAfterVectorization.insert(BB);
6622       }
6623   }
6624 }
6625 
6626 int LoopVectorizationCostModel::computePredInstDiscount(
6627     Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
6628     unsigned VF) {
6629   assert(!isUniformAfterVectorization(PredInst, VF) &&
6630          "Instruction marked uniform-after-vectorization will be predicated");
6631 
6632   // Initialize the discount to zero, meaning that the scalar version and the
6633   // vector version cost the same.
6634   int Discount = 0;
6635 
6636   // Holds instructions to analyze. The instructions we visit are mapped in
6637   // ScalarCosts. Those instructions are the ones that would be scalarized if
6638   // we find that the scalar version costs less.
6639   SmallVector<Instruction *, 8> Worklist;
6640 
6641   // Returns true if the given instruction can be scalarized.
6642   auto canBeScalarized = [&](Instruction *I) -> bool {
6643     // We only attempt to scalarize instructions forming a single-use chain
6644     // from the original predicated block that would otherwise be vectorized.
6645     // Although not strictly necessary, we give up on instructions we know will
6646     // already be scalar to avoid traversing chains that are unlikely to be
6647     // beneficial.
6648     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6649         isScalarAfterVectorization(I, VF))
6650       return false;
6651 
6652     // If the instruction is scalar with predication, it will be analyzed
6653     // separately. We ignore it within the context of PredInst.
6654     if (Legal->isScalarWithPredication(I))
6655       return false;
6656 
6657     // If any of the instruction's operands are uniform after vectorization,
6658     // the instruction cannot be scalarized. This prevents, for example, a
6659     // masked load from being scalarized.
6660     //
6661     // We assume we will only emit a value for lane zero of an instruction
6662     // marked uniform after vectorization, rather than VF identical values.
6663     // Thus, if we scalarize an instruction that uses a uniform, we would
6664     // create uses of values corresponding to the lanes we aren't emitting code
6665     // for. This behavior can be changed by allowing getScalarValue to clone
6666     // the lane zero values for uniforms rather than asserting.
6667     for (Use &U : I->operands())
6668       if (auto *J = dyn_cast<Instruction>(U.get()))
6669         if (isUniformAfterVectorization(J, VF))
6670           return false;
6671 
6672     // Otherwise, we can scalarize the instruction.
6673     return true;
6674   };
6675 
6676   // Returns true if an operand that cannot be scalarized must be extracted
6677   // from a vector. We will account for this scalarization overhead below. Note
6678   // that the non-void predicated instructions are placed in their own blocks,
6679   // and their return values are inserted into vectors. Thus, an extract would
6680   // still be required.
6681   auto needsExtract = [&](Instruction *I) -> bool {
6682     return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
6683   };
6684 
6685   // Compute the expected cost discount from scalarizing the entire expression
6686   // feeding the predicated instruction. We currently only consider expressions
6687   // that are single-use instruction chains.
6688   Worklist.push_back(PredInst);
6689   while (!Worklist.empty()) {
6690     Instruction *I = Worklist.pop_back_val();
6691 
6692     // If we've already analyzed the instruction, there's nothing to do.
6693     if (ScalarCosts.count(I))
6694       continue;
6695 
6696     // Compute the cost of the vector instruction. Note that this cost already
6697     // includes the scalarization overhead of the predicated instruction.
6698     unsigned VectorCost = getInstructionCost(I, VF).first;
6699 
6700     // Compute the cost of the scalarized instruction. This cost is the cost of
6701     // the instruction as if it wasn't if-converted and instead remained in the
6702     // predicated block. We will scale this cost by block probability after
6703     // computing the scalarization overhead.
6704     unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
6705 
6706     // Compute the scalarization overhead of needed insertelement instructions
6707     // and phi nodes.
6708     if (Legal->isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6709       ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
6710                                                  true, false);
6711       ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
6712     }
6713 
6714     // Compute the scalarization overhead of needed extractelement
6715     // instructions. For each of the instruction's operands, if the operand can
6716     // be scalarized, add it to the worklist; otherwise, account for the
6717     // overhead.
6718     for (Use &U : I->operands())
6719       if (auto *J = dyn_cast<Instruction>(U.get())) {
6720         assert(VectorType::isValidElementType(J->getType()) &&
6721                "Instruction has non-scalar type");
6722         if (canBeScalarized(J))
6723           Worklist.push_back(J);
6724         else if (needsExtract(J))
6725           ScalarCost += TTI.getScalarizationOverhead(
6726                               ToVectorTy(J->getType(),VF), false, true);
6727       }
6728 
6729     // Scale the total scalar cost by block probability.
6730     ScalarCost /= getReciprocalPredBlockProb();
6731 
6732     // Compute the discount. A non-negative discount means the vector version
6733     // of the instruction costs more, and scalarizing would be beneficial.
6734     Discount += VectorCost - ScalarCost;
6735     ScalarCosts[I] = ScalarCost;
6736   }
6737 
6738   return Discount;
6739 }
6740 
6741 LoopVectorizationCostModel::VectorizationCostTy
6742 LoopVectorizationCostModel::expectedCost(unsigned VF) {
6743   VectorizationCostTy Cost;
6744 
6745   // For each block.
6746   for (BasicBlock *BB : TheLoop->blocks()) {
6747     VectorizationCostTy BlockCost;
6748 
6749     // For each instruction in the old loop.
6750     for (Instruction &I : *BB) {
6751       // Skip dbg intrinsics.
6752       if (isa<DbgInfoIntrinsic>(I))
6753         continue;
6754 
6755       // Skip ignored values.
6756       if (ValuesToIgnore.count(&I) ||
6757           (VF > 1 && VecValuesToIgnore.count(&I)))
6758         continue;
6759 
6760       VectorizationCostTy C = getInstructionCost(&I, VF);
6761 
6762       // Check if we should override the cost.
6763       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6764         C.first = ForceTargetInstructionCost;
6765 
6766       BlockCost.first += C.first;
6767       BlockCost.second |= C.second;
6768       DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF "
6769                    << VF << " For instruction: " << I << '\n');
6770     }
6771 
6772     // If we are vectorizing a predicated block, it will have been
6773     // if-converted. This means that the block's instructions (aside from
6774     // stores and instructions that may divide by zero) will now be
6775     // unconditionally executed. For the scalar case, we may not always execute
6776     // the predicated block. Thus, scale the block's cost by the probability of
6777     // executing it.
6778     if (VF == 1 && Legal->blockNeedsPredication(BB))
6779       BlockCost.first /= getReciprocalPredBlockProb();
6780 
6781     Cost.first += BlockCost.first;
6782     Cost.second |= BlockCost.second;
6783   }
6784 
6785   return Cost;
6786 }
6787 
6788 /// \brief Gets Address Access SCEV after verifying that the access pattern
6789 /// is loop invariant except the induction variable dependence.
6790 ///
6791 /// This SCEV can be sent to the Target in order to estimate the address
6792 /// calculation cost.
6793 static const SCEV *getAddressAccessSCEV(
6794               Value *Ptr,
6795               LoopVectorizationLegality *Legal,
6796               PredicatedScalarEvolution &PSE,
6797               const Loop *TheLoop) {
6798 
6799   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6800   if (!Gep)
6801     return nullptr;
6802 
6803   // We are looking for a gep with all loop invariant indices except for one
6804   // which should be an induction variable.
6805   auto SE = PSE.getSE();
6806   unsigned NumOperands = Gep->getNumOperands();
6807   for (unsigned i = 1; i < NumOperands; ++i) {
6808     Value *Opd = Gep->getOperand(i);
6809     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6810         !Legal->isInductionVariable(Opd))
6811       return nullptr;
6812   }
6813 
6814   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6815   return PSE.getSCEV(Ptr);
6816 }
6817 
6818 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6819   return Legal->hasStride(I->getOperand(0)) ||
6820          Legal->hasStride(I->getOperand(1));
6821 }
6822 
6823 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6824                                                                  unsigned VF) {
6825   Type *ValTy = getMemInstValueType(I);
6826   auto SE = PSE.getSE();
6827 
6828   unsigned Alignment = getMemInstAlignment(I);
6829   unsigned AS = getMemInstAddressSpace(I);
6830   Value *Ptr = getPointerOperand(I);
6831   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6832 
6833   // Figure out whether the access is strided and get the stride value
6834   // if it's known in compile time
6835   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6836 
6837   // Get the cost of the scalar memory instruction and address computation.
6838   unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6839 
6840   Cost += VF *
6841           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6842                               AS, I);
6843 
6844   // Get the overhead of the extractelement and insertelement instructions
6845   // we might create due to scalarization.
6846   Cost += getScalarizationOverhead(I, VF, TTI);
6847 
6848   // If we have a predicated store, it may not be executed for each vector
6849   // lane. Scale the cost by the probability of executing the predicated
6850   // block.
6851   if (Legal->isScalarWithPredication(I))
6852     Cost /= getReciprocalPredBlockProb();
6853 
6854   return Cost;
6855 }
6856 
6857 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6858                                                              unsigned VF) {
6859   Type *ValTy = getMemInstValueType(I);
6860   Type *VectorTy = ToVectorTy(ValTy, VF);
6861   unsigned Alignment = getMemInstAlignment(I);
6862   Value *Ptr = getPointerOperand(I);
6863   unsigned AS = getMemInstAddressSpace(I);
6864   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6865 
6866   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6867          "Stride should be 1 or -1 for consecutive memory access");
6868   unsigned Cost = 0;
6869   if (Legal->isMaskRequired(I))
6870     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6871   else
6872     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
6873 
6874   bool Reverse = ConsecutiveStride < 0;
6875   if (Reverse)
6876     Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6877   return Cost;
6878 }
6879 
6880 unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6881                                                          unsigned VF) {
6882   LoadInst *LI = cast<LoadInst>(I);
6883   Type *ValTy = LI->getType();
6884   Type *VectorTy = ToVectorTy(ValTy, VF);
6885   unsigned Alignment = LI->getAlignment();
6886   unsigned AS = LI->getPointerAddressSpace();
6887 
6888   return TTI.getAddressComputationCost(ValTy) +
6889          TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
6890          TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6891 }
6892 
6893 unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6894                                                           unsigned VF) {
6895   Type *ValTy = getMemInstValueType(I);
6896   Type *VectorTy = ToVectorTy(ValTy, VF);
6897   unsigned Alignment = getMemInstAlignment(I);
6898   Value *Ptr = getPointerOperand(I);
6899 
6900   return TTI.getAddressComputationCost(VectorTy) +
6901          TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
6902                                     Legal->isMaskRequired(I), Alignment);
6903 }
6904 
6905 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6906                                                             unsigned VF) {
6907   Type *ValTy = getMemInstValueType(I);
6908   Type *VectorTy = ToVectorTy(ValTy, VF);
6909   unsigned AS = getMemInstAddressSpace(I);
6910 
6911   auto Group = Legal->getInterleavedAccessGroup(I);
6912   assert(Group && "Fail to get an interleaved access group.");
6913 
6914   unsigned InterleaveFactor = Group->getFactor();
6915   Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6916 
6917   // Holds the indices of existing members in an interleaved load group.
6918   // An interleaved store group doesn't need this as it doesn't allow gaps.
6919   SmallVector<unsigned, 4> Indices;
6920   if (isa<LoadInst>(I)) {
6921     for (unsigned i = 0; i < InterleaveFactor; i++)
6922       if (Group->getMember(i))
6923         Indices.push_back(i);
6924   }
6925 
6926   // Calculate the cost of the whole interleaved group.
6927   unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy,
6928                                                  Group->getFactor(), Indices,
6929                                                  Group->getAlignment(), AS);
6930 
6931   if (Group->isReverse())
6932     Cost += Group->getNumMembers() *
6933             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6934   return Cost;
6935 }
6936 
6937 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6938                                                               unsigned VF) {
6939   // Calculate scalar cost only. Vectorization cost should be ready at this
6940   // moment.
6941   if (VF == 1) {
6942     Type *ValTy = getMemInstValueType(I);
6943     unsigned Alignment = getMemInstAlignment(I);
6944     unsigned AS = getMemInstAddressSpace(I);
6945 
6946     return TTI.getAddressComputationCost(ValTy) +
6947            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I);
6948   }
6949   return getWideningCost(I, VF);
6950 }
6951 
6952 LoopVectorizationCostModel::VectorizationCostTy
6953 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
6954   // If we know that this instruction will remain uniform, check the cost of
6955   // the scalar version.
6956   if (isUniformAfterVectorization(I, VF))
6957     VF = 1;
6958 
6959   if (VF > 1 && isProfitableToScalarize(I, VF))
6960     return VectorizationCostTy(InstsToScalarize[VF][I], false);
6961 
6962   // Forced scalars do not have any scalarization overhead.
6963   if (VF > 1 && ForcedScalars.count(VF) &&
6964       ForcedScalars.find(VF)->second.count(I))
6965     return VectorizationCostTy((getInstructionCost(I, 1).first * VF), false);
6966 
6967   Type *VectorTy;
6968   unsigned C = getInstructionCost(I, VF, VectorTy);
6969 
6970   bool TypeNotScalarized =
6971       VF > 1 && VectorTy->isVectorTy() && TTI.getNumberOfParts(VectorTy) < VF;
6972   return VectorizationCostTy(C, TypeNotScalarized);
6973 }
6974 
6975 void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
6976   if (VF == 1)
6977     return;
6978   for (BasicBlock *BB : TheLoop->blocks()) {
6979     // For each instruction in the old loop.
6980     for (Instruction &I : *BB) {
6981       Value *Ptr = getPointerOperand(&I);
6982       if (!Ptr)
6983         continue;
6984 
6985       if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) {
6986         // Scalar load + broadcast
6987         unsigned Cost = getUniformMemOpCost(&I, VF);
6988         setWideningDecision(&I, VF, CM_Scalarize, Cost);
6989         continue;
6990       }
6991 
6992       // We assume that widening is the best solution when possible.
6993       if (Legal->memoryInstructionCanBeWidened(&I, VF)) {
6994         unsigned Cost = getConsecutiveMemOpCost(&I, VF);
6995         int ConsecutiveStride = Legal->isConsecutivePtr(getPointerOperand(&I));
6996         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6997                "Expected consecutive stride.");
6998         InstWidening Decision =
6999             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7000         setWideningDecision(&I, VF, Decision, Cost);
7001         continue;
7002       }
7003 
7004       // Choose between Interleaving, Gather/Scatter or Scalarization.
7005       unsigned InterleaveCost = std::numeric_limits<unsigned>::max();
7006       unsigned NumAccesses = 1;
7007       if (Legal->isAccessInterleaved(&I)) {
7008         auto Group = Legal->getInterleavedAccessGroup(&I);
7009         assert(Group && "Fail to get an interleaved access group.");
7010 
7011         // Make one decision for the whole group.
7012         if (getWideningDecision(&I, VF) != CM_Unknown)
7013           continue;
7014 
7015         NumAccesses = Group->getNumMembers();
7016         InterleaveCost = getInterleaveGroupCost(&I, VF);
7017       }
7018 
7019       unsigned GatherScatterCost =
7020           Legal->isLegalGatherOrScatter(&I)
7021               ? getGatherScatterCost(&I, VF) * NumAccesses
7022               : std::numeric_limits<unsigned>::max();
7023 
7024       unsigned ScalarizationCost =
7025           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7026 
7027       // Choose better solution for the current VF,
7028       // write down this decision and use it during vectorization.
7029       unsigned Cost;
7030       InstWidening Decision;
7031       if (InterleaveCost <= GatherScatterCost &&
7032           InterleaveCost < ScalarizationCost) {
7033         Decision = CM_Interleave;
7034         Cost = InterleaveCost;
7035       } else if (GatherScatterCost < ScalarizationCost) {
7036         Decision = CM_GatherScatter;
7037         Cost = GatherScatterCost;
7038       } else {
7039         Decision = CM_Scalarize;
7040         Cost = ScalarizationCost;
7041       }
7042       // If the instructions belongs to an interleave group, the whole group
7043       // receives the same decision. The whole group receives the cost, but
7044       // the cost will actually be assigned to one instruction.
7045       if (auto Group = Legal->getInterleavedAccessGroup(&I))
7046         setWideningDecision(Group, VF, Decision, Cost);
7047       else
7048         setWideningDecision(&I, VF, Decision, Cost);
7049     }
7050   }
7051 
7052   // Make sure that any load of address and any other address computation
7053   // remains scalar unless there is gather/scatter support. This avoids
7054   // inevitable extracts into address registers, and also has the benefit of
7055   // activating LSR more, since that pass can't optimize vectorized
7056   // addresses.
7057   if (TTI.prefersVectorizedAddressing())
7058     return;
7059 
7060   // Start with all scalar pointer uses.
7061   SmallPtrSet<Instruction *, 8> AddrDefs;
7062   for (BasicBlock *BB : TheLoop->blocks())
7063     for (Instruction &I : *BB) {
7064       Instruction *PtrDef =
7065         dyn_cast_or_null<Instruction>(getPointerOperand(&I));
7066       if (PtrDef && TheLoop->contains(PtrDef) &&
7067           getWideningDecision(&I, VF) != CM_GatherScatter)
7068         AddrDefs.insert(PtrDef);
7069     }
7070 
7071   // Add all instructions used to generate the addresses.
7072   SmallVector<Instruction *, 4> Worklist;
7073   for (auto *I : AddrDefs)
7074     Worklist.push_back(I);
7075   while (!Worklist.empty()) {
7076     Instruction *I = Worklist.pop_back_val();
7077     for (auto &Op : I->operands())
7078       if (auto *InstOp = dyn_cast<Instruction>(Op))
7079         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7080             AddrDefs.insert(InstOp).second)
7081           Worklist.push_back(InstOp);
7082   }
7083 
7084   for (auto *I : AddrDefs) {
7085     if (isa<LoadInst>(I)) {
7086       // Setting the desired widening decision should ideally be handled in
7087       // by cost functions, but since this involves the task of finding out
7088       // if the loaded register is involved in an address computation, it is
7089       // instead changed here when we know this is the case.
7090       InstWidening Decision = getWideningDecision(I, VF);
7091       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7092         // Scalarize a widened load of address.
7093         setWideningDecision(I, VF, CM_Scalarize,
7094                             (VF * getMemoryInstructionCost(I, 1)));
7095       else if (auto Group = Legal->getInterleavedAccessGroup(I)) {
7096         // Scalarize an interleave group of address loads.
7097         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7098           if (Instruction *Member = Group->getMember(I))
7099             setWideningDecision(Member, VF, CM_Scalarize,
7100                                 (VF * getMemoryInstructionCost(Member, 1)));
7101         }
7102       }
7103     } else
7104       // Make sure I gets scalarized and a cost estimate without
7105       // scalarization overhead.
7106       ForcedScalars[VF].insert(I);
7107   }
7108 }
7109 
7110 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7111                                                         unsigned VF,
7112                                                         Type *&VectorTy) {
7113   Type *RetTy = I->getType();
7114   if (canTruncateToMinimalBitwidth(I, VF))
7115     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7116   VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
7117   auto SE = PSE.getSE();
7118 
7119   // TODO: We need to estimate the cost of intrinsic calls.
7120   switch (I->getOpcode()) {
7121   case Instruction::GetElementPtr:
7122     // We mark this instruction as zero-cost because the cost of GEPs in
7123     // vectorized code depends on whether the corresponding memory instruction
7124     // is scalarized or not. Therefore, we handle GEPs with the memory
7125     // instruction cost.
7126     return 0;
7127   case Instruction::Br: {
7128     // In cases of scalarized and predicated instructions, there will be VF
7129     // predicated blocks in the vectorized loop. Each branch around these
7130     // blocks requires also an extract of its vector compare i1 element.
7131     bool ScalarPredicatedBB = false;
7132     BranchInst *BI = cast<BranchInst>(I);
7133     if (VF > 1 && BI->isConditional() &&
7134         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7135          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7136       ScalarPredicatedBB = true;
7137 
7138     if (ScalarPredicatedBB) {
7139       // Return cost for branches around scalarized and predicated blocks.
7140       Type *Vec_i1Ty =
7141           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7142       return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) +
7143               (TTI.getCFInstrCost(Instruction::Br) * VF));
7144     } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1)
7145       // The back-edge branch will remain, as will all scalar branches.
7146       return TTI.getCFInstrCost(Instruction::Br);
7147     else
7148       // This branch will be eliminated by if-conversion.
7149       return 0;
7150     // Note: We currently assume zero cost for an unconditional branch inside
7151     // a predicated block since it will become a fall-through, although we
7152     // may decide in the future to call TTI for all branches.
7153   }
7154   case Instruction::PHI: {
7155     auto *Phi = cast<PHINode>(I);
7156 
7157     // First-order recurrences are replaced by vector shuffles inside the loop.
7158     if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
7159       return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
7160                                 VectorTy, VF - 1, VectorTy);
7161 
7162     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7163     // converted into select instructions. We require N - 1 selects per phi
7164     // node, where N is the number of incoming values.
7165     if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
7166       return (Phi->getNumIncomingValues() - 1) *
7167              TTI.getCmpSelInstrCost(
7168                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7169                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF));
7170 
7171     return TTI.getCFInstrCost(Instruction::PHI);
7172   }
7173   case Instruction::UDiv:
7174   case Instruction::SDiv:
7175   case Instruction::URem:
7176   case Instruction::SRem:
7177     // If we have a predicated instruction, it may not be executed for each
7178     // vector lane. Get the scalarization cost and scale this amount by the
7179     // probability of executing the predicated block. If the instruction is not
7180     // predicated, we fall through to the next case.
7181     if (VF > 1 && Legal->isScalarWithPredication(I)) {
7182       unsigned Cost = 0;
7183 
7184       // These instructions have a non-void type, so account for the phi nodes
7185       // that we will create. This cost is likely to be zero. The phi node
7186       // cost, if any, should be scaled by the block probability because it
7187       // models a copy at the end of each predicated block.
7188       Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
7189 
7190       // The cost of the non-predicated instruction.
7191       Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
7192 
7193       // The cost of insertelement and extractelement instructions needed for
7194       // scalarization.
7195       Cost += getScalarizationOverhead(I, VF, TTI);
7196 
7197       // Scale the cost by the probability of executing the predicated blocks.
7198       // This assumes the predicated block for each vector lane is equally
7199       // likely.
7200       return Cost / getReciprocalPredBlockProb();
7201     }
7202     LLVM_FALLTHROUGH;
7203   case Instruction::Add:
7204   case Instruction::FAdd:
7205   case Instruction::Sub:
7206   case Instruction::FSub:
7207   case Instruction::Mul:
7208   case Instruction::FMul:
7209   case Instruction::FDiv:
7210   case Instruction::FRem:
7211   case Instruction::Shl:
7212   case Instruction::LShr:
7213   case Instruction::AShr:
7214   case Instruction::And:
7215   case Instruction::Or:
7216   case Instruction::Xor: {
7217     // Since we will replace the stride by 1 the multiplication should go away.
7218     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7219       return 0;
7220     // Certain instructions can be cheaper to vectorize if they have a constant
7221     // second vector operand. One example of this are shifts on x86.
7222     TargetTransformInfo::OperandValueKind Op1VK =
7223         TargetTransformInfo::OK_AnyValue;
7224     TargetTransformInfo::OperandValueKind Op2VK =
7225         TargetTransformInfo::OK_AnyValue;
7226     TargetTransformInfo::OperandValueProperties Op1VP =
7227         TargetTransformInfo::OP_None;
7228     TargetTransformInfo::OperandValueProperties Op2VP =
7229         TargetTransformInfo::OP_None;
7230     Value *Op2 = I->getOperand(1);
7231 
7232     // Check for a splat or for a non uniform vector of constants.
7233     if (isa<ConstantInt>(Op2)) {
7234       ConstantInt *CInt = cast<ConstantInt>(Op2);
7235       if (CInt && CInt->getValue().isPowerOf2())
7236         Op2VP = TargetTransformInfo::OP_PowerOf2;
7237       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7238     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
7239       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
7240       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
7241       if (SplatValue) {
7242         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
7243         if (CInt && CInt->getValue().isPowerOf2())
7244           Op2VP = TargetTransformInfo::OP_PowerOf2;
7245         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7246       }
7247     } else if (Legal->isUniform(Op2)) {
7248       Op2VK = TargetTransformInfo::OK_UniformValue;
7249     }
7250     SmallVector<const Value *, 4> Operands(I->operand_values());
7251     unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
7252     return N * TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK,
7253                                           Op2VK, Op1VP, Op2VP, Operands);
7254   }
7255   case Instruction::Select: {
7256     SelectInst *SI = cast<SelectInst>(I);
7257     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7258     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7259     Type *CondTy = SI->getCondition()->getType();
7260     if (!ScalarCond)
7261       CondTy = VectorType::get(CondTy, VF);
7262 
7263     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I);
7264   }
7265   case Instruction::ICmp:
7266   case Instruction::FCmp: {
7267     Type *ValTy = I->getOperand(0)->getType();
7268     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7269     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7270       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7271     VectorTy = ToVectorTy(ValTy, VF);
7272     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I);
7273   }
7274   case Instruction::Store:
7275   case Instruction::Load: {
7276     unsigned Width = VF;
7277     if (Width > 1) {
7278       InstWidening Decision = getWideningDecision(I, Width);
7279       assert(Decision != CM_Unknown &&
7280              "CM decision should be taken at this point");
7281       if (Decision == CM_Scalarize)
7282         Width = 1;
7283     }
7284     VectorTy = ToVectorTy(getMemInstValueType(I), Width);
7285     return getMemoryInstructionCost(I, VF);
7286   }
7287   case Instruction::ZExt:
7288   case Instruction::SExt:
7289   case Instruction::FPToUI:
7290   case Instruction::FPToSI:
7291   case Instruction::FPExt:
7292   case Instruction::PtrToInt:
7293   case Instruction::IntToPtr:
7294   case Instruction::SIToFP:
7295   case Instruction::UIToFP:
7296   case Instruction::Trunc:
7297   case Instruction::FPTrunc:
7298   case Instruction::BitCast: {
7299     // We optimize the truncation of induction variables having constant
7300     // integer steps. The cost of these truncations is the same as the scalar
7301     // operation.
7302     if (isOptimizableIVTruncate(I, VF)) {
7303       auto *Trunc = cast<TruncInst>(I);
7304       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7305                                   Trunc->getSrcTy(), Trunc);
7306     }
7307 
7308     Type *SrcScalarTy = I->getOperand(0)->getType();
7309     Type *SrcVecTy =
7310         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7311     if (canTruncateToMinimalBitwidth(I, VF)) {
7312       // This cast is going to be shrunk. This may remove the cast or it might
7313       // turn it into slightly different cast. For example, if MinBW == 16,
7314       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7315       //
7316       // Calculate the modified src and dest types.
7317       Type *MinVecTy = VectorTy;
7318       if (I->getOpcode() == Instruction::Trunc) {
7319         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7320         VectorTy =
7321             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7322       } else if (I->getOpcode() == Instruction::ZExt ||
7323                  I->getOpcode() == Instruction::SExt) {
7324         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7325         VectorTy =
7326             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7327       }
7328     }
7329 
7330     unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
7331     return N * TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I);
7332   }
7333   case Instruction::Call: {
7334     bool NeedToScalarize;
7335     CallInst *CI = cast<CallInst>(I);
7336     unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
7337     if (getVectorIntrinsicIDForCall(CI, TLI))
7338       return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
7339     return CallCost;
7340   }
7341   default:
7342     // The cost of executing VF copies of the scalar instruction. This opcode
7343     // is unknown. Assume that it is the same as 'mul'.
7344     return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
7345            getScalarizationOverhead(I, VF, TTI);
7346   } // end of switch.
7347 }
7348 
7349 char LoopVectorize::ID = 0;
7350 
7351 static const char lv_name[] = "Loop Vectorization";
7352 
7353 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7354 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7355 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7356 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7357 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7358 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7359 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7360 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7361 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7362 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7363 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7364 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7365 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7366 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7367 
7368 namespace llvm {
7369 
7370 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
7371   return new LoopVectorize(NoUnrolling, AlwaysVectorize);
7372 }
7373 
7374 } // end namespace llvm
7375 
7376 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7377   // Check if the pointer operand of a load or store instruction is
7378   // consecutive.
7379   if (auto *Ptr = getPointerOperand(Inst))
7380     return Legal->isConsecutivePtr(Ptr);
7381   return false;
7382 }
7383 
7384 void LoopVectorizationCostModel::collectValuesToIgnore() {
7385   // Ignore ephemeral values.
7386   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7387 
7388   // Ignore type-promoting instructions we identified during reduction
7389   // detection.
7390   for (auto &Reduction : *Legal->getReductionVars()) {
7391     RecurrenceDescriptor &RedDes = Reduction.second;
7392     SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7393     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7394   }
7395   // Ignore type-casting instructions we identified during induction
7396   // detection.
7397   for (auto &Induction : *Legal->getInductionVars()) {
7398     InductionDescriptor &IndDes = Induction.second;
7399     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7400     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7401   }
7402 }
7403 
7404 VectorizationFactor
7405 LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) {
7406   // Width 1 means no vectorize, cost 0 means uncomputed cost.
7407   const VectorizationFactor NoVectorization = {1U, 0U};
7408   Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize);
7409   if (!MaybeMaxVF.hasValue()) // Cases considered too costly to vectorize.
7410     return NoVectorization;
7411 
7412   if (UserVF) {
7413     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7414     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
7415     // Collect the instructions (and their associated costs) that will be more
7416     // profitable to scalarize.
7417     CM.selectUserVectorizationFactor(UserVF);
7418     buildVPlans(UserVF, UserVF);
7419     DEBUG(printPlans(dbgs()));
7420     return {UserVF, 0};
7421   }
7422 
7423   unsigned MaxVF = MaybeMaxVF.getValue();
7424   assert(MaxVF != 0 && "MaxVF is zero.");
7425 
7426   for (unsigned VF = 1; VF <= MaxVF; VF *= 2) {
7427     // Collect Uniform and Scalar instructions after vectorization with VF.
7428     CM.collectUniformsAndScalars(VF);
7429 
7430     // Collect the instructions (and their associated costs) that will be more
7431     // profitable to scalarize.
7432     if (VF > 1)
7433       CM.collectInstsToScalarize(VF);
7434   }
7435 
7436   buildVPlans(1, MaxVF);
7437   DEBUG(printPlans(dbgs()));
7438   if (MaxVF == 1)
7439     return NoVectorization;
7440 
7441   // Select the optimal vectorization factor.
7442   return CM.selectVectorizationFactor(MaxVF);
7443 }
7444 
7445 void LoopVectorizationPlanner::setBestPlan(unsigned VF, unsigned UF) {
7446   DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF << '\n');
7447   BestVF = VF;
7448   BestUF = UF;
7449 
7450   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
7451     return !Plan->hasVF(VF);
7452   });
7453   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
7454 }
7455 
7456 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
7457                                            DominatorTree *DT) {
7458   // Perform the actual loop transformation.
7459 
7460   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7461   VPCallbackILV CallbackILV(ILV);
7462 
7463   VPTransformState State{BestVF, BestUF,      LI,
7464                          DT,     ILV.Builder, ILV.VectorLoopValueMap,
7465                          &ILV,   CallbackILV};
7466   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7467 
7468   //===------------------------------------------------===//
7469   //
7470   // Notice: any optimization or new instruction that go
7471   // into the code below should also be implemented in
7472   // the cost-model.
7473   //
7474   //===------------------------------------------------===//
7475 
7476   // 2. Copy and widen instructions from the old loop into the new loop.
7477   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
7478   VPlans.front()->execute(&State);
7479 
7480   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7481   //    predication, updating analyses.
7482   ILV.fixVectorizedLoop();
7483 }
7484 
7485 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7486     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7487   BasicBlock *Latch = OrigLoop->getLoopLatch();
7488 
7489   // We create new control-flow for the vectorized loop, so the original
7490   // condition will be dead after vectorization if it's only used by the
7491   // branch.
7492   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
7493   if (Cmp && Cmp->hasOneUse())
7494     DeadInstructions.insert(Cmp);
7495 
7496   // We create new "steps" for induction variable updates to which the original
7497   // induction variables map. An original update instruction will be dead if
7498   // all its users except the induction variable are dead.
7499   for (auto &Induction : *Legal->getInductionVars()) {
7500     PHINode *Ind = Induction.first;
7501     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7502     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
7503           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7504         }))
7505       DeadInstructions.insert(IndUpdate);
7506 
7507     // We record as "Dead" also the type-casting instructions we had identified
7508     // during induction analysis. We don't need any handling for them in the
7509     // vectorized loop because we have proven that, under a proper runtime
7510     // test guarding the vectorized loop, the value of the phi, and the casted
7511     // value of the phi, are the same. The last instruction in this casting chain
7512     // will get its scalar/vector/widened def from the scalar/vector/widened def
7513     // of the respective phi node. Any other casts in the induction def-use chain
7514     // have no other uses outside the phi update chain, and will be ignored.
7515     InductionDescriptor &IndDes = Induction.second;
7516     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7517     DeadInstructions.insert(Casts.begin(), Casts.end());
7518   }
7519 }
7520 
7521 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
7522 
7523 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7524 
7525 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
7526                                         Instruction::BinaryOps BinOp) {
7527   // When unrolling and the VF is 1, we only need to add a simple scalar.
7528   Type *Ty = Val->getType();
7529   assert(!Ty->isVectorTy() && "Val must be a scalar");
7530 
7531   if (Ty->isFloatingPointTy()) {
7532     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
7533 
7534     // Floating point operations had to be 'fast' to enable the unrolling.
7535     Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
7536     return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
7537   }
7538   Constant *C = ConstantInt::get(Ty, StartIdx);
7539   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
7540 }
7541 
7542 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7543   SmallVector<Metadata *, 4> MDs;
7544   // Reserve first location for self reference to the LoopID metadata node.
7545   MDs.push_back(nullptr);
7546   bool IsUnrollMetadata = false;
7547   MDNode *LoopID = L->getLoopID();
7548   if (LoopID) {
7549     // First find existing loop unrolling disable metadata.
7550     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7551       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7552       if (MD) {
7553         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7554         IsUnrollMetadata =
7555             S && S->getString().startswith("llvm.loop.unroll.disable");
7556       }
7557       MDs.push_back(LoopID->getOperand(i));
7558     }
7559   }
7560 
7561   if (!IsUnrollMetadata) {
7562     // Add runtime unroll disable metadata.
7563     LLVMContext &Context = L->getHeader()->getContext();
7564     SmallVector<Metadata *, 1> DisableOperands;
7565     DisableOperands.push_back(
7566         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7567     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7568     MDs.push_back(DisableNode);
7569     MDNode *NewLoopID = MDNode::get(Context, MDs);
7570     // Set operand 0 to refer to the loop id itself.
7571     NewLoopID->replaceOperandWith(0, NewLoopID);
7572     L->setLoopID(NewLoopID);
7573   }
7574 }
7575 
7576 bool LoopVectorizationPlanner::getDecisionAndClampRange(
7577     const std::function<bool(unsigned)> &Predicate, VFRange &Range) {
7578   assert(Range.End > Range.Start && "Trying to test an empty VF range.");
7579   bool PredicateAtRangeStart = Predicate(Range.Start);
7580 
7581   for (unsigned TmpVF = Range.Start * 2; TmpVF < Range.End; TmpVF *= 2)
7582     if (Predicate(TmpVF) != PredicateAtRangeStart) {
7583       Range.End = TmpVF;
7584       break;
7585     }
7586 
7587   return PredicateAtRangeStart;
7588 }
7589 
7590 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
7591 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
7592 /// of VF's starting at a given VF and extending it as much as possible. Each
7593 /// vectorization decision can potentially shorten this sub-range during
7594 /// buildVPlan().
7595 void LoopVectorizationPlanner::buildVPlans(unsigned MinVF, unsigned MaxVF) {
7596 
7597   // Collect conditions feeding internal conditional branches; they need to be
7598   // represented in VPlan for it to model masking.
7599   SmallPtrSet<Value *, 1> NeedDef;
7600 
7601   auto *Latch = OrigLoop->getLoopLatch();
7602   for (BasicBlock *BB : OrigLoop->blocks()) {
7603     if (BB == Latch)
7604       continue;
7605     BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
7606     if (Branch && Branch->isConditional())
7607       NeedDef.insert(Branch->getCondition());
7608   }
7609 
7610   for (unsigned VF = MinVF; VF < MaxVF + 1;) {
7611     VFRange SubRange = {VF, MaxVF + 1};
7612     VPlans.push_back(buildVPlan(SubRange, NeedDef));
7613     VF = SubRange.End;
7614   }
7615 }
7616 
7617 VPValue *LoopVectorizationPlanner::createEdgeMask(BasicBlock *Src,
7618                                                   BasicBlock *Dst,
7619                                                   VPlanPtr &Plan) {
7620   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
7621 
7622   // Look for cached value.
7623   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
7624   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
7625   if (ECEntryIt != EdgeMaskCache.end())
7626     return ECEntryIt->second;
7627 
7628   VPValue *SrcMask = createBlockInMask(Src, Plan);
7629 
7630   // The terminator has to be a branch inst!
7631   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
7632   assert(BI && "Unexpected terminator found");
7633 
7634   if (!BI->isConditional())
7635     return EdgeMaskCache[Edge] = SrcMask;
7636 
7637   VPValue *EdgeMask = Plan->getVPValue(BI->getCondition());
7638   assert(EdgeMask && "No Edge Mask found for condition");
7639 
7640   if (BI->getSuccessor(0) != Dst)
7641     EdgeMask = Builder.createNot(EdgeMask);
7642 
7643   if (SrcMask) // Otherwise block in-mask is all-one, no need to AND.
7644     EdgeMask = Builder.createAnd(EdgeMask, SrcMask);
7645 
7646   return EdgeMaskCache[Edge] = EdgeMask;
7647 }
7648 
7649 VPValue *LoopVectorizationPlanner::createBlockInMask(BasicBlock *BB,
7650                                                      VPlanPtr &Plan) {
7651   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
7652 
7653   // Look for cached value.
7654   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
7655   if (BCEntryIt != BlockMaskCache.end())
7656     return BCEntryIt->second;
7657 
7658   // All-one mask is modelled as no-mask following the convention for masked
7659   // load/store/gather/scatter. Initialize BlockMask to no-mask.
7660   VPValue *BlockMask = nullptr;
7661 
7662   // Loop incoming mask is all-one.
7663   if (OrigLoop->getHeader() == BB)
7664     return BlockMaskCache[BB] = BlockMask;
7665 
7666   // This is the block mask. We OR all incoming edges.
7667   for (auto *Predecessor : predecessors(BB)) {
7668     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
7669     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
7670       return BlockMaskCache[BB] = EdgeMask;
7671 
7672     if (!BlockMask) { // BlockMask has its initialized nullptr value.
7673       BlockMask = EdgeMask;
7674       continue;
7675     }
7676 
7677     BlockMask = Builder.createOr(BlockMask, EdgeMask);
7678   }
7679 
7680   return BlockMaskCache[BB] = BlockMask;
7681 }
7682 
7683 VPInterleaveRecipe *
7684 LoopVectorizationPlanner::tryToInterleaveMemory(Instruction *I,
7685                                                 VFRange &Range) {
7686   const InterleaveGroup *IG = Legal->getInterleavedAccessGroup(I);
7687   if (!IG)
7688     return nullptr;
7689 
7690   // Now check if IG is relevant for VF's in the given range.
7691   auto isIGMember = [&](Instruction *I) -> std::function<bool(unsigned)> {
7692     return [=](unsigned VF) -> bool {
7693       return (VF >= 2 && // Query is illegal for VF == 1
7694               CM.getWideningDecision(I, VF) ==
7695                   LoopVectorizationCostModel::CM_Interleave);
7696     };
7697   };
7698   if (!getDecisionAndClampRange(isIGMember(I), Range))
7699     return nullptr;
7700 
7701   // I is a member of an InterleaveGroup for VF's in the (possibly trimmed)
7702   // range. If it's the primary member of the IG construct a VPInterleaveRecipe.
7703   // Otherwise, it's an adjunct member of the IG, do not construct any Recipe.
7704   assert(I == IG->getInsertPos() &&
7705          "Generating a recipe for an adjunct member of an interleave group");
7706 
7707   return new VPInterleaveRecipe(IG);
7708 }
7709 
7710 VPWidenMemoryInstructionRecipe *
7711 LoopVectorizationPlanner::tryToWidenMemory(Instruction *I, VFRange &Range,
7712                                            VPlanPtr &Plan) {
7713   if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
7714     return nullptr;
7715 
7716   auto willWiden = [&](unsigned VF) -> bool {
7717     if (VF == 1)
7718       return false;
7719     if (CM.isScalarAfterVectorization(I, VF) ||
7720         CM.isProfitableToScalarize(I, VF))
7721       return false;
7722     LoopVectorizationCostModel::InstWidening Decision =
7723         CM.getWideningDecision(I, VF);
7724     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
7725            "CM decision should be taken at this point.");
7726     assert(Decision != LoopVectorizationCostModel::CM_Interleave &&
7727            "Interleave memory opportunity should be caught earlier.");
7728     return Decision != LoopVectorizationCostModel::CM_Scalarize;
7729   };
7730 
7731   if (!getDecisionAndClampRange(willWiden, Range))
7732     return nullptr;
7733 
7734   VPValue *Mask = nullptr;
7735   if (Legal->isMaskRequired(I))
7736     Mask = createBlockInMask(I->getParent(), Plan);
7737 
7738   return new VPWidenMemoryInstructionRecipe(*I, Mask);
7739 }
7740 
7741 VPWidenIntOrFpInductionRecipe *
7742 LoopVectorizationPlanner::tryToOptimizeInduction(Instruction *I,
7743                                                  VFRange &Range) {
7744   if (PHINode *Phi = dyn_cast<PHINode>(I)) {
7745     // Check if this is an integer or fp induction. If so, build the recipe that
7746     // produces its scalar and vector values.
7747     InductionDescriptor II = Legal->getInductionVars()->lookup(Phi);
7748     if (II.getKind() == InductionDescriptor::IK_IntInduction ||
7749         II.getKind() == InductionDescriptor::IK_FpInduction)
7750       return new VPWidenIntOrFpInductionRecipe(Phi);
7751 
7752     return nullptr;
7753   }
7754 
7755   // Optimize the special case where the source is a constant integer
7756   // induction variable. Notice that we can only optimize the 'trunc' case
7757   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
7758   // (c) other casts depend on pointer size.
7759 
7760   // Determine whether \p K is a truncation based on an induction variable that
7761   // can be optimized.
7762   auto isOptimizableIVTruncate =
7763       [&](Instruction *K) -> std::function<bool(unsigned)> {
7764     return
7765         [=](unsigned VF) -> bool { return CM.isOptimizableIVTruncate(K, VF); };
7766   };
7767 
7768   if (isa<TruncInst>(I) &&
7769       getDecisionAndClampRange(isOptimizableIVTruncate(I), Range))
7770     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
7771                                              cast<TruncInst>(I));
7772   return nullptr;
7773 }
7774 
7775 VPBlendRecipe *
7776 LoopVectorizationPlanner::tryToBlend(Instruction *I, VPlanPtr &Plan) {
7777   PHINode *Phi = dyn_cast<PHINode>(I);
7778   if (!Phi || Phi->getParent() == OrigLoop->getHeader())
7779     return nullptr;
7780 
7781   // We know that all PHIs in non-header blocks are converted into selects, so
7782   // we don't have to worry about the insertion order and we can just use the
7783   // builder. At this point we generate the predication tree. There may be
7784   // duplications since this is a simple recursive scan, but future
7785   // optimizations will clean it up.
7786 
7787   SmallVector<VPValue *, 2> Masks;
7788   unsigned NumIncoming = Phi->getNumIncomingValues();
7789   for (unsigned In = 0; In < NumIncoming; In++) {
7790     VPValue *EdgeMask =
7791       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
7792     assert((EdgeMask || NumIncoming == 1) &&
7793            "Multiple predecessors with one having a full mask");
7794     if (EdgeMask)
7795       Masks.push_back(EdgeMask);
7796   }
7797   return new VPBlendRecipe(Phi, Masks);
7798 }
7799 
7800 bool LoopVectorizationPlanner::tryToWiden(Instruction *I, VPBasicBlock *VPBB,
7801                                           VFRange &Range) {
7802   if (Legal->isScalarWithPredication(I))
7803     return false;
7804 
7805   auto IsVectorizableOpcode = [](unsigned Opcode) {
7806     switch (Opcode) {
7807     case Instruction::Add:
7808     case Instruction::And:
7809     case Instruction::AShr:
7810     case Instruction::BitCast:
7811     case Instruction::Br:
7812     case Instruction::Call:
7813     case Instruction::FAdd:
7814     case Instruction::FCmp:
7815     case Instruction::FDiv:
7816     case Instruction::FMul:
7817     case Instruction::FPExt:
7818     case Instruction::FPToSI:
7819     case Instruction::FPToUI:
7820     case Instruction::FPTrunc:
7821     case Instruction::FRem:
7822     case Instruction::FSub:
7823     case Instruction::GetElementPtr:
7824     case Instruction::ICmp:
7825     case Instruction::IntToPtr:
7826     case Instruction::Load:
7827     case Instruction::LShr:
7828     case Instruction::Mul:
7829     case Instruction::Or:
7830     case Instruction::PHI:
7831     case Instruction::PtrToInt:
7832     case Instruction::SDiv:
7833     case Instruction::Select:
7834     case Instruction::SExt:
7835     case Instruction::Shl:
7836     case Instruction::SIToFP:
7837     case Instruction::SRem:
7838     case Instruction::Store:
7839     case Instruction::Sub:
7840     case Instruction::Trunc:
7841     case Instruction::UDiv:
7842     case Instruction::UIToFP:
7843     case Instruction::URem:
7844     case Instruction::Xor:
7845     case Instruction::ZExt:
7846       return true;
7847     }
7848     return false;
7849   };
7850 
7851   if (!IsVectorizableOpcode(I->getOpcode()))
7852     return false;
7853 
7854   if (CallInst *CI = dyn_cast<CallInst>(I)) {
7855     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7856     if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
7857                ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
7858       return false;
7859   }
7860 
7861   auto willWiden = [&](unsigned VF) -> bool {
7862     if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) ||
7863                              CM.isProfitableToScalarize(I, VF)))
7864       return false;
7865     if (CallInst *CI = dyn_cast<CallInst>(I)) {
7866       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7867       // The following case may be scalarized depending on the VF.
7868       // The flag shows whether we use Intrinsic or a usual Call for vectorized
7869       // version of the instruction.
7870       // Is it beneficial to perform intrinsic call compared to lib call?
7871       bool NeedToScalarize;
7872       unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
7873       bool UseVectorIntrinsic =
7874           ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
7875       return UseVectorIntrinsic || !NeedToScalarize;
7876     }
7877     if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
7878       assert(CM.getWideningDecision(I, VF) ==
7879                  LoopVectorizationCostModel::CM_Scalarize &&
7880              "Memory widening decisions should have been taken care by now");
7881       return false;
7882     }
7883     return true;
7884   };
7885 
7886   if (!getDecisionAndClampRange(willWiden, Range))
7887     return false;
7888 
7889   // Success: widen this instruction. We optimize the common case where
7890   // consecutive instructions can be represented by a single recipe.
7891   if (!VPBB->empty()) {
7892     VPWidenRecipe *LastWidenRecipe = dyn_cast<VPWidenRecipe>(&VPBB->back());
7893     if (LastWidenRecipe && LastWidenRecipe->appendInstruction(I))
7894       return true;
7895   }
7896 
7897   VPBB->appendRecipe(new VPWidenRecipe(I));
7898   return true;
7899 }
7900 
7901 VPBasicBlock *LoopVectorizationPlanner::handleReplication(
7902     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
7903     DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
7904     VPlanPtr &Plan) {
7905   bool IsUniform = getDecisionAndClampRange(
7906       [&](unsigned VF) { return CM.isUniformAfterVectorization(I, VF); },
7907       Range);
7908 
7909   bool IsPredicated = Legal->isScalarWithPredication(I);
7910   auto *Recipe = new VPReplicateRecipe(I, IsUniform, IsPredicated);
7911 
7912   // Find if I uses a predicated instruction. If so, it will use its scalar
7913   // value. Avoid hoisting the insert-element which packs the scalar value into
7914   // a vector value, as that happens iff all users use the vector value.
7915   for (auto &Op : I->operands())
7916     if (auto *PredInst = dyn_cast<Instruction>(Op))
7917       if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
7918         PredInst2Recipe[PredInst]->setAlsoPack(false);
7919 
7920   // Finalize the recipe for Instr, first if it is not predicated.
7921   if (!IsPredicated) {
7922     DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
7923     VPBB->appendRecipe(Recipe);
7924     return VPBB;
7925   }
7926   DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
7927   assert(VPBB->getSuccessors().empty() &&
7928          "VPBB has successors when handling predicated replication.");
7929   // Record predicated instructions for above packing optimizations.
7930   PredInst2Recipe[I] = Recipe;
7931   VPBlockBase *Region =
7932     VPBB->setOneSuccessor(createReplicateRegion(I, Recipe, Plan));
7933   return cast<VPBasicBlock>(Region->setOneSuccessor(new VPBasicBlock()));
7934 }
7935 
7936 VPRegionBlock *
7937 LoopVectorizationPlanner::createReplicateRegion(Instruction *Instr,
7938                                                 VPRecipeBase *PredRecipe,
7939                                                 VPlanPtr &Plan) {
7940   // Instructions marked for predication are replicated and placed under an
7941   // if-then construct to prevent side-effects.
7942 
7943   // Generate recipes to compute the block mask for this region.
7944   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
7945 
7946   // Build the triangular if-then region.
7947   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
7948   assert(Instr->getParent() && "Predicated instruction not in any basic block");
7949   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
7950   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
7951   auto *PHIRecipe =
7952       Instr->getType()->isVoidTy() ? nullptr : new VPPredInstPHIRecipe(Instr);
7953   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
7954   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
7955   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
7956 
7957   // Note: first set Entry as region entry and then connect successors starting
7958   // from it in order, to propagate the "parent" of each VPBasicBlock.
7959   Entry->setTwoSuccessors(Pred, Exit);
7960   Pred->setOneSuccessor(Exit);
7961 
7962   return Region;
7963 }
7964 
7965 LoopVectorizationPlanner::VPlanPtr
7966 LoopVectorizationPlanner::buildVPlan(VFRange &Range,
7967                                      const SmallPtrSetImpl<Value *> &NeedDef) {
7968   EdgeMaskCache.clear();
7969   BlockMaskCache.clear();
7970   DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
7971   DenseMap<Instruction *, Instruction *> SinkAfterInverse;
7972 
7973   // Collect instructions from the original loop that will become trivially dead
7974   // in the vectorized loop. We don't need to vectorize these instructions. For
7975   // example, original induction update instructions can become dead because we
7976   // separately emit induction "steps" when generating code for the new loop.
7977   // Similarly, we create a new latch condition when setting up the structure
7978   // of the new loop, so the old one can become dead.
7979   SmallPtrSet<Instruction *, 4> DeadInstructions;
7980   collectTriviallyDeadInstructions(DeadInstructions);
7981 
7982   // Hold a mapping from predicated instructions to their recipes, in order to
7983   // fix their AlsoPack behavior if a user is determined to replicate and use a
7984   // scalar instead of vector value.
7985   DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
7986 
7987   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
7988   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
7989   auto Plan = llvm::make_unique<VPlan>(VPBB);
7990 
7991   // Represent values that will have defs inside VPlan.
7992   for (Value *V : NeedDef)
7993     Plan->addVPValue(V);
7994 
7995   // Scan the body of the loop in a topological order to visit each basic block
7996   // after having visited its predecessor basic blocks.
7997   LoopBlocksDFS DFS(OrigLoop);
7998   DFS.perform(LI);
7999 
8000   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8001     // Relevant instructions from basic block BB will be grouped into VPRecipe
8002     // ingredients and fill a new VPBasicBlock.
8003     unsigned VPBBsForBB = 0;
8004     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
8005     VPBB->setOneSuccessor(FirstVPBBForBB);
8006     VPBB = FirstVPBBForBB;
8007     Builder.setInsertPoint(VPBB);
8008 
8009     std::vector<Instruction *> Ingredients;
8010 
8011     // Organize the ingredients to vectorize from current basic block in the
8012     // right order.
8013     for (Instruction &I : *BB) {
8014       Instruction *Instr = &I;
8015 
8016       // First filter out irrelevant instructions, to ensure no recipes are
8017       // built for them.
8018       if (isa<BranchInst>(Instr) || isa<DbgInfoIntrinsic>(Instr) ||
8019           DeadInstructions.count(Instr))
8020         continue;
8021 
8022       // I is a member of an InterleaveGroup for Range.Start. If it's an adjunct
8023       // member of the IG, do not construct any Recipe for it.
8024       const InterleaveGroup *IG = Legal->getInterleavedAccessGroup(Instr);
8025       if (IG && Instr != IG->getInsertPos() &&
8026           Range.Start >= 2 && // Query is illegal for VF == 1
8027           CM.getWideningDecision(Instr, Range.Start) ==
8028               LoopVectorizationCostModel::CM_Interleave) {
8029         if (SinkAfterInverse.count(Instr))
8030           Ingredients.push_back(SinkAfterInverse.find(Instr)->second);
8031         continue;
8032       }
8033 
8034       // Move instructions to handle first-order recurrences, step 1: avoid
8035       // handling this instruction until after we've handled the instruction it
8036       // should follow.
8037       auto SAIt = SinkAfter.find(Instr);
8038       if (SAIt != SinkAfter.end()) {
8039         DEBUG(dbgs() << "Sinking" << *SAIt->first << " after" << *SAIt->second
8040                      << " to vectorize a 1st order recurrence.\n");
8041         SinkAfterInverse[SAIt->second] = Instr;
8042         continue;
8043       }
8044 
8045       Ingredients.push_back(Instr);
8046 
8047       // Move instructions to handle first-order recurrences, step 2: push the
8048       // instruction to be sunk at its insertion point.
8049       auto SAInvIt = SinkAfterInverse.find(Instr);
8050       if (SAInvIt != SinkAfterInverse.end())
8051         Ingredients.push_back(SAInvIt->second);
8052     }
8053 
8054     // Introduce each ingredient into VPlan.
8055     for (Instruction *Instr : Ingredients) {
8056       VPRecipeBase *Recipe = nullptr;
8057 
8058       // Check if Instr should belong to an interleave memory recipe, or already
8059       // does. In the latter case Instr is irrelevant.
8060       if ((Recipe = tryToInterleaveMemory(Instr, Range))) {
8061         VPBB->appendRecipe(Recipe);
8062         continue;
8063       }
8064 
8065       // Check if Instr is a memory operation that should be widened.
8066       if ((Recipe = tryToWidenMemory(Instr, Range, Plan))) {
8067         VPBB->appendRecipe(Recipe);
8068         continue;
8069       }
8070 
8071       // Check if Instr should form some PHI recipe.
8072       if ((Recipe = tryToOptimizeInduction(Instr, Range))) {
8073         VPBB->appendRecipe(Recipe);
8074         continue;
8075       }
8076       if ((Recipe = tryToBlend(Instr, Plan))) {
8077         VPBB->appendRecipe(Recipe);
8078         continue;
8079       }
8080       if (PHINode *Phi = dyn_cast<PHINode>(Instr)) {
8081         VPBB->appendRecipe(new VPWidenPHIRecipe(Phi));
8082         continue;
8083       }
8084 
8085       // Check if Instr is to be widened by a general VPWidenRecipe, after
8086       // having first checked for specific widening recipes that deal with
8087       // Interleave Groups, Inductions and Phi nodes.
8088       if (tryToWiden(Instr, VPBB, Range))
8089         continue;
8090 
8091       // Otherwise, if all widening options failed, Instruction is to be
8092       // replicated. This may create a successor for VPBB.
8093       VPBasicBlock *NextVPBB =
8094         handleReplication(Instr, Range, VPBB, PredInst2Recipe, Plan);
8095       if (NextVPBB != VPBB) {
8096         VPBB = NextVPBB;
8097         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8098                                     : "");
8099       }
8100     }
8101   }
8102 
8103   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
8104   // may also be empty, such as the last one VPBB, reflecting original
8105   // basic-blocks with no recipes.
8106   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
8107   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
8108   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
8109   PreEntry->disconnectSuccessor(Entry);
8110   delete PreEntry;
8111 
8112   std::string PlanName;
8113   raw_string_ostream RSO(PlanName);
8114   unsigned VF = Range.Start;
8115   Plan->addVF(VF);
8116   RSO << "Initial VPlan for VF={" << VF;
8117   for (VF *= 2; VF < Range.End; VF *= 2) {
8118     Plan->addVF(VF);
8119     RSO << "," << VF;
8120   }
8121   RSO << "},UF>=1";
8122   RSO.flush();
8123   Plan->setName(PlanName);
8124 
8125   return Plan;
8126 }
8127 
8128 Value* LoopVectorizationPlanner::VPCallbackILV::
8129 getOrCreateVectorValues(Value *V, unsigned Part) {
8130       return ILV.getOrCreateVectorValue(V, Part);
8131 }
8132 
8133 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent) const {
8134   O << " +\n"
8135     << Indent << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
8136   IG->getInsertPos()->printAsOperand(O, false);
8137   O << "\\l\"";
8138   for (unsigned i = 0; i < IG->getFactor(); ++i)
8139     if (Instruction *I = IG->getMember(i))
8140       O << " +\n"
8141         << Indent << "\"  " << VPlanIngredient(I) << " " << i << "\\l\"";
8142 }
8143 
8144 void VPWidenRecipe::execute(VPTransformState &State) {
8145   for (auto &Instr : make_range(Begin, End))
8146     State.ILV->widenInstruction(Instr);
8147 }
8148 
8149 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
8150   assert(!State.Instance && "Int or FP induction being replicated.");
8151   State.ILV->widenIntOrFpInduction(IV, Trunc);
8152 }
8153 
8154 void VPWidenPHIRecipe::execute(VPTransformState &State) {
8155   State.ILV->widenPHIInstruction(Phi, State.UF, State.VF);
8156 }
8157 
8158 void VPBlendRecipe::execute(VPTransformState &State) {
8159   State.ILV->setDebugLocFromInst(State.Builder, Phi);
8160   // We know that all PHIs in non-header blocks are converted into
8161   // selects, so we don't have to worry about the insertion order and we
8162   // can just use the builder.
8163   // At this point we generate the predication tree. There may be
8164   // duplications since this is a simple recursive scan, but future
8165   // optimizations will clean it up.
8166 
8167   unsigned NumIncoming = Phi->getNumIncomingValues();
8168 
8169   assert((User || NumIncoming == 1) &&
8170          "Multiple predecessors with predecessors having a full mask");
8171   // Generate a sequence of selects of the form:
8172   // SELECT(Mask3, In3,
8173   //      SELECT(Mask2, In2,
8174   //                   ( ...)))
8175   InnerLoopVectorizer::VectorParts Entry(State.UF);
8176   for (unsigned In = 0; In < NumIncoming; ++In) {
8177     for (unsigned Part = 0; Part < State.UF; ++Part) {
8178       // We might have single edge PHIs (blocks) - use an identity
8179       // 'select' for the first PHI operand.
8180       Value *In0 =
8181           State.ILV->getOrCreateVectorValue(Phi->getIncomingValue(In), Part);
8182       if (In == 0)
8183         Entry[Part] = In0; // Initialize with the first incoming value.
8184       else {
8185         // Select between the current value and the previous incoming edge
8186         // based on the incoming mask.
8187         Value *Cond = State.get(User->getOperand(In), Part);
8188         Entry[Part] =
8189             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
8190       }
8191     }
8192   }
8193   for (unsigned Part = 0; Part < State.UF; ++Part)
8194     State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
8195 }
8196 
8197 void VPInterleaveRecipe::execute(VPTransformState &State) {
8198   assert(!State.Instance && "Interleave group being replicated.");
8199   State.ILV->vectorizeInterleaveGroup(IG->getInsertPos());
8200 }
8201 
8202 void VPReplicateRecipe::execute(VPTransformState &State) {
8203   if (State.Instance) { // Generate a single instance.
8204     State.ILV->scalarizeInstruction(Ingredient, *State.Instance, IsPredicated);
8205     // Insert scalar instance packing it into a vector.
8206     if (AlsoPack && State.VF > 1) {
8207       // If we're constructing lane 0, initialize to start from undef.
8208       if (State.Instance->Lane == 0) {
8209         Value *Undef =
8210             UndefValue::get(VectorType::get(Ingredient->getType(), State.VF));
8211         State.ValueMap.setVectorValue(Ingredient, State.Instance->Part, Undef);
8212       }
8213       State.ILV->packScalarIntoVectorValue(Ingredient, *State.Instance);
8214     }
8215     return;
8216   }
8217 
8218   // Generate scalar instances for all VF lanes of all UF parts, unless the
8219   // instruction is uniform inwhich case generate only the first lane for each
8220   // of the UF parts.
8221   unsigned EndLane = IsUniform ? 1 : State.VF;
8222   for (unsigned Part = 0; Part < State.UF; ++Part)
8223     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
8224       State.ILV->scalarizeInstruction(Ingredient, {Part, Lane}, IsPredicated);
8225 }
8226 
8227 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
8228   assert(State.Instance && "Branch on Mask works only on single instance.");
8229 
8230   unsigned Part = State.Instance->Part;
8231   unsigned Lane = State.Instance->Lane;
8232 
8233   Value *ConditionBit = nullptr;
8234   if (!User) // Block in mask is all-one.
8235     ConditionBit = State.Builder.getTrue();
8236   else {
8237     VPValue *BlockInMask = User->getOperand(0);
8238     ConditionBit = State.get(BlockInMask, Part);
8239     if (ConditionBit->getType()->isVectorTy())
8240       ConditionBit = State.Builder.CreateExtractElement(
8241           ConditionBit, State.Builder.getInt32(Lane));
8242   }
8243 
8244   // Replace the temporary unreachable terminator with a new conditional branch,
8245   // whose two destinations will be set later when they are created.
8246   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
8247   assert(isa<UnreachableInst>(CurrentTerminator) &&
8248          "Expected to replace unreachable terminator with conditional branch.");
8249   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
8250   CondBr->setSuccessor(0, nullptr);
8251   ReplaceInstWithInst(CurrentTerminator, CondBr);
8252 }
8253 
8254 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
8255   assert(State.Instance && "Predicated instruction PHI works per instance.");
8256   Instruction *ScalarPredInst = cast<Instruction>(
8257       State.ValueMap.getScalarValue(PredInst, *State.Instance));
8258   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
8259   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
8260   assert(PredicatingBB && "Predicated block has no single predecessor.");
8261 
8262   // By current pack/unpack logic we need to generate only a single phi node: if
8263   // a vector value for the predicated instruction exists at this point it means
8264   // the instruction has vector users only, and a phi for the vector value is
8265   // needed. In this case the recipe of the predicated instruction is marked to
8266   // also do that packing, thereby "hoisting" the insert-element sequence.
8267   // Otherwise, a phi node for the scalar value is needed.
8268   unsigned Part = State.Instance->Part;
8269   if (State.ValueMap.hasVectorValue(PredInst, Part)) {
8270     Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
8271     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
8272     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
8273     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
8274     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
8275     State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
8276   } else {
8277     Type *PredInstType = PredInst->getType();
8278     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
8279     Phi->addIncoming(UndefValue::get(ScalarPredInst->getType()), PredicatingBB);
8280     Phi->addIncoming(ScalarPredInst, PredicatedBB);
8281     State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
8282   }
8283 }
8284 
8285 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
8286   if (!User)
8287     return State.ILV->vectorizeMemoryInstruction(&Instr);
8288 
8289   // Last (and currently only) operand is a mask.
8290   InnerLoopVectorizer::VectorParts MaskValues(State.UF);
8291   VPValue *Mask = User->getOperand(User->getNumOperands() - 1);
8292   for (unsigned Part = 0; Part < State.UF; ++Part)
8293     MaskValues[Part] = State.get(Mask, Part);
8294   State.ILV->vectorizeMemoryInstruction(&Instr, &MaskValues);
8295 }
8296 
8297 bool LoopVectorizePass::processLoop(Loop *L) {
8298   assert(L->empty() && "Only process inner loops.");
8299 
8300 #ifndef NDEBUG
8301   const std::string DebugLocStr = getDebugLocString(L);
8302 #endif /* NDEBUG */
8303 
8304   DEBUG(dbgs() << "\nLV: Checking a loop in \""
8305                << L->getHeader()->getParent()->getName() << "\" from "
8306                << DebugLocStr << "\n");
8307 
8308   LoopVectorizeHints Hints(L, DisableUnrolling, *ORE);
8309 
8310   DEBUG(dbgs() << "LV: Loop hints:"
8311                << " force="
8312                << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
8313                        ? "disabled"
8314                        : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
8315                               ? "enabled"
8316                               : "?"))
8317                << " width=" << Hints.getWidth()
8318                << " unroll=" << Hints.getInterleave() << "\n");
8319 
8320   // Function containing loop
8321   Function *F = L->getHeader()->getParent();
8322 
8323   // Looking at the diagnostic output is the only way to determine if a loop
8324   // was vectorized (other than looking at the IR or machine code), so it
8325   // is important to generate an optimization remark for each loop. Most of
8326   // these messages are generated as OptimizationRemarkAnalysis. Remarks
8327   // generated as OptimizationRemark and OptimizationRemarkMissed are
8328   // less verbose reporting vectorized loops and unvectorized loops that may
8329   // benefit from vectorization, respectively.
8330 
8331   if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
8332     DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
8333     return false;
8334   }
8335 
8336   PredicatedScalarEvolution PSE(*SE, *L);
8337 
8338   // Check if it is legal to vectorize the loop.
8339   LoopVectorizationRequirements Requirements(*ORE);
8340   LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE,
8341                                 &Requirements, &Hints, DB, AC);
8342   if (!LVL.canVectorize()) {
8343     DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
8344     emitMissedWarning(F, L, Hints, ORE);
8345     return false;
8346   }
8347 
8348   // Check the function attributes to find out if this function should be
8349   // optimized for size.
8350   bool OptForSize =
8351       Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
8352 
8353   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
8354   // count by optimizing for size, to minimize overheads.
8355   // Prefer constant trip counts over profile data, over upper bound estimate.
8356   unsigned ExpectedTC = 0;
8357   bool HasExpectedTC = false;
8358   if (const SCEVConstant *ConstExits =
8359       dyn_cast<SCEVConstant>(SE->getBackedgeTakenCount(L))) {
8360     const APInt &ExitsCount = ConstExits->getAPInt();
8361     // We are interested in small values for ExpectedTC. Skip over those that
8362     // can't fit an unsigned.
8363     if (ExitsCount.ult(std::numeric_limits<unsigned>::max())) {
8364       ExpectedTC = static_cast<unsigned>(ExitsCount.getZExtValue()) + 1;
8365       HasExpectedTC = true;
8366     }
8367   }
8368   // ExpectedTC may be large because it's bound by a variable. Check
8369   // profiling information to validate we should vectorize.
8370   if (!HasExpectedTC && LoopVectorizeWithBlockFrequency) {
8371     auto EstimatedTC = getLoopEstimatedTripCount(L);
8372     if (EstimatedTC) {
8373       ExpectedTC = *EstimatedTC;
8374       HasExpectedTC = true;
8375     }
8376   }
8377   if (!HasExpectedTC) {
8378     ExpectedTC = SE->getSmallConstantMaxTripCount(L);
8379     HasExpectedTC = (ExpectedTC > 0);
8380   }
8381 
8382   if (HasExpectedTC && ExpectedTC < TinyTripCountVectorThreshold) {
8383     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
8384                  << "This loop is worth vectorizing only if no scalar "
8385                  << "iteration overheads are incurred.");
8386     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
8387       DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
8388     else {
8389       DEBUG(dbgs() << "\n");
8390       // Loops with a very small trip count are considered for vectorization
8391       // under OptForSize, thereby making sure the cost of their loop body is
8392       // dominant, free of runtime guards and scalar iteration overheads.
8393       OptForSize = true;
8394     }
8395   }
8396 
8397   // Check the function attributes to see if implicit floats are allowed.
8398   // FIXME: This check doesn't seem possibly correct -- what if the loop is
8399   // an integer loop and the vector instructions selected are purely integer
8400   // vector instructions?
8401   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
8402     DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
8403                     "attribute is used.\n");
8404     ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(),
8405                                    "NoImplicitFloat", L)
8406               << "loop not vectorized due to NoImplicitFloat attribute");
8407     emitMissedWarning(F, L, Hints, ORE);
8408     return false;
8409   }
8410 
8411   // Check if the target supports potentially unsafe FP vectorization.
8412   // FIXME: Add a check for the type of safety issue (denormal, signaling)
8413   // for the target we're vectorizing for, to make sure none of the
8414   // additional fp-math flags can help.
8415   if (Hints.isPotentiallyUnsafe() &&
8416       TTI->isFPVectorizationPotentiallyUnsafe()) {
8417     DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
8418     ORE->emit(
8419         createMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
8420         << "loop not vectorized due to unsafe FP support.");
8421     emitMissedWarning(F, L, Hints, ORE);
8422     return false;
8423   }
8424 
8425   // Use the cost model.
8426   LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
8427                                 &Hints);
8428   CM.collectValuesToIgnore();
8429 
8430   // Use the planner for vectorization.
8431   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM);
8432 
8433   // Get user vectorization factor.
8434   unsigned UserVF = Hints.getWidth();
8435 
8436   // Plan how to best vectorize, return the best VF and its cost.
8437   VectorizationFactor VF = LVP.plan(OptForSize, UserVF);
8438 
8439   // Select the interleave count.
8440   unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
8441 
8442   // Get user interleave count.
8443   unsigned UserIC = Hints.getInterleave();
8444 
8445   // Identify the diagnostic messages that should be produced.
8446   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
8447   bool VectorizeLoop = true, InterleaveLoop = true;
8448   if (Requirements.doesNotMeet(F, L, Hints)) {
8449     DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
8450                     "requirements.\n");
8451     emitMissedWarning(F, L, Hints, ORE);
8452     return false;
8453   }
8454 
8455   if (VF.Width == 1) {
8456     DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
8457     VecDiagMsg = std::make_pair(
8458         "VectorizationNotBeneficial",
8459         "the cost-model indicates that vectorization is not beneficial");
8460     VectorizeLoop = false;
8461   }
8462 
8463   if (IC == 1 && UserIC <= 1) {
8464     // Tell the user interleaving is not beneficial.
8465     DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
8466     IntDiagMsg = std::make_pair(
8467         "InterleavingNotBeneficial",
8468         "the cost-model indicates that interleaving is not beneficial");
8469     InterleaveLoop = false;
8470     if (UserIC == 1) {
8471       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
8472       IntDiagMsg.second +=
8473           " and is explicitly disabled or interleave count is set to 1";
8474     }
8475   } else if (IC > 1 && UserIC == 1) {
8476     // Tell the user interleaving is beneficial, but it explicitly disabled.
8477     DEBUG(dbgs()
8478           << "LV: Interleaving is beneficial but is explicitly disabled.");
8479     IntDiagMsg = std::make_pair(
8480         "InterleavingBeneficialButDisabled",
8481         "the cost-model indicates that interleaving is beneficial "
8482         "but is explicitly disabled or interleave count is set to 1");
8483     InterleaveLoop = false;
8484   }
8485 
8486   // Override IC if user provided an interleave count.
8487   IC = UserIC > 0 ? UserIC : IC;
8488 
8489   // Emit diagnostic messages, if any.
8490   const char *VAPassName = Hints.vectorizeAnalysisPassName();
8491   if (!VectorizeLoop && !InterleaveLoop) {
8492     // Do not vectorize or interleaving the loop.
8493     ORE->emit([&]() {
8494       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
8495                                       L->getStartLoc(), L->getHeader())
8496              << VecDiagMsg.second;
8497     });
8498     ORE->emit([&]() {
8499       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
8500                                       L->getStartLoc(), L->getHeader())
8501              << IntDiagMsg.second;
8502     });
8503     return false;
8504   } else if (!VectorizeLoop && InterleaveLoop) {
8505     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
8506     ORE->emit([&]() {
8507       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
8508                                         L->getStartLoc(), L->getHeader())
8509              << VecDiagMsg.second;
8510     });
8511   } else if (VectorizeLoop && !InterleaveLoop) {
8512     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
8513                  << DebugLocStr << '\n');
8514     ORE->emit([&]() {
8515       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
8516                                         L->getStartLoc(), L->getHeader())
8517              << IntDiagMsg.second;
8518     });
8519   } else if (VectorizeLoop && InterleaveLoop) {
8520     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
8521                  << DebugLocStr << '\n');
8522     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
8523   }
8524 
8525   LVP.setBestPlan(VF.Width, IC);
8526 
8527   using namespace ore;
8528 
8529   if (!VectorizeLoop) {
8530     assert(IC > 1 && "interleave count should not be 1 or 0");
8531     // If we decided that it is not legal to vectorize the loop, then
8532     // interleave it.
8533     InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
8534                                &CM);
8535     LVP.executePlan(Unroller, DT);
8536 
8537     ORE->emit([&]() {
8538       return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
8539                                 L->getHeader())
8540              << "interleaved loop (interleaved count: "
8541              << NV("InterleaveCount", IC) << ")";
8542     });
8543   } else {
8544     // If we decided that it is *legal* to vectorize the loop, then do it.
8545     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
8546                            &LVL, &CM);
8547     LVP.executePlan(LB, DT);
8548     ++LoopsVectorized;
8549 
8550     // Add metadata to disable runtime unrolling a scalar loop when there are
8551     // no runtime checks about strides and memory. A scalar loop that is
8552     // rarely used is not worth unrolling.
8553     if (!LB.areSafetyChecksAdded())
8554       AddRuntimeUnrollDisableMetaData(L);
8555 
8556     // Report the vectorization decision.
8557     ORE->emit([&]() {
8558       return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
8559                                 L->getHeader())
8560              << "vectorized loop (vectorization width: "
8561              << NV("VectorizationFactor", VF.Width)
8562              << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
8563     });
8564   }
8565 
8566   // Mark the loop as already vectorized to avoid vectorizing again.
8567   Hints.setAlreadyVectorized();
8568 
8569   DEBUG(verifyFunction(*L->getHeader()->getParent()));
8570   return true;
8571 }
8572 
8573 bool LoopVectorizePass::runImpl(
8574     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
8575     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
8576     DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
8577     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
8578     OptimizationRemarkEmitter &ORE_) {
8579   SE = &SE_;
8580   LI = &LI_;
8581   TTI = &TTI_;
8582   DT = &DT_;
8583   BFI = &BFI_;
8584   TLI = TLI_;
8585   AA = &AA_;
8586   AC = &AC_;
8587   GetLAA = &GetLAA_;
8588   DB = &DB_;
8589   ORE = &ORE_;
8590 
8591   // Don't attempt if
8592   // 1. the target claims to have no vector registers, and
8593   // 2. interleaving won't help ILP.
8594   //
8595   // The second condition is necessary because, even if the target has no
8596   // vector registers, loop vectorization may still enable scalar
8597   // interleaving.
8598   if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
8599     return false;
8600 
8601   bool Changed = false;
8602 
8603   // The vectorizer requires loops to be in simplified form.
8604   // Since simplification may add new inner loops, it has to run before the
8605   // legality and profitability checks. This means running the loop vectorizer
8606   // will simplify all loops, regardless of whether anything end up being
8607   // vectorized.
8608   for (auto &L : *LI)
8609     Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */);
8610 
8611   // Build up a worklist of inner-loops to vectorize. This is necessary as
8612   // the act of vectorizing or partially unrolling a loop creates new loops
8613   // and can invalidate iterators across the loops.
8614   SmallVector<Loop *, 8> Worklist;
8615 
8616   for (Loop *L : *LI)
8617     addAcyclicInnerLoop(*L, Worklist);
8618 
8619   LoopsAnalyzed += Worklist.size();
8620 
8621   // Now walk the identified inner loops.
8622   while (!Worklist.empty()) {
8623     Loop *L = Worklist.pop_back_val();
8624 
8625     // For the inner loops we actually process, form LCSSA to simplify the
8626     // transform.
8627     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
8628 
8629     Changed |= processLoop(L);
8630   }
8631 
8632   // Process each loop nest in the function.
8633   return Changed;
8634 }
8635 
8636 PreservedAnalyses LoopVectorizePass::run(Function &F,
8637                                          FunctionAnalysisManager &AM) {
8638     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
8639     auto &LI = AM.getResult<LoopAnalysis>(F);
8640     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
8641     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
8642     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
8643     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
8644     auto &AA = AM.getResult<AAManager>(F);
8645     auto &AC = AM.getResult<AssumptionAnalysis>(F);
8646     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
8647     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8648 
8649     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
8650     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
8651         [&](Loop &L) -> const LoopAccessInfo & {
8652       LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, nullptr};
8653       return LAM.getResult<LoopAccessAnalysis>(L, AR);
8654     };
8655     bool Changed =
8656         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
8657     if (!Changed)
8658       return PreservedAnalyses::all();
8659     PreservedAnalyses PA;
8660     PA.preserve<LoopAnalysis>();
8661     PA.preserve<DominatorTreeAnalysis>();
8662     PA.preserve<BasicAA>();
8663     PA.preserve<GlobalsAA>();
8664     return PA;
8665 }
8666