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