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