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