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