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