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