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