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