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