LoopVectorize.cpp revision 66d1fa6f4b443ac9f8bcea5d1f71a73ada733a42
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#define LV_NAME "loop-vectorize"
46#define DEBUG_TYPE LV_NAME
47
48#include "llvm/Transforms/Vectorize.h"
49#include "llvm/ADT/DenseMap.h"
50#include "llvm/ADT/EquivalenceClasses.h"
51#include "llvm/ADT/MapVector.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallPtrSet.h"
54#include "llvm/ADT/SmallSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/Analysis/AliasAnalysis.h"
58#include "llvm/Analysis/Dominators.h"
59#include "llvm/Analysis/LoopInfo.h"
60#include "llvm/Analysis/LoopIterator.h"
61#include "llvm/Analysis/LoopPass.h"
62#include "llvm/Analysis/ScalarEvolution.h"
63#include "llvm/Analysis/ScalarEvolutionExpander.h"
64#include "llvm/Analysis/ScalarEvolutionExpressions.h"
65#include "llvm/Analysis/TargetTransformInfo.h"
66#include "llvm/Analysis/ValueTracking.h"
67#include "llvm/Analysis/Verifier.h"
68#include "llvm/IR/Constants.h"
69#include "llvm/IR/DataLayout.h"
70#include "llvm/IR/DerivedTypes.h"
71#include "llvm/IR/Function.h"
72#include "llvm/IR/IRBuilder.h"
73#include "llvm/IR/Instructions.h"
74#include "llvm/IR/IntrinsicInst.h"
75#include "llvm/IR/LLVMContext.h"
76#include "llvm/IR/Module.h"
77#include "llvm/IR/Type.h"
78#include "llvm/IR/Value.h"
79#include "llvm/Pass.h"
80#include "llvm/Support/CommandLine.h"
81#include "llvm/Support/Debug.h"
82#include "llvm/Support/PatternMatch.h"
83#include "llvm/Support/raw_ostream.h"
84#include "llvm/Support/ValueHandle.h"
85#include "llvm/Target/TargetLibraryInfo.h"
86#include "llvm/Transforms/Scalar.h"
87#include "llvm/Transforms/Utils/BasicBlockUtils.h"
88#include "llvm/Transforms/Utils/Local.h"
89#include <algorithm>
90#include <map>
91
92using namespace llvm;
93using namespace llvm::PatternMatch;
94
95static cl::opt<unsigned>
96VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
97                    cl::desc("Sets the SIMD width. Zero is autoselect."));
98
99static cl::opt<unsigned>
100VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
101                    cl::desc("Sets the vectorization unroll count. "
102                             "Zero is autoselect."));
103
104static cl::opt<bool>
105EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
106                   cl::desc("Enable if-conversion during vectorization."));
107
108/// We don't vectorize loops with a known constant trip count below this number.
109static cl::opt<unsigned>
110TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
111                             cl::Hidden,
112                             cl::desc("Don't vectorize loops with a constant "
113                                      "trip count that is smaller than this "
114                                      "value."));
115
116/// We don't unroll loops with a known constant trip count below this number.
117static const unsigned TinyTripCountUnrollThreshold = 128;
118
119/// When performing memory disambiguation checks at runtime do not make more
120/// than this number of comparisons.
121static const unsigned RuntimeMemoryCheckThreshold = 8;
122
123/// Maximum simd width.
124static const unsigned MaxVectorWidth = 64;
125
126/// Maximum vectorization unroll count.
127static const unsigned MaxUnrollFactor = 16;
128
129namespace {
130
131// Forward declarations.
132class LoopVectorizationLegality;
133class LoopVectorizationCostModel;
134
135/// InnerLoopVectorizer vectorizes loops which contain only one basic
136/// block to a specified vectorization factor (VF).
137/// This class performs the widening of scalars into vectors, or multiple
138/// scalars. This class also implements the following features:
139/// * It inserts an epilogue loop for handling loops that don't have iteration
140///   counts that are known to be a multiple of the vectorization factor.
141/// * It handles the code generation for reduction variables.
142/// * Scalarization (implementation using scalars) of un-vectorizable
143///   instructions.
144/// InnerLoopVectorizer does not perform any vectorization-legality
145/// checks, and relies on the caller to check for the different legality
146/// aspects. The InnerLoopVectorizer relies on the
147/// LoopVectorizationLegality class to provide information about the induction
148/// and reduction variables that were found to a given vectorization factor.
149class InnerLoopVectorizer {
150public:
151  InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
152                      DominatorTree *DT, DataLayout *DL,
153                      const TargetLibraryInfo *TLI, unsigned VecWidth,
154                      unsigned UnrollFactor)
155      : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
156        VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
157        OldInduction(0), WidenMap(UnrollFactor) {}
158
159  // Perform the actual loop widening (vectorization).
160  void vectorize(LoopVectorizationLegality *Legal) {
161    // Create a new empty loop. Unlink the old loop and connect the new one.
162    createEmptyLoop(Legal);
163    // Widen each instruction in the old loop to a new one in the new loop.
164    // Use the Legality module to find the induction and reduction variables.
165    vectorizeLoop(Legal);
166    // Register the new loop and update the analysis passes.
167    updateAnalysis();
168  }
169
170private:
171  /// A small list of PHINodes.
172  typedef SmallVector<PHINode*, 4> PhiVector;
173  /// When we unroll loops we have multiple vector values for each scalar.
174  /// This data structure holds the unrolled and vectorized values that
175  /// originated from one scalar instruction.
176  typedef SmallVector<Value*, 2> VectorParts;
177
178  // When we if-convert we need create edge masks. We have to cache values so
179  // that we don't end up with exponential recursion/IR.
180  typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
181                   VectorParts> EdgeMaskCache;
182
183  /// Add code that checks at runtime if the accessed arrays overlap.
184  /// Returns the comparator value or NULL if no check is needed.
185  Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
186                               Instruction *Loc);
187  /// Create an empty loop, based on the loop ranges of the old loop.
188  void createEmptyLoop(LoopVectorizationLegality *Legal);
189  /// Copy and widen the instructions from the old loop.
190  void vectorizeLoop(LoopVectorizationLegality *Legal);
191
192  /// A helper function that computes the predicate of the block BB, assuming
193  /// that the header block of the loop is set to True. It returns the *entry*
194  /// mask for the block BB.
195  VectorParts createBlockInMask(BasicBlock *BB);
196  /// A helper function that computes the predicate of the edge between SRC
197  /// and DST.
198  VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
199
200  /// A helper function to vectorize a single BB within the innermost loop.
201  void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
202                            PhiVector *PV);
203
204  /// Insert the new loop to the loop hierarchy and pass manager
205  /// and update the analysis passes.
206  void updateAnalysis();
207
208  /// This instruction is un-vectorizable. Implement it as a sequence
209  /// of scalars.
210  void scalarizeInstruction(Instruction *Instr);
211
212  /// Vectorize Load and Store instructions,
213  void vectorizeMemoryInstruction(Instruction *Instr,
214                                  LoopVectorizationLegality *Legal);
215
216  /// Create a broadcast instruction. This method generates a broadcast
217  /// instruction (shuffle) for loop invariant values and for the induction
218  /// value. If this is the induction variable then we extend it to N, N+1, ...
219  /// this is needed because each iteration in the loop corresponds to a SIMD
220  /// element.
221  Value *getBroadcastInstrs(Value *V);
222
223  /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
224  /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
225  /// The sequence starts at StartIndex.
226  Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
227
228  /// When we go over instructions in the basic block we rely on previous
229  /// values within the current basic block or on loop invariant values.
230  /// When we widen (vectorize) values we place them in the map. If the values
231  /// are not within the map, they have to be loop invariant, so we simply
232  /// broadcast them into a vector.
233  VectorParts &getVectorValue(Value *V);
234
235  /// Generate a shuffle sequence that will reverse the vector Vec.
236  Value *reverseVector(Value *Vec);
237
238  /// This is a helper class that holds the vectorizer state. It maps scalar
239  /// instructions to vector instructions. When the code is 'unrolled' then
240  /// then a single scalar value is mapped to multiple vector parts. The parts
241  /// are stored in the VectorPart type.
242  struct ValueMap {
243    /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
244    /// are mapped.
245    ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
246
247    /// \return True if 'Key' is saved in the Value Map.
248    bool has(Value *Key) const { return MapStorage.count(Key); }
249
250    /// Initializes a new entry in the map. Sets all of the vector parts to the
251    /// save value in 'Val'.
252    /// \return A reference to a vector with splat values.
253    VectorParts &splat(Value *Key, Value *Val) {
254      VectorParts &Entry = MapStorage[Key];
255      Entry.assign(UF, Val);
256      return Entry;
257    }
258
259    ///\return A reference to the value that is stored at 'Key'.
260    VectorParts &get(Value *Key) {
261      VectorParts &Entry = MapStorage[Key];
262      if (Entry.empty())
263        Entry.resize(UF);
264      assert(Entry.size() == UF);
265      return Entry;
266    }
267
268  private:
269    /// The unroll factor. Each entry in the map stores this number of vector
270    /// elements.
271    unsigned UF;
272
273    /// Map storage. We use std::map and not DenseMap because insertions to a
274    /// dense map invalidates its iterators.
275    std::map<Value *, VectorParts> MapStorage;
276  };
277
278  /// The original loop.
279  Loop *OrigLoop;
280  /// Scev analysis to use.
281  ScalarEvolution *SE;
282  /// Loop Info.
283  LoopInfo *LI;
284  /// Dominator Tree.
285  DominatorTree *DT;
286  /// Data Layout.
287  DataLayout *DL;
288  /// Target Library Info.
289  const TargetLibraryInfo *TLI;
290
291  /// The vectorization SIMD factor to use. Each vector will have this many
292  /// vector elements.
293  unsigned VF;
294  /// The vectorization unroll factor to use. Each scalar is vectorized to this
295  /// many different vector instructions.
296  unsigned UF;
297
298  /// The builder that we use
299  IRBuilder<> Builder;
300
301  // --- Vectorization state ---
302
303  /// The vector-loop preheader.
304  BasicBlock *LoopVectorPreHeader;
305  /// The scalar-loop preheader.
306  BasicBlock *LoopScalarPreHeader;
307  /// Middle Block between the vector and the scalar.
308  BasicBlock *LoopMiddleBlock;
309  ///The ExitBlock of the scalar loop.
310  BasicBlock *LoopExitBlock;
311  ///The vector loop body.
312  BasicBlock *LoopVectorBody;
313  ///The scalar loop body.
314  BasicBlock *LoopScalarBody;
315  /// A list of all bypass blocks. The first block is the entry of the loop.
316  SmallVector<BasicBlock *, 4> LoopBypassBlocks;
317
318  /// The new Induction variable which was added to the new block.
319  PHINode *Induction;
320  /// The induction variable of the old basic block.
321  PHINode *OldInduction;
322  /// Holds the extended (to the widest induction type) start index.
323  Value *ExtendedIdx;
324  /// Maps scalars to widened vectors.
325  ValueMap WidenMap;
326  EdgeMaskCache MaskCache;
327};
328
329/// \brief Look for a meaningful debug location on the instruction or it's
330/// operands.
331static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
332  if (!I)
333    return I;
334
335  DebugLoc Empty;
336  if (I->getDebugLoc() != Empty)
337    return I;
338
339  for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
340    if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
341      if (OpInst->getDebugLoc() != Empty)
342        return OpInst;
343  }
344
345  return I;
346}
347
348/// \brief Set the debug location in the builder using the debug location in the
349/// instruction.
350static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
351  if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
352    B.SetCurrentDebugLocation(Inst->getDebugLoc());
353  else
354    B.SetCurrentDebugLocation(DebugLoc());
355}
356
357/// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
358/// to what vectorization factor.
359/// This class does not look at the profitability of vectorization, only the
360/// legality. This class has two main kinds of checks:
361/// * Memory checks - The code in canVectorizeMemory checks if vectorization
362///   will change the order of memory accesses in a way that will change the
363///   correctness of the program.
364/// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
365/// checks for a number of different conditions, such as the availability of a
366/// single induction variable, that all types are supported and vectorize-able,
367/// etc. This code reflects the capabilities of InnerLoopVectorizer.
368/// This class is also used by InnerLoopVectorizer for identifying
369/// induction variable and the different reduction variables.
370class LoopVectorizationLegality {
371public:
372  LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
373                            DominatorTree *DT, TargetLibraryInfo *TLI)
374      : TheLoop(L), SE(SE), DL(DL), DT(DT), TLI(TLI),
375        Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
376        MaxSafeDepDistBytes(-1U) {}
377
378  /// This enum represents the kinds of reductions that we support.
379  enum ReductionKind {
380    RK_NoReduction, ///< Not a reduction.
381    RK_IntegerAdd,  ///< Sum of integers.
382    RK_IntegerMult, ///< Product of integers.
383    RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
384    RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
385    RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
386    RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
387    RK_FloatAdd,    ///< Sum of floats.
388    RK_FloatMult,   ///< Product of floats.
389    RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
390  };
391
392  /// This enum represents the kinds of inductions that we support.
393  enum InductionKind {
394    IK_NoInduction,         ///< Not an induction variable.
395    IK_IntInduction,        ///< Integer induction variable. Step = 1.
396    IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
397    IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
398    IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
399  };
400
401  // This enum represents the kind of minmax reduction.
402  enum MinMaxReductionKind {
403    MRK_Invalid,
404    MRK_UIntMin,
405    MRK_UIntMax,
406    MRK_SIntMin,
407    MRK_SIntMax,
408    MRK_FloatMin,
409    MRK_FloatMax
410  };
411
412  /// This POD struct holds information about reduction variables.
413  struct ReductionDescriptor {
414    ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
415      Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
416
417    ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
418                        MinMaxReductionKind MK)
419        : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
420
421    // The starting value of the reduction.
422    // It does not have to be zero!
423    TrackingVH<Value> StartValue;
424    // The instruction who's value is used outside the loop.
425    Instruction *LoopExitInstr;
426    // The kind of the reduction.
427    ReductionKind Kind;
428    // If this a min/max reduction the kind of reduction.
429    MinMaxReductionKind MinMaxKind;
430  };
431
432  /// This POD struct holds information about a potential reduction operation.
433  struct ReductionInstDesc {
434    ReductionInstDesc(bool IsRedux, Instruction *I) :
435      IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
436
437    ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
438      IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
439
440    // Is this instruction a reduction candidate.
441    bool IsReduction;
442    // The last instruction in a min/max pattern (select of the select(icmp())
443    // pattern), or the current reduction instruction otherwise.
444    Instruction *PatternLastInst;
445    // If this is a min/max pattern the comparison predicate.
446    MinMaxReductionKind MinMaxKind;
447  };
448
449  // This POD struct holds information about the memory runtime legality
450  // check that a group of pointers do not overlap.
451  struct RuntimePointerCheck {
452    RuntimePointerCheck() : Need(false) {}
453
454    /// Reset the state of the pointer runtime information.
455    void reset() {
456      Need = false;
457      Pointers.clear();
458      Starts.clear();
459      Ends.clear();
460    }
461
462    /// Insert a pointer and calculate the start and end SCEVs.
463    void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
464                unsigned DepSetId);
465
466    /// This flag indicates if we need to add the runtime check.
467    bool Need;
468    /// Holds the pointers that we need to check.
469    SmallVector<TrackingVH<Value>, 2> Pointers;
470    /// Holds the pointer value at the beginning of the loop.
471    SmallVector<const SCEV*, 2> Starts;
472    /// Holds the pointer value at the end of the loop.
473    SmallVector<const SCEV*, 2> Ends;
474    /// Holds the information if this pointer is used for writing to memory.
475    SmallVector<bool, 2> IsWritePtr;
476    /// Holds the id of the set of pointers that could be dependent because of a
477    /// shared underlying object.
478    SmallVector<unsigned, 2> DependencySetId;
479  };
480
481  /// A POD for saving information about induction variables.
482  struct InductionInfo {
483    InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
484    InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
485    /// Start value.
486    TrackingVH<Value> StartValue;
487    /// Induction kind.
488    InductionKind IK;
489  };
490
491  /// ReductionList contains the reduction descriptors for all
492  /// of the reductions that were found in the loop.
493  typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
494
495  /// InductionList saves induction variables and maps them to the
496  /// induction descriptor.
497  typedef MapVector<PHINode*, InductionInfo> InductionList;
498
499  /// Returns true if it is legal to vectorize this loop.
500  /// This does not mean that it is profitable to vectorize this
501  /// loop, only that it is legal to do so.
502  bool canVectorize();
503
504  /// Returns the Induction variable.
505  PHINode *getInduction() { return Induction; }
506
507  /// Returns the reduction variables found in the loop.
508  ReductionList *getReductionVars() { return &Reductions; }
509
510  /// Returns the induction variables found in the loop.
511  InductionList *getInductionVars() { return &Inductions; }
512
513  /// Returns the widest induction type.
514  Type *getWidestInductionType() { return WidestIndTy; }
515
516  /// Returns True if V is an induction variable in this loop.
517  bool isInductionVariable(const Value *V);
518
519  /// Return true if the block BB needs to be predicated in order for the loop
520  /// to be vectorized.
521  bool blockNeedsPredication(BasicBlock *BB);
522
523  /// Check if this  pointer is consecutive when vectorizing. This happens
524  /// when the last index of the GEP is the induction variable, or that the
525  /// pointer itself is an induction variable.
526  /// This check allows us to vectorize A[idx] into a wide load/store.
527  /// Returns:
528  /// 0 - Stride is unknown or non consecutive.
529  /// 1 - Address is consecutive.
530  /// -1 - Address is consecutive, and decreasing.
531  int isConsecutivePtr(Value *Ptr);
532
533  /// Returns true if the value V is uniform within the loop.
534  bool isUniform(Value *V);
535
536  /// Returns true if this instruction will remain scalar after vectorization.
537  bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
538
539  /// Returns the information that we collected about runtime memory check.
540  RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
541
542  /// This function returns the identity element (or neutral element) for
543  /// the operation K.
544  static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
545
546  unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
547
548private:
549  /// Check if a single basic block loop is vectorizable.
550  /// At this point we know that this is a loop with a constant trip count
551  /// and we only need to check individual instructions.
552  bool canVectorizeInstrs();
553
554  /// When we vectorize loops we may change the order in which
555  /// we read and write from memory. This method checks if it is
556  /// legal to vectorize the code, considering only memory constrains.
557  /// Returns true if the loop is vectorizable
558  bool canVectorizeMemory();
559
560  /// Return true if we can vectorize this loop using the IF-conversion
561  /// transformation.
562  bool canVectorizeWithIfConvert();
563
564  /// Collect the variables that need to stay uniform after vectorization.
565  void collectLoopUniforms();
566
567  /// Return true if all of the instructions in the block can be speculatively
568  /// executed. \p SafePtrs is a list of addresses that are known to be legal
569  /// and we know that we can read from them without segfault.
570  bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
571
572  /// Returns True, if 'Phi' is the kind of reduction variable for type
573  /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
574  bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
575  /// Returns a struct describing if the instruction 'I' can be a reduction
576  /// variable of type 'Kind'. If the reduction is a min/max pattern of
577  /// select(icmp()) this function advances the instruction pointer 'I' from the
578  /// compare instruction to the select instruction and stores this pointer in
579  /// 'PatternLastInst' member of the returned struct.
580  ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
581                                     ReductionInstDesc &Desc);
582  /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
583  /// pattern corresponding to a min(X, Y) or max(X, Y).
584  static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
585                                                    ReductionInstDesc &Prev);
586  /// Returns the induction kind of Phi. This function may return NoInduction
587  /// if the PHI is not an induction variable.
588  InductionKind isInductionVariable(PHINode *Phi);
589
590  /// The loop that we evaluate.
591  Loop *TheLoop;
592  /// Scev analysis.
593  ScalarEvolution *SE;
594  /// DataLayout analysis.
595  DataLayout *DL;
596  /// Dominators.
597  DominatorTree *DT;
598  /// Target Library Info.
599  TargetLibraryInfo *TLI;
600
601  //  ---  vectorization state --- //
602
603  /// Holds the integer induction variable. This is the counter of the
604  /// loop.
605  PHINode *Induction;
606  /// Holds the reduction variables.
607  ReductionList Reductions;
608  /// Holds all of the induction variables that we found in the loop.
609  /// Notice that inductions don't need to start at zero and that induction
610  /// variables can be pointers.
611  InductionList Inductions;
612  /// Holds the widest induction type encountered.
613  Type *WidestIndTy;
614
615  /// Allowed outside users. This holds the reduction
616  /// vars which can be accessed from outside the loop.
617  SmallPtrSet<Value*, 4> AllowedExit;
618  /// This set holds the variables which are known to be uniform after
619  /// vectorization.
620  SmallPtrSet<Instruction*, 4> Uniforms;
621  /// We need to check that all of the pointers in this list are disjoint
622  /// at runtime.
623  RuntimePointerCheck PtrRtCheck;
624  /// Can we assume the absence of NaNs.
625  bool HasFunNoNaNAttr;
626
627  unsigned MaxSafeDepDistBytes;
628};
629
630/// LoopVectorizationCostModel - estimates the expected speedups due to
631/// vectorization.
632/// In many cases vectorization is not profitable. This can happen because of
633/// a number of reasons. In this class we mainly attempt to predict the
634/// expected speedup/slowdowns due to the supported instruction set. We use the
635/// TargetTransformInfo to query the different backends for the cost of
636/// different operations.
637class LoopVectorizationCostModel {
638public:
639  LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
640                             LoopVectorizationLegality *Legal,
641                             const TargetTransformInfo &TTI,
642                             DataLayout *DL, const TargetLibraryInfo *TLI)
643      : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
644
645  /// Information about vectorization costs
646  struct VectorizationFactor {
647    unsigned Width; // Vector width with best cost
648    unsigned Cost; // Cost of the loop with that width
649  };
650  /// \return The most profitable vectorization factor and the cost of that VF.
651  /// This method checks every power of two up to VF. If UserVF is not ZERO
652  /// then this vectorization factor will be selected if vectorization is
653  /// possible.
654  VectorizationFactor selectVectorizationFactor(bool OptForSize,
655                                                unsigned UserVF);
656
657  /// \return The size (in bits) of the widest type in the code that
658  /// needs to be vectorized. We ignore values that remain scalar such as
659  /// 64 bit loop indices.
660  unsigned getWidestType();
661
662  /// \return The most profitable unroll factor.
663  /// If UserUF is non-zero then this method finds the best unroll-factor
664  /// based on register pressure and other parameters.
665  /// VF and LoopCost are the selected vectorization factor and the cost of the
666  /// selected VF.
667  unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
668                              unsigned LoopCost);
669
670  /// \brief A struct that represents some properties of the register usage
671  /// of a loop.
672  struct RegisterUsage {
673    /// Holds the number of loop invariant values that are used in the loop.
674    unsigned LoopInvariantRegs;
675    /// Holds the maximum number of concurrent live intervals in the loop.
676    unsigned MaxLocalUsers;
677    /// Holds the number of instructions in the loop.
678    unsigned NumInstructions;
679  };
680
681  /// \return  information about the register usage of the loop.
682  RegisterUsage calculateRegisterUsage();
683
684private:
685  /// Returns the expected execution cost. The unit of the cost does
686  /// not matter because we use the 'cost' units to compare different
687  /// vector widths. The cost that is returned is *not* normalized by
688  /// the factor width.
689  unsigned expectedCost(unsigned VF);
690
691  /// Returns the execution time cost of an instruction for a given vector
692  /// width. Vector width of one means scalar.
693  unsigned getInstructionCost(Instruction *I, unsigned VF);
694
695  /// A helper function for converting Scalar types to vector types.
696  /// If the incoming type is void, we return void. If the VF is 1, we return
697  /// the scalar type.
698  static Type* ToVectorTy(Type *Scalar, unsigned VF);
699
700  /// Returns whether the instruction is a load or store and will be a emitted
701  /// as a vector operation.
702  bool isConsecutiveLoadOrStore(Instruction *I);
703
704  /// The loop that we evaluate.
705  Loop *TheLoop;
706  /// Scev analysis.
707  ScalarEvolution *SE;
708  /// Loop Info analysis.
709  LoopInfo *LI;
710  /// Vectorization legality.
711  LoopVectorizationLegality *Legal;
712  /// Vector target information.
713  const TargetTransformInfo &TTI;
714  /// Target data layout information.
715  DataLayout *DL;
716  /// Target Library Info.
717  const TargetLibraryInfo *TLI;
718};
719
720/// Utility class for getting and setting loop vectorizer hints in the form
721/// of loop metadata.
722struct LoopVectorizeHints {
723  /// Vectorization width.
724  unsigned Width;
725  /// Vectorization unroll factor.
726  unsigned Unroll;
727
728  LoopVectorizeHints(const Loop *L)
729  : Width(VectorizationFactor)
730  , Unroll(VectorizationUnroll)
731  , LoopID(L->getLoopID()) {
732    getHints(L);
733    // The command line options override any loop metadata except for when
734    // width == 1 which is used to indicate the loop is already vectorized.
735    if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
736      Width = VectorizationFactor;
737    if (VectorizationUnroll.getNumOccurrences() > 0)
738      Unroll = VectorizationUnroll;
739  }
740
741  /// Return the loop vectorizer metadata prefix.
742  static StringRef Prefix() { return "llvm.vectorizer."; }
743
744  MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
745    SmallVector<Value*, 2> Vals;
746    Vals.push_back(MDString::get(Context, Name));
747    Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
748    return MDNode::get(Context, Vals);
749  }
750
751  /// Mark the loop L as already vectorized by setting the width to 1.
752  void setAlreadyVectorized(Loop *L) {
753    LLVMContext &Context = L->getHeader()->getContext();
754
755    Width = 1;
756
757    // Create a new loop id with one more operand for the already_vectorized
758    // hint. If the loop already has a loop id then copy the existing operands.
759    SmallVector<Value*, 4> Vals(1);
760    if (LoopID)
761      for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
762        Vals.push_back(LoopID->getOperand(i));
763
764    Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
765
766    MDNode *NewLoopID = MDNode::get(Context, Vals);
767    // Set operand 0 to refer to the loop id itself.
768    NewLoopID->replaceOperandWith(0, NewLoopID);
769
770    L->setLoopID(NewLoopID);
771    if (LoopID)
772      LoopID->replaceAllUsesWith(NewLoopID);
773
774    LoopID = NewLoopID;
775  }
776
777private:
778  MDNode *LoopID;
779
780  /// Find hints specified in the loop metadata.
781  void getHints(const Loop *L) {
782    if (!LoopID)
783      return;
784
785    // First operand should refer to the loop id itself.
786    assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
787    assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
788
789    for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
790      const MDString *S = 0;
791      SmallVector<Value*, 4> Args;
792
793      // The expected hint is either a MDString or a MDNode with the first
794      // operand a MDString.
795      if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
796        if (!MD || MD->getNumOperands() == 0)
797          continue;
798        S = dyn_cast<MDString>(MD->getOperand(0));
799        for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
800          Args.push_back(MD->getOperand(i));
801      } else {
802        S = dyn_cast<MDString>(LoopID->getOperand(i));
803        assert(Args.size() == 0 && "too many arguments for MDString");
804      }
805
806      if (!S)
807        continue;
808
809      // Check if the hint starts with the vectorizer prefix.
810      StringRef Hint = S->getString();
811      if (!Hint.startswith(Prefix()))
812        continue;
813      // Remove the prefix.
814      Hint = Hint.substr(Prefix().size(), StringRef::npos);
815
816      if (Args.size() == 1)
817        getHint(Hint, Args[0]);
818    }
819  }
820
821  // Check string hint with one operand.
822  void getHint(StringRef Hint, Value *Arg) {
823    const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
824    if (!C) return;
825    unsigned Val = C->getZExtValue();
826
827    if (Hint == "width") {
828      assert(isPowerOf2_32(Val) && Val <= MaxVectorWidth &&
829             "Invalid width metadata");
830      Width = Val;
831    } else if (Hint == "unroll") {
832      assert(isPowerOf2_32(Val) && Val <= MaxUnrollFactor &&
833             "Invalid unroll metadata");
834      Unroll = Val;
835    } else
836      DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint);
837  }
838};
839
840/// The LoopVectorize Pass.
841struct LoopVectorize : public LoopPass {
842  /// Pass identification, replacement for typeid
843  static char ID;
844
845  explicit LoopVectorize() : LoopPass(ID) {
846    initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
847  }
848
849  ScalarEvolution *SE;
850  DataLayout *DL;
851  LoopInfo *LI;
852  TargetTransformInfo *TTI;
853  DominatorTree *DT;
854  TargetLibraryInfo *TLI;
855
856  virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
857    // We only vectorize innermost loops.
858    if (!L->empty())
859      return false;
860
861    SE = &getAnalysis<ScalarEvolution>();
862    DL = getAnalysisIfAvailable<DataLayout>();
863    LI = &getAnalysis<LoopInfo>();
864    TTI = &getAnalysis<TargetTransformInfo>();
865    DT = &getAnalysis<DominatorTree>();
866    TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
867
868    if (DL == NULL) {
869      DEBUG(dbgs() << "LV: Not vectorizing because of missing data layout");
870      return false;
871    }
872
873    DEBUG(dbgs() << "LV: Checking a loop in \"" <<
874          L->getHeader()->getParent()->getName() << "\"\n");
875
876    LoopVectorizeHints Hints(L);
877
878    if (Hints.Width == 1) {
879      DEBUG(dbgs() << "LV: Not vectorizing.\n");
880      return false;
881    }
882
883    // Check if it is legal to vectorize the loop.
884    LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
885    if (!LVL.canVectorize()) {
886      DEBUG(dbgs() << "LV: Not vectorizing.\n");
887      return false;
888    }
889
890    // Use the cost model.
891    LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
892
893    // Check the function attributes to find out if this function should be
894    // optimized for size.
895    Function *F = L->getHeader()->getParent();
896    Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
897    Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
898    unsigned FnIndex = AttributeSet::FunctionIndex;
899    bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
900    bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
901
902    if (NoFloat) {
903      DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
904            "attribute is used.\n");
905      return false;
906    }
907
908    // Select the optimal vectorization factor.
909    LoopVectorizationCostModel::VectorizationFactor VF;
910    VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
911    // Select the unroll factor.
912    unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
913                                        VF.Cost);
914
915    if (VF.Width == 1) {
916      DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
917      return false;
918    }
919
920    DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
921          F->getParent()->getModuleIdentifier()<<"\n");
922    DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
923
924    // If we decided that it is *legal* to vectorize the loop then do it.
925    InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
926    LB.vectorize(&LVL);
927
928    // Mark the loop as already vectorized to avoid vectorizing again.
929    Hints.setAlreadyVectorized(L);
930
931    DEBUG(verifyFunction(*L->getHeader()->getParent()));
932    return true;
933  }
934
935  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
936    LoopPass::getAnalysisUsage(AU);
937    AU.addRequiredID(LoopSimplifyID);
938    AU.addRequiredID(LCSSAID);
939    AU.addRequired<DominatorTree>();
940    AU.addRequired<LoopInfo>();
941    AU.addRequired<ScalarEvolution>();
942    AU.addRequired<TargetTransformInfo>();
943    AU.addPreserved<LoopInfo>();
944    AU.addPreserved<DominatorTree>();
945  }
946
947};
948
949} // end anonymous namespace
950
951//===----------------------------------------------------------------------===//
952// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
953// LoopVectorizationCostModel.
954//===----------------------------------------------------------------------===//
955
956void
957LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
958                                                       Loop *Lp, Value *Ptr,
959                                                       bool WritePtr,
960                                                       unsigned DepSetId) {
961  const SCEV *Sc = SE->getSCEV(Ptr);
962  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
963  assert(AR && "Invalid addrec expression");
964  const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
965  const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
966  Pointers.push_back(Ptr);
967  Starts.push_back(AR->getStart());
968  Ends.push_back(ScEnd);
969  IsWritePtr.push_back(WritePtr);
970  DependencySetId.push_back(DepSetId);
971}
972
973Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
974  // Save the current insertion location.
975  Instruction *Loc = Builder.GetInsertPoint();
976
977  // We need to place the broadcast of invariant variables outside the loop.
978  Instruction *Instr = dyn_cast<Instruction>(V);
979  bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
980  bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
981
982  // Place the code for broadcasting invariant variables in the new preheader.
983  if (Invariant)
984    Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
985
986  // Broadcast the scalar into all locations in the vector.
987  Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
988
989  // Restore the builder insertion point.
990  if (Invariant)
991    Builder.SetInsertPoint(Loc);
992
993  return Shuf;
994}
995
996Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
997                                                 bool Negate) {
998  assert(Val->getType()->isVectorTy() && "Must be a vector");
999  assert(Val->getType()->getScalarType()->isIntegerTy() &&
1000         "Elem must be an integer");
1001  // Create the types.
1002  Type *ITy = Val->getType()->getScalarType();
1003  VectorType *Ty = cast<VectorType>(Val->getType());
1004  int VLen = Ty->getNumElements();
1005  SmallVector<Constant*, 8> Indices;
1006
1007  // Create a vector of consecutive numbers from zero to VF.
1008  for (int i = 0; i < VLen; ++i) {
1009    int64_t Idx = Negate ? (-i) : i;
1010    Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1011  }
1012
1013  // Add the consecutive indices to the vector value.
1014  Constant *Cv = ConstantVector::get(Indices);
1015  assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1016  return Builder.CreateAdd(Val, Cv, "induction");
1017}
1018
1019int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1020  assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
1021  // Make sure that the pointer does not point to structs.
1022  if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
1023    return 0;
1024
1025  // If this value is a pointer induction variable we know it is consecutive.
1026  PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1027  if (Phi && Inductions.count(Phi)) {
1028    InductionInfo II = Inductions[Phi];
1029    if (IK_PtrInduction == II.IK)
1030      return 1;
1031    else if (IK_ReversePtrInduction == II.IK)
1032      return -1;
1033  }
1034
1035  GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1036  if (!Gep)
1037    return 0;
1038
1039  unsigned NumOperands = Gep->getNumOperands();
1040  Value *LastIndex = Gep->getOperand(NumOperands - 1);
1041
1042  Value *GpPtr = Gep->getPointerOperand();
1043  // If this GEP value is a consecutive pointer induction variable and all of
1044  // the indices are constant then we know it is consecutive. We can
1045  Phi = dyn_cast<PHINode>(GpPtr);
1046  if (Phi && Inductions.count(Phi)) {
1047
1048    // Make sure that the pointer does not point to structs.
1049    PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1050    if (GepPtrType->getElementType()->isAggregateType())
1051      return 0;
1052
1053    // Make sure that all of the index operands are loop invariant.
1054    for (unsigned i = 1; i < NumOperands; ++i)
1055      if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1056        return 0;
1057
1058    InductionInfo II = Inductions[Phi];
1059    if (IK_PtrInduction == II.IK)
1060      return 1;
1061    else if (IK_ReversePtrInduction == II.IK)
1062      return -1;
1063  }
1064
1065  // Check that all of the gep indices are uniform except for the last.
1066  for (unsigned i = 0; i < NumOperands - 1; ++i)
1067    if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1068      return 0;
1069
1070  // We can emit wide load/stores only if the last index is the induction
1071  // variable.
1072  const SCEV *Last = SE->getSCEV(LastIndex);
1073  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1074    const SCEV *Step = AR->getStepRecurrence(*SE);
1075
1076    // The memory is consecutive because the last index is consecutive
1077    // and all other indices are loop invariant.
1078    if (Step->isOne())
1079      return 1;
1080    if (Step->isAllOnesValue())
1081      return -1;
1082  }
1083
1084  return 0;
1085}
1086
1087bool LoopVectorizationLegality::isUniform(Value *V) {
1088  return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1089}
1090
1091InnerLoopVectorizer::VectorParts&
1092InnerLoopVectorizer::getVectorValue(Value *V) {
1093  assert(V != Induction && "The new induction variable should not be used.");
1094  assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1095
1096  // If we have this scalar in the map, return it.
1097  if (WidenMap.has(V))
1098    return WidenMap.get(V);
1099
1100  // If this scalar is unknown, assume that it is a constant or that it is
1101  // loop invariant. Broadcast V and save the value for future uses.
1102  Value *B = getBroadcastInstrs(V);
1103  return WidenMap.splat(V, B);
1104}
1105
1106Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1107  assert(Vec->getType()->isVectorTy() && "Invalid type");
1108  SmallVector<Constant*, 8> ShuffleMask;
1109  for (unsigned i = 0; i < VF; ++i)
1110    ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1111
1112  return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1113                                     ConstantVector::get(ShuffleMask),
1114                                     "reverse");
1115}
1116
1117
1118void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
1119                                             LoopVectorizationLegality *Legal) {
1120  // Attempt to issue a wide load.
1121  LoadInst *LI = dyn_cast<LoadInst>(Instr);
1122  StoreInst *SI = dyn_cast<StoreInst>(Instr);
1123
1124  assert((LI || SI) && "Invalid Load/Store instruction");
1125
1126  Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1127  Type *DataTy = VectorType::get(ScalarDataTy, VF);
1128  Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1129  unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1130  unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1131  unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1132  unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1133
1134  if (ScalarAllocatedSize != VectorElementSize)
1135    return scalarizeInstruction(Instr);
1136
1137  // If the pointer is loop invariant or if it is non consecutive,
1138  // scalarize the load.
1139  int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1140  bool Reverse = ConsecutiveStride < 0;
1141  bool UniformLoad = LI && Legal->isUniform(Ptr);
1142  if (!ConsecutiveStride || UniformLoad)
1143    return scalarizeInstruction(Instr);
1144
1145  Constant *Zero = Builder.getInt32(0);
1146  VectorParts &Entry = WidenMap.get(Instr);
1147
1148  // Handle consecutive loads/stores.
1149  GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1150  if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1151    setDebugLocFromInst(Builder, Gep);
1152    Value *PtrOperand = Gep->getPointerOperand();
1153    Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1154    FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1155
1156    // Create the new GEP with the new induction variable.
1157    GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1158    Gep2->setOperand(0, FirstBasePtr);
1159    Gep2->setName("gep.indvar.base");
1160    Ptr = Builder.Insert(Gep2);
1161  } else if (Gep) {
1162    setDebugLocFromInst(Builder, Gep);
1163    assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1164                               OrigLoop) && "Base ptr must be invariant");
1165
1166    // The last index does not have to be the induction. It can be
1167    // consecutive and be a function of the index. For example A[I+1];
1168    unsigned NumOperands = Gep->getNumOperands();
1169    unsigned LastOperand = NumOperands - 1;
1170    // Create the new GEP with the new induction variable.
1171    GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1172
1173    for (unsigned i = 0; i < NumOperands; ++i) {
1174      Value *GepOperand = Gep->getOperand(i);
1175      Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1176
1177      // Update last index or loop invariant instruction anchored in loop.
1178      if (i == LastOperand ||
1179          (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1180        assert((i == LastOperand ||
1181               SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1182               "Must be last index or loop invariant");
1183
1184        VectorParts &GEPParts = getVectorValue(GepOperand);
1185        Value *Index = GEPParts[0];
1186        Index = Builder.CreateExtractElement(Index, Zero);
1187        Gep2->setOperand(i, Index);
1188        Gep2->setName("gep.indvar.idx");
1189      }
1190    }
1191    Ptr = Builder.Insert(Gep2);
1192  } else {
1193    // Use the induction element ptr.
1194    assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1195    setDebugLocFromInst(Builder, Ptr);
1196    VectorParts &PtrVal = getVectorValue(Ptr);
1197    Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1198  }
1199
1200  // Handle Stores:
1201  if (SI) {
1202    assert(!Legal->isUniform(SI->getPointerOperand()) &&
1203           "We do not allow storing to uniform addresses");
1204    setDebugLocFromInst(Builder, SI);
1205    // We don't want to update the value in the map as it might be used in
1206    // another expression. So don't use a reference type for "StoredVal".
1207    VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1208
1209    for (unsigned Part = 0; Part < UF; ++Part) {
1210      // Calculate the pointer for the specific unroll-part.
1211      Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1212
1213      if (Reverse) {
1214        // If we store to reverse consecutive memory locations then we need
1215        // to reverse the order of elements in the stored value.
1216        StoredVal[Part] = reverseVector(StoredVal[Part]);
1217        // If the address is consecutive but reversed, then the
1218        // wide store needs to start at the last vector element.
1219        PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1220        PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1221      }
1222
1223      Value *VecPtr = Builder.CreateBitCast(PartPtr,
1224                                            DataTy->getPointerTo(AddressSpace));
1225      Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1226    }
1227    return;
1228  }
1229
1230  // Handle loads.
1231  assert(LI && "Must have a load instruction");
1232  setDebugLocFromInst(Builder, LI);
1233  for (unsigned Part = 0; Part < UF; ++Part) {
1234    // Calculate the pointer for the specific unroll-part.
1235    Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1236
1237    if (Reverse) {
1238      // If the address is consecutive but reversed, then the
1239      // wide store needs to start at the last vector element.
1240      PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1241      PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1242    }
1243
1244    Value *VecPtr = Builder.CreateBitCast(PartPtr,
1245                                          DataTy->getPointerTo(AddressSpace));
1246    Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1247    cast<LoadInst>(LI)->setAlignment(Alignment);
1248    Entry[Part] = Reverse ? reverseVector(LI) :  LI;
1249  }
1250}
1251
1252void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1253  assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1254  // Holds vector parameters or scalars, in case of uniform vals.
1255  SmallVector<VectorParts, 4> Params;
1256
1257  setDebugLocFromInst(Builder, Instr);
1258
1259  // Find all of the vectorized parameters.
1260  for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1261    Value *SrcOp = Instr->getOperand(op);
1262
1263    // If we are accessing the old induction variable, use the new one.
1264    if (SrcOp == OldInduction) {
1265      Params.push_back(getVectorValue(SrcOp));
1266      continue;
1267    }
1268
1269    // Try using previously calculated values.
1270    Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1271
1272    // If the src is an instruction that appeared earlier in the basic block
1273    // then it should already be vectorized.
1274    if (SrcInst && OrigLoop->contains(SrcInst)) {
1275      assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1276      // The parameter is a vector value from earlier.
1277      Params.push_back(WidenMap.get(SrcInst));
1278    } else {
1279      // The parameter is a scalar from outside the loop. Maybe even a constant.
1280      VectorParts Scalars;
1281      Scalars.append(UF, SrcOp);
1282      Params.push_back(Scalars);
1283    }
1284  }
1285
1286  assert(Params.size() == Instr->getNumOperands() &&
1287         "Invalid number of operands");
1288
1289  // Does this instruction return a value ?
1290  bool IsVoidRetTy = Instr->getType()->isVoidTy();
1291
1292  Value *UndefVec = IsVoidRetTy ? 0 :
1293    UndefValue::get(VectorType::get(Instr->getType(), VF));
1294  // Create a new entry in the WidenMap and initialize it to Undef or Null.
1295  VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1296
1297  // For each vector unroll 'part':
1298  for (unsigned Part = 0; Part < UF; ++Part) {
1299    // For each scalar that we create:
1300    for (unsigned Width = 0; Width < VF; ++Width) {
1301      Instruction *Cloned = Instr->clone();
1302      if (!IsVoidRetTy)
1303        Cloned->setName(Instr->getName() + ".cloned");
1304      // Replace the operands of the cloned instrucions with extracted scalars.
1305      for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1306        Value *Op = Params[op][Part];
1307        // Param is a vector. Need to extract the right lane.
1308        if (Op->getType()->isVectorTy())
1309          Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1310        Cloned->setOperand(op, Op);
1311      }
1312
1313      // Place the cloned scalar in the new loop.
1314      Builder.Insert(Cloned);
1315
1316      // If the original scalar returns a value we need to place it in a vector
1317      // so that future users will be able to use it.
1318      if (!IsVoidRetTy)
1319        VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1320                                                       Builder.getInt32(Width));
1321    }
1322  }
1323}
1324
1325Instruction *
1326InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1327                                     Instruction *Loc) {
1328  LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1329  Legal->getRuntimePointerCheck();
1330
1331  if (!PtrRtCheck->Need)
1332    return NULL;
1333
1334  unsigned NumPointers = PtrRtCheck->Pointers.size();
1335  SmallVector<TrackingVH<Value> , 2> Starts;
1336  SmallVector<TrackingVH<Value> , 2> Ends;
1337
1338  SCEVExpander Exp(*SE, "induction");
1339
1340  // Use this type for pointer arithmetic.
1341  Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1342
1343  for (unsigned i = 0; i < NumPointers; ++i) {
1344    Value *Ptr = PtrRtCheck->Pointers[i];
1345    const SCEV *Sc = SE->getSCEV(Ptr);
1346
1347    if (SE->isLoopInvariant(Sc, OrigLoop)) {
1348      DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1349            *Ptr <<"\n");
1350      Starts.push_back(Ptr);
1351      Ends.push_back(Ptr);
1352    } else {
1353      DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1354
1355      Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1356      Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1357      Starts.push_back(Start);
1358      Ends.push_back(End);
1359    }
1360  }
1361
1362  IRBuilder<> ChkBuilder(Loc);
1363  // Our instructions might fold to a constant.
1364  Value *MemoryRuntimeCheck = 0;
1365  for (unsigned i = 0; i < NumPointers; ++i) {
1366    for (unsigned j = i+1; j < NumPointers; ++j) {
1367      // No need to check if two readonly pointers intersect.
1368      if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1369        continue;
1370
1371      // Only need to check pointers between two different dependency sets.
1372      if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1373       continue;
1374
1375      Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1376      Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1377      Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy, "bc");
1378      Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy, "bc");
1379
1380      Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1381      Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1382      Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1383      if (MemoryRuntimeCheck)
1384        IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1385                                         "conflict.rdx");
1386      MemoryRuntimeCheck = IsConflict;
1387    }
1388  }
1389
1390  // We have to do this trickery because the IRBuilder might fold the check to a
1391  // constant expression in which case there is no Instruction anchored in a
1392  // the block.
1393  LLVMContext &Ctx = Loc->getContext();
1394  Instruction * Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1395                                                  ConstantInt::getTrue(Ctx));
1396  ChkBuilder.Insert(Check, "memcheck.conflict");
1397  return Check;
1398}
1399
1400void
1401InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1402  /*
1403   In this function we generate a new loop. The new loop will contain
1404   the vectorized instructions while the old loop will continue to run the
1405   scalar remainder.
1406
1407       [ ] <-- vector loop bypass (may consist of multiple blocks).
1408     /  |
1409    /   v
1410   |   [ ]     <-- vector pre header.
1411   |    |
1412   |    v
1413   |   [  ] \
1414   |   [  ]_|   <-- vector loop.
1415   |    |
1416    \   v
1417      >[ ]   <--- middle-block.
1418     /  |
1419    /   v
1420   |   [ ]     <--- new preheader.
1421   |    |
1422   |    v
1423   |   [ ] \
1424   |   [ ]_|   <-- old scalar loop to handle remainder.
1425    \   |
1426     \  v
1427      >[ ]     <-- exit block.
1428   ...
1429   */
1430
1431  BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1432  BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1433  BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1434  assert(ExitBlock && "Must have an exit block");
1435
1436  // Some loops have a single integer induction variable, while other loops
1437  // don't. One example is c++ iterators that often have multiple pointer
1438  // induction variables. In the code below we also support a case where we
1439  // don't have a single induction variable.
1440  OldInduction = Legal->getInduction();
1441  Type *IdxTy = Legal->getWidestInductionType();
1442
1443  // Find the loop boundaries.
1444  const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1445  assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1446
1447  // Get the total trip count from the count by adding 1.
1448  ExitCount = SE->getAddExpr(ExitCount,
1449                             SE->getConstant(ExitCount->getType(), 1));
1450
1451  // Expand the trip count and place the new instructions in the preheader.
1452  // Notice that the pre-header does not change, only the loop body.
1453  SCEVExpander Exp(*SE, "induction");
1454
1455  // Count holds the overall loop count (N).
1456  Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1457                                   BypassBlock->getTerminator());
1458
1459  // The loop index does not have to start at Zero. Find the original start
1460  // value from the induction PHI node. If we don't have an induction variable
1461  // then we know that it starts at zero.
1462  Builder.SetInsertPoint(BypassBlock->getTerminator());
1463  Value *StartIdx = ExtendedIdx = OldInduction ?
1464    Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1465                       IdxTy):
1466    ConstantInt::get(IdxTy, 0);
1467
1468  assert(BypassBlock && "Invalid loop structure");
1469  LoopBypassBlocks.push_back(BypassBlock);
1470
1471  // Split the single block loop into the two loop structure described above.
1472  BasicBlock *VectorPH =
1473  BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1474  BasicBlock *VecBody =
1475  VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1476  BasicBlock *MiddleBlock =
1477  VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1478  BasicBlock *ScalarPH =
1479  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1480
1481  // Create and register the new vector loop.
1482  Loop* Lp = new Loop();
1483  Loop *ParentLoop = OrigLoop->getParentLoop();
1484
1485  // Insert the new loop into the loop nest and register the new basic blocks
1486  // before calling any utilities such as SCEV that require valid LoopInfo.
1487  if (ParentLoop) {
1488    ParentLoop->addChildLoop(Lp);
1489    ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1490    ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1491    ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1492  } else {
1493    LI->addTopLevelLoop(Lp);
1494  }
1495  Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1496
1497  // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1498  // inside the loop.
1499  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1500
1501  // Generate the induction variable.
1502  setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
1503  Induction = Builder.CreatePHI(IdxTy, 2, "index");
1504  // The loop step is equal to the vectorization factor (num of SIMD elements)
1505  // times the unroll factor (num of SIMD instructions).
1506  Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1507
1508  // This is the IR builder that we use to add all of the logic for bypassing
1509  // the new vector loop.
1510  IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1511  setDebugLocFromInst(BypassBuilder,
1512                      getDebugLocFromInstOrOperands(OldInduction));
1513
1514  // We may need to extend the index in case there is a type mismatch.
1515  // We know that the count starts at zero and does not overflow.
1516  if (Count->getType() != IdxTy) {
1517    // The exit count can be of pointer type. Convert it to the correct
1518    // integer type.
1519    if (ExitCount->getType()->isPointerTy())
1520      Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1521    else
1522      Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1523  }
1524
1525  // Add the start index to the loop count to get the new end index.
1526  Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1527
1528  // Now we need to generate the expression for N - (N % VF), which is
1529  // the part that the vectorized body will execute.
1530  Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1531  Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1532  Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1533                                                     "end.idx.rnd.down");
1534
1535  // Now, compare the new count to zero. If it is zero skip the vector loop and
1536  // jump to the scalar loop.
1537  Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1538                                          "cmp.zero");
1539
1540  BasicBlock *LastBypassBlock = BypassBlock;
1541
1542  // Generate the code that checks in runtime if arrays overlap. We put the
1543  // checks into a separate block to make the more common case of few elements
1544  // faster.
1545  Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1546                                                 BypassBlock->getTerminator());
1547  if (MemRuntimeCheck) {
1548    // Create a new block containing the memory check.
1549    BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1550                                                          "vector.memcheck");
1551    if (ParentLoop)
1552      ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1553    LoopBypassBlocks.push_back(CheckBlock);
1554
1555    // Replace the branch into the memory check block with a conditional branch
1556    // for the "few elements case".
1557    Instruction *OldTerm = BypassBlock->getTerminator();
1558    BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1559    OldTerm->eraseFromParent();
1560
1561    Cmp = MemRuntimeCheck;
1562    LastBypassBlock = CheckBlock;
1563  }
1564
1565  LastBypassBlock->getTerminator()->eraseFromParent();
1566  BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1567                     LastBypassBlock);
1568
1569  // We are going to resume the execution of the scalar loop.
1570  // Go over all of the induction variables that we found and fix the
1571  // PHIs that are left in the scalar version of the loop.
1572  // The starting values of PHI nodes depend on the counter of the last
1573  // iteration in the vectorized loop.
1574  // If we come from a bypass edge then we need to start from the original
1575  // start value.
1576
1577  // This variable saves the new starting index for the scalar loop.
1578  PHINode *ResumeIndex = 0;
1579  LoopVectorizationLegality::InductionList::iterator I, E;
1580  LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1581  // Set builder to point to last bypass block.
1582  BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1583  for (I = List->begin(), E = List->end(); I != E; ++I) {
1584    PHINode *OrigPhi = I->first;
1585    LoopVectorizationLegality::InductionInfo II = I->second;
1586
1587    Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1588    PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1589                                         MiddleBlock->getTerminator());
1590    // We might have extended the type of the induction variable but we need a
1591    // truncated version for the scalar loop.
1592    PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1593      PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1594                      MiddleBlock->getTerminator()) : 0;
1595
1596    Value *EndValue = 0;
1597    switch (II.IK) {
1598    case LoopVectorizationLegality::IK_NoInduction:
1599      llvm_unreachable("Unknown induction");
1600    case LoopVectorizationLegality::IK_IntInduction: {
1601      // Handle the integer induction counter.
1602      assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1603
1604      // We have the canonical induction variable.
1605      if (OrigPhi == OldInduction) {
1606        // Create a truncated version of the resume value for the scalar loop,
1607        // we might have promoted the type to a larger width.
1608        EndValue =
1609          BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1610        // The new PHI merges the original incoming value, in case of a bypass,
1611        // or the value at the end of the vectorized loop.
1612        for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1613          TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1614        TruncResumeVal->addIncoming(EndValue, VecBody);
1615
1616        // We know what the end value is.
1617        EndValue = IdxEndRoundDown;
1618        // We also know which PHI node holds it.
1619        ResumeIndex = ResumeVal;
1620        break;
1621      }
1622
1623      // Not the canonical induction variable - add the vector loop count to the
1624      // start value.
1625      Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1626                                                   II.StartValue->getType(),
1627                                                   "cast.crd");
1628      EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
1629      break;
1630    }
1631    case LoopVectorizationLegality::IK_ReverseIntInduction: {
1632      // Convert the CountRoundDown variable to the PHI size.
1633      Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1634                                                   II.StartValue->getType(),
1635                                                   "cast.crd");
1636      // Handle reverse integer induction counter.
1637      EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
1638      break;
1639    }
1640    case LoopVectorizationLegality::IK_PtrInduction: {
1641      // For pointer induction variables, calculate the offset using
1642      // the end index.
1643      EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
1644                                         "ptr.ind.end");
1645      break;
1646    }
1647    case LoopVectorizationLegality::IK_ReversePtrInduction: {
1648      // The value at the end of the loop for the reverse pointer is calculated
1649      // by creating a GEP with a negative index starting from the start value.
1650      Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1651      Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
1652                                              "rev.ind.end");
1653      EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
1654                                         "rev.ptr.ind.end");
1655      break;
1656    }
1657    }// end of case
1658
1659    // The new PHI merges the original incoming value, in case of a bypass,
1660    // or the value at the end of the vectorized loop.
1661    for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
1662      if (OrigPhi == OldInduction)
1663        ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
1664      else
1665        ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1666    }
1667    ResumeVal->addIncoming(EndValue, VecBody);
1668
1669    // Fix the scalar body counter (PHI node).
1670    unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1671    // The old inductions phi node in the scalar body needs the truncated value.
1672    if (OrigPhi == OldInduction)
1673      OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
1674    else
1675      OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1676  }
1677
1678  // If we are generating a new induction variable then we also need to
1679  // generate the code that calculates the exit value. This value is not
1680  // simply the end of the counter because we may skip the vectorized body
1681  // in case of a runtime check.
1682  if (!OldInduction){
1683    assert(!ResumeIndex && "Unexpected resume value found");
1684    ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1685                                  MiddleBlock->getTerminator());
1686    for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1687      ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1688    ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1689  }
1690
1691  // Make sure that we found the index where scalar loop needs to continue.
1692  assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1693         "Invalid resume Index");
1694
1695  // Add a check in the middle block to see if we have completed
1696  // all of the iterations in the first vector loop.
1697  // If (N - N%VF) == N, then we *don't* need to run the remainder.
1698  Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1699                                ResumeIndex, "cmp.n",
1700                                MiddleBlock->getTerminator());
1701
1702  BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1703  // Remove the old terminator.
1704  MiddleBlock->getTerminator()->eraseFromParent();
1705
1706  // Create i+1 and fill the PHINode.
1707  Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1708  Induction->addIncoming(StartIdx, VectorPH);
1709  Induction->addIncoming(NextIdx, VecBody);
1710  // Create the compare.
1711  Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1712  Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1713
1714  // Now we have two terminators. Remove the old one from the block.
1715  VecBody->getTerminator()->eraseFromParent();
1716
1717  // Get ready to start creating new instructions into the vectorized body.
1718  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1719
1720  // Save the state.
1721  LoopVectorPreHeader = VectorPH;
1722  LoopScalarPreHeader = ScalarPH;
1723  LoopMiddleBlock = MiddleBlock;
1724  LoopExitBlock = ExitBlock;
1725  LoopVectorBody = VecBody;
1726  LoopScalarBody = OldBasicBlock;
1727}
1728
1729/// This function returns the identity element (or neutral element) for
1730/// the operation K.
1731Constant*
1732LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
1733  switch (K) {
1734  case RK_IntegerXor:
1735  case RK_IntegerAdd:
1736  case RK_IntegerOr:
1737    // Adding, Xoring, Oring zero to a number does not change it.
1738    return ConstantInt::get(Tp, 0);
1739  case RK_IntegerMult:
1740    // Multiplying a number by 1 does not change it.
1741    return ConstantInt::get(Tp, 1);
1742  case RK_IntegerAnd:
1743    // AND-ing a number with an all-1 value does not change it.
1744    return ConstantInt::get(Tp, -1, true);
1745  case  RK_FloatMult:
1746    // Multiplying a number by 1 does not change it.
1747    return ConstantFP::get(Tp, 1.0L);
1748  case  RK_FloatAdd:
1749    // Adding zero to a number does not change it.
1750    return ConstantFP::get(Tp, 0.0L);
1751  default:
1752    llvm_unreachable("Unknown reduction kind");
1753  }
1754}
1755
1756static Intrinsic::ID
1757getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1758  // If we have an intrinsic call, check if it is trivially vectorizable.
1759  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1760    switch (II->getIntrinsicID()) {
1761    case Intrinsic::sqrt:
1762    case Intrinsic::sin:
1763    case Intrinsic::cos:
1764    case Intrinsic::exp:
1765    case Intrinsic::exp2:
1766    case Intrinsic::log:
1767    case Intrinsic::log10:
1768    case Intrinsic::log2:
1769    case Intrinsic::fabs:
1770    case Intrinsic::copysign:
1771    case Intrinsic::floor:
1772    case Intrinsic::ceil:
1773    case Intrinsic::trunc:
1774    case Intrinsic::rint:
1775    case Intrinsic::nearbyint:
1776    case Intrinsic::round:
1777    case Intrinsic::pow:
1778    case Intrinsic::fma:
1779    case Intrinsic::fmuladd:
1780    case Intrinsic::lifetime_start:
1781    case Intrinsic::lifetime_end:
1782      return II->getIntrinsicID();
1783    default:
1784      return Intrinsic::not_intrinsic;
1785    }
1786  }
1787
1788  if (!TLI)
1789    return Intrinsic::not_intrinsic;
1790
1791  LibFunc::Func Func;
1792  Function *F = CI->getCalledFunction();
1793  // We're going to make assumptions on the semantics of the functions, check
1794  // that the target knows that it's available in this environment.
1795  if (!F || !TLI->getLibFunc(F->getName(), Func))
1796    return Intrinsic::not_intrinsic;
1797
1798  // Otherwise check if we have a call to a function that can be turned into a
1799  // vector intrinsic.
1800  switch (Func) {
1801  default:
1802    break;
1803  case LibFunc::sin:
1804  case LibFunc::sinf:
1805  case LibFunc::sinl:
1806    return Intrinsic::sin;
1807  case LibFunc::cos:
1808  case LibFunc::cosf:
1809  case LibFunc::cosl:
1810    return Intrinsic::cos;
1811  case LibFunc::exp:
1812  case LibFunc::expf:
1813  case LibFunc::expl:
1814    return Intrinsic::exp;
1815  case LibFunc::exp2:
1816  case LibFunc::exp2f:
1817  case LibFunc::exp2l:
1818    return Intrinsic::exp2;
1819  case LibFunc::log:
1820  case LibFunc::logf:
1821  case LibFunc::logl:
1822    return Intrinsic::log;
1823  case LibFunc::log10:
1824  case LibFunc::log10f:
1825  case LibFunc::log10l:
1826    return Intrinsic::log10;
1827  case LibFunc::log2:
1828  case LibFunc::log2f:
1829  case LibFunc::log2l:
1830    return Intrinsic::log2;
1831  case LibFunc::fabs:
1832  case LibFunc::fabsf:
1833  case LibFunc::fabsl:
1834    return Intrinsic::fabs;
1835  case LibFunc::copysign:
1836  case LibFunc::copysignf:
1837  case LibFunc::copysignl:
1838    return Intrinsic::copysign;
1839  case LibFunc::floor:
1840  case LibFunc::floorf:
1841  case LibFunc::floorl:
1842    return Intrinsic::floor;
1843  case LibFunc::ceil:
1844  case LibFunc::ceilf:
1845  case LibFunc::ceill:
1846    return Intrinsic::ceil;
1847  case LibFunc::trunc:
1848  case LibFunc::truncf:
1849  case LibFunc::truncl:
1850    return Intrinsic::trunc;
1851  case LibFunc::rint:
1852  case LibFunc::rintf:
1853  case LibFunc::rintl:
1854    return Intrinsic::rint;
1855  case LibFunc::nearbyint:
1856  case LibFunc::nearbyintf:
1857  case LibFunc::nearbyintl:
1858    return Intrinsic::nearbyint;
1859  case LibFunc::round:
1860  case LibFunc::roundf:
1861  case LibFunc::roundl:
1862    return Intrinsic::round;
1863  case LibFunc::pow:
1864  case LibFunc::powf:
1865  case LibFunc::powl:
1866    return Intrinsic::pow;
1867  }
1868
1869  return Intrinsic::not_intrinsic;
1870}
1871
1872/// This function translates the reduction kind to an LLVM binary operator.
1873static unsigned
1874getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1875  switch (Kind) {
1876    case LoopVectorizationLegality::RK_IntegerAdd:
1877      return Instruction::Add;
1878    case LoopVectorizationLegality::RK_IntegerMult:
1879      return Instruction::Mul;
1880    case LoopVectorizationLegality::RK_IntegerOr:
1881      return Instruction::Or;
1882    case LoopVectorizationLegality::RK_IntegerAnd:
1883      return Instruction::And;
1884    case LoopVectorizationLegality::RK_IntegerXor:
1885      return Instruction::Xor;
1886    case LoopVectorizationLegality::RK_FloatMult:
1887      return Instruction::FMul;
1888    case LoopVectorizationLegality::RK_FloatAdd:
1889      return Instruction::FAdd;
1890    case LoopVectorizationLegality::RK_IntegerMinMax:
1891      return Instruction::ICmp;
1892    case LoopVectorizationLegality::RK_FloatMinMax:
1893      return Instruction::FCmp;
1894    default:
1895      llvm_unreachable("Unknown reduction operation");
1896  }
1897}
1898
1899Value *createMinMaxOp(IRBuilder<> &Builder,
1900                      LoopVectorizationLegality::MinMaxReductionKind RK,
1901                      Value *Left,
1902                      Value *Right) {
1903  CmpInst::Predicate P = CmpInst::ICMP_NE;
1904  switch (RK) {
1905  default:
1906    llvm_unreachable("Unknown min/max reduction kind");
1907  case LoopVectorizationLegality::MRK_UIntMin:
1908    P = CmpInst::ICMP_ULT;
1909    break;
1910  case LoopVectorizationLegality::MRK_UIntMax:
1911    P = CmpInst::ICMP_UGT;
1912    break;
1913  case LoopVectorizationLegality::MRK_SIntMin:
1914    P = CmpInst::ICMP_SLT;
1915    break;
1916  case LoopVectorizationLegality::MRK_SIntMax:
1917    P = CmpInst::ICMP_SGT;
1918    break;
1919  case LoopVectorizationLegality::MRK_FloatMin:
1920    P = CmpInst::FCMP_OLT;
1921    break;
1922  case LoopVectorizationLegality::MRK_FloatMax:
1923    P = CmpInst::FCMP_OGT;
1924    break;
1925  }
1926
1927  Value *Cmp;
1928  if (RK == LoopVectorizationLegality::MRK_FloatMin ||
1929      RK == LoopVectorizationLegality::MRK_FloatMax)
1930    Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
1931  else
1932    Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
1933
1934  Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1935  return Select;
1936}
1937
1938void
1939InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1940  //===------------------------------------------------===//
1941  //
1942  // Notice: any optimization or new instruction that go
1943  // into the code below should be also be implemented in
1944  // the cost-model.
1945  //
1946  //===------------------------------------------------===//
1947  Constant *Zero = Builder.getInt32(0);
1948
1949  // In order to support reduction variables we need to be able to vectorize
1950  // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1951  // stages. First, we create a new vector PHI node with no incoming edges.
1952  // We use this value when we vectorize all of the instructions that use the
1953  // PHI. Next, after all of the instructions in the block are complete we
1954  // add the new incoming edges to the PHI. At this point all of the
1955  // instructions in the basic block are vectorized, so we can use them to
1956  // construct the PHI.
1957  PhiVector RdxPHIsToFix;
1958
1959  // Scan the loop in a topological order to ensure that defs are vectorized
1960  // before users.
1961  LoopBlocksDFS DFS(OrigLoop);
1962  DFS.perform(LI);
1963
1964  // Vectorize all of the blocks in the original loop.
1965  for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1966       be = DFS.endRPO(); bb != be; ++bb)
1967    vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1968
1969  // At this point every instruction in the original loop is widened to
1970  // a vector form. We are almost done. Now, we need to fix the PHI nodes
1971  // that we vectorized. The PHI nodes are currently empty because we did
1972  // not want to introduce cycles. Notice that the remaining PHI nodes
1973  // that we need to fix are reduction variables.
1974
1975  // Create the 'reduced' values for each of the induction vars.
1976  // The reduced values are the vector values that we scalarize and combine
1977  // after the loop is finished.
1978  for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1979       it != e; ++it) {
1980    PHINode *RdxPhi = *it;
1981    assert(RdxPhi && "Unable to recover vectorized PHI");
1982
1983    // Find the reduction variable descriptor.
1984    assert(Legal->getReductionVars()->count(RdxPhi) &&
1985           "Unable to find the reduction variable");
1986    LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1987    (*Legal->getReductionVars())[RdxPhi];
1988
1989    setDebugLocFromInst(Builder, RdxDesc.StartValue);
1990
1991    // We need to generate a reduction vector from the incoming scalar.
1992    // To do so, we need to generate the 'identity' vector and overide
1993    // one of the elements with the incoming scalar reduction. We need
1994    // to do it in the vector-loop preheader.
1995    Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
1996
1997    // This is the vector-clone of the value that leaves the loop.
1998    VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1999    Type *VecTy = VectorExit[0]->getType();
2000
2001    // Find the reduction identity variable. Zero for addition, or, xor,
2002    // one for multiplication, -1 for And.
2003    Value *Identity;
2004    Value *VectorStart;
2005    if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2006        RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2007      // MinMax reduction have the start value as their identify.
2008      VectorStart = Identity = Builder.CreateVectorSplat(VF, RdxDesc.StartValue,
2009                                                         "minmax.ident");
2010    } else {
2011      Constant *Iden =
2012        LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2013                                                        VecTy->getScalarType());
2014      Identity = ConstantVector::getSplat(VF, Iden);
2015
2016      // This vector is the Identity vector where the first element is the
2017      // incoming scalar reduction.
2018      VectorStart = Builder.CreateInsertElement(Identity,
2019                                                RdxDesc.StartValue, Zero);
2020    }
2021
2022    // Fix the vector-loop phi.
2023    // We created the induction variable so we know that the
2024    // preheader is the first entry.
2025    BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2026
2027    // Reductions do not have to start at zero. They can start with
2028    // any loop invariant values.
2029    VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2030    BasicBlock *Latch = OrigLoop->getLoopLatch();
2031    Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2032    VectorParts &Val = getVectorValue(LoopVal);
2033    for (unsigned part = 0; part < UF; ++part) {
2034      // Make sure to add the reduction stat value only to the
2035      // first unroll part.
2036      Value *StartVal = (part == 0) ? VectorStart : Identity;
2037      cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2038      cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
2039    }
2040
2041    // Before each round, move the insertion point right between
2042    // the PHIs and the values we are going to write.
2043    // This allows us to write both PHINodes and the extractelement
2044    // instructions.
2045    Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2046
2047    VectorParts RdxParts;
2048    setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2049    for (unsigned part = 0; part < UF; ++part) {
2050      // This PHINode contains the vectorized reduction variable, or
2051      // the initial value vector, if we bypass the vector loop.
2052      VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2053      PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2054      Value *StartVal = (part == 0) ? VectorStart : Identity;
2055      for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2056        NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2057      NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
2058      RdxParts.push_back(NewPhi);
2059    }
2060
2061    // Reduce all of the unrolled parts into a single vector.
2062    Value *ReducedPartRdx = RdxParts[0];
2063    unsigned Op = getReductionBinOp(RdxDesc.Kind);
2064    setDebugLocFromInst(Builder, ReducedPartRdx);
2065    for (unsigned part = 1; part < UF; ++part) {
2066      if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2067        ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2068                                             RdxParts[part], ReducedPartRdx,
2069                                             "bin.rdx");
2070      else
2071        ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2072                                        ReducedPartRdx, RdxParts[part]);
2073    }
2074
2075    // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2076    // and vector ops, reducing the set of values being computed by half each
2077    // round.
2078    assert(isPowerOf2_32(VF) &&
2079           "Reduction emission only supported for pow2 vectors!");
2080    Value *TmpVec = ReducedPartRdx;
2081    SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2082    for (unsigned i = VF; i != 1; i >>= 1) {
2083      // Move the upper half of the vector to the lower half.
2084      for (unsigned j = 0; j != i/2; ++j)
2085        ShuffleMask[j] = Builder.getInt32(i/2 + j);
2086
2087      // Fill the rest of the mask with undef.
2088      std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2089                UndefValue::get(Builder.getInt32Ty()));
2090
2091      Value *Shuf =
2092        Builder.CreateShuffleVector(TmpVec,
2093                                    UndefValue::get(TmpVec->getType()),
2094                                    ConstantVector::get(ShuffleMask),
2095                                    "rdx.shuf");
2096
2097      if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2098        TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2099                                     "bin.rdx");
2100      else
2101        TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2102    }
2103
2104    // The result is in the first element of the vector.
2105    Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2106
2107    // Now, we need to fix the users of the reduction variable
2108    // inside and outside of the scalar remainder loop.
2109    // We know that the loop is in LCSSA form. We need to update the
2110    // PHI nodes in the exit blocks.
2111    for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2112         LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2113      PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2114      if (!LCSSAPhi) continue;
2115
2116      // All PHINodes need to have a single entry edge, or two if
2117      // we already fixed them.
2118      assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2119
2120      // We found our reduction value exit-PHI. Update it with the
2121      // incoming bypass edge.
2122      if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2123        // Add an edge coming from the bypass.
2124        LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
2125        break;
2126      }
2127    }// end of the LCSSA phi scan.
2128
2129    // Fix the scalar loop reduction variable with the incoming reduction sum
2130    // from the vector body and from the backedge value.
2131    int IncomingEdgeBlockIdx =
2132    (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2133    assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2134    // Pick the other block.
2135    int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2136    (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
2137    (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2138  }// end of for each redux variable.
2139
2140  // The Loop exit block may have single value PHI nodes where the incoming
2141  // value is 'undef'. While vectorizing we only handled real values that
2142  // were defined inside the loop. Here we handle the 'undef case'.
2143  // See PR14725.
2144  for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2145       LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2146    PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2147    if (!LCSSAPhi) continue;
2148    if (LCSSAPhi->getNumIncomingValues() == 1)
2149      LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2150                            LoopMiddleBlock);
2151  }
2152}
2153
2154InnerLoopVectorizer::VectorParts
2155InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2156  assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2157         "Invalid edge");
2158
2159  // Look for cached value.
2160  std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2161  EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2162  if (ECEntryIt != MaskCache.end())
2163    return ECEntryIt->second;
2164
2165  VectorParts SrcMask = createBlockInMask(Src);
2166
2167  // The terminator has to be a branch inst!
2168  BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2169  assert(BI && "Unexpected terminator found");
2170
2171  if (BI->isConditional()) {
2172    VectorParts EdgeMask = getVectorValue(BI->getCondition());
2173
2174    if (BI->getSuccessor(0) != Dst)
2175      for (unsigned part = 0; part < UF; ++part)
2176        EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2177
2178    for (unsigned part = 0; part < UF; ++part)
2179      EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2180
2181    MaskCache[Edge] = EdgeMask;
2182    return EdgeMask;
2183  }
2184
2185  MaskCache[Edge] = SrcMask;
2186  return SrcMask;
2187}
2188
2189InnerLoopVectorizer::VectorParts
2190InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2191  assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2192
2193  // Loop incoming mask is all-one.
2194  if (OrigLoop->getHeader() == BB) {
2195    Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2196    return getVectorValue(C);
2197  }
2198
2199  // This is the block mask. We OR all incoming edges, and with zero.
2200  Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2201  VectorParts BlockMask = getVectorValue(Zero);
2202
2203  // For each pred:
2204  for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2205    VectorParts EM = createEdgeMask(*it, BB);
2206    for (unsigned part = 0; part < UF; ++part)
2207      BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2208  }
2209
2210  return BlockMask;
2211}
2212
2213void
2214InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
2215                                          BasicBlock *BB, PhiVector *PV) {
2216  // For each instruction in the old loop.
2217  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2218    VectorParts &Entry = WidenMap.get(it);
2219    switch (it->getOpcode()) {
2220    case Instruction::Br:
2221      // Nothing to do for PHIs and BR, since we already took care of the
2222      // loop control flow instructions.
2223      continue;
2224    case Instruction::PHI:{
2225      PHINode* P = cast<PHINode>(it);
2226      // Handle reduction variables:
2227      if (Legal->getReductionVars()->count(P)) {
2228        for (unsigned part = 0; part < UF; ++part) {
2229          // This is phase one of vectorizing PHIs.
2230          Type *VecTy = VectorType::get(it->getType(), VF);
2231          Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2232                                        LoopVectorBody-> getFirstInsertionPt());
2233        }
2234        PV->push_back(P);
2235        continue;
2236      }
2237
2238      setDebugLocFromInst(Builder, P);
2239      // Check for PHI nodes that are lowered to vector selects.
2240      if (P->getParent() != OrigLoop->getHeader()) {
2241        // We know that all PHIs in non header blocks are converted into
2242        // selects, so we don't have to worry about the insertion order and we
2243        // can just use the builder.
2244        // At this point we generate the predication tree. There may be
2245        // duplications since this is a simple recursive scan, but future
2246        // optimizations will clean it up.
2247
2248        unsigned NumIncoming = P->getNumIncomingValues();
2249
2250        // Generate a sequence of selects of the form:
2251        // SELECT(Mask3, In3,
2252        //      SELECT(Mask2, In2,
2253        //                   ( ...)))
2254        for (unsigned In = 0; In < NumIncoming; In++) {
2255          VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2256                                            P->getParent());
2257          VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2258
2259          for (unsigned part = 0; part < UF; ++part) {
2260            // We might have single edge PHIs (blocks) - use an identity
2261            // 'select' for the first PHI operand.
2262            if (In == 0)
2263              Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2264                                                 In0[part]);
2265            else
2266              // Select between the current value and the previous incoming edge
2267              // based on the incoming mask.
2268              Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2269                                                 Entry[part], "predphi");
2270          }
2271        }
2272        continue;
2273      }
2274
2275      // This PHINode must be an induction variable.
2276      // Make sure that we know about it.
2277      assert(Legal->getInductionVars()->count(P) &&
2278             "Not an induction variable");
2279
2280      LoopVectorizationLegality::InductionInfo II =
2281        Legal->getInductionVars()->lookup(P);
2282
2283      switch (II.IK) {
2284      case LoopVectorizationLegality::IK_NoInduction:
2285        llvm_unreachable("Unknown induction");
2286      case LoopVectorizationLegality::IK_IntInduction: {
2287        assert(P->getType() == II.StartValue->getType() && "Types must match");
2288        Type *PhiTy = P->getType();
2289        Value *Broadcasted;
2290        if (P == OldInduction) {
2291          // Handle the canonical induction variable. We might have had to
2292          // extend the type.
2293          Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2294        } else {
2295          // Handle other induction variables that are now based on the
2296          // canonical one.
2297          Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2298                                                   "normalized.idx");
2299          NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2300          Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2301                                          "offset.idx");
2302        }
2303        Broadcasted = getBroadcastInstrs(Broadcasted);
2304        // After broadcasting the induction variable we need to make the vector
2305        // consecutive by adding 0, 1, 2, etc.
2306        for (unsigned part = 0; part < UF; ++part)
2307          Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2308        continue;
2309      }
2310      case LoopVectorizationLegality::IK_ReverseIntInduction:
2311      case LoopVectorizationLegality::IK_PtrInduction:
2312      case LoopVectorizationLegality::IK_ReversePtrInduction:
2313        // Handle reverse integer and pointer inductions.
2314        Value *StartIdx = ExtendedIdx;
2315        // This is the normalized GEP that starts counting at zero.
2316        Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2317                                                 "normalized.idx");
2318
2319        // Handle the reverse integer induction variable case.
2320        if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2321          IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2322          Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2323                                                 "resize.norm.idx");
2324          Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
2325                                                 "reverse.idx");
2326
2327          // This is a new value so do not hoist it out.
2328          Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2329          // After broadcasting the induction variable we need to make the
2330          // vector consecutive by adding  ... -3, -2, -1, 0.
2331          for (unsigned part = 0; part < UF; ++part)
2332            Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2333                                               true);
2334          continue;
2335        }
2336
2337        // Handle the pointer induction variable case.
2338        assert(P->getType()->isPointerTy() && "Unexpected type.");
2339
2340        // Is this a reverse induction ptr or a consecutive induction ptr.
2341        bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2342                        II.IK);
2343
2344        // This is the vector of results. Notice that we don't generate
2345        // vector geps because scalar geps result in better code.
2346        for (unsigned part = 0; part < UF; ++part) {
2347          Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2348          for (unsigned int i = 0; i < VF; ++i) {
2349            int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2350            Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2351            Value *GlobalIdx;
2352            if (!Reverse)
2353              GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2354            else
2355              GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2356
2357            Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2358                                               "next.gep");
2359            VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2360                                                 Builder.getInt32(i),
2361                                                 "insert.gep");
2362          }
2363          Entry[part] = VecVal;
2364        }
2365        continue;
2366      }
2367
2368    }// End of PHI.
2369
2370    case Instruction::Add:
2371    case Instruction::FAdd:
2372    case Instruction::Sub:
2373    case Instruction::FSub:
2374    case Instruction::Mul:
2375    case Instruction::FMul:
2376    case Instruction::UDiv:
2377    case Instruction::SDiv:
2378    case Instruction::FDiv:
2379    case Instruction::URem:
2380    case Instruction::SRem:
2381    case Instruction::FRem:
2382    case Instruction::Shl:
2383    case Instruction::LShr:
2384    case Instruction::AShr:
2385    case Instruction::And:
2386    case Instruction::Or:
2387    case Instruction::Xor: {
2388      // Just widen binops.
2389      BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2390      setDebugLocFromInst(Builder, BinOp);
2391      VectorParts &A = getVectorValue(it->getOperand(0));
2392      VectorParts &B = getVectorValue(it->getOperand(1));
2393
2394      // Use this vector value for all users of the original instruction.
2395      for (unsigned Part = 0; Part < UF; ++Part) {
2396        Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2397
2398        // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2399        BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2400        if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2401          VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2402          VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2403        }
2404        if (VecOp && isa<PossiblyExactOperator>(VecOp))
2405          VecOp->setIsExact(BinOp->isExact());
2406
2407        Entry[Part] = V;
2408      }
2409      break;
2410    }
2411    case Instruction::Select: {
2412      // Widen selects.
2413      // If the selector is loop invariant we can create a select
2414      // instruction with a scalar condition. Otherwise, use vector-select.
2415      bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2416                                               OrigLoop);
2417      setDebugLocFromInst(Builder, it);
2418
2419      // The condition can be loop invariant  but still defined inside the
2420      // loop. This means that we can't just use the original 'cond' value.
2421      // We have to take the 'vectorized' value and pick the first lane.
2422      // Instcombine will make this a no-op.
2423      VectorParts &Cond = getVectorValue(it->getOperand(0));
2424      VectorParts &Op0  = getVectorValue(it->getOperand(1));
2425      VectorParts &Op1  = getVectorValue(it->getOperand(2));
2426      Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2427                                                       Builder.getInt32(0));
2428      for (unsigned Part = 0; Part < UF; ++Part) {
2429        Entry[Part] = Builder.CreateSelect(
2430          InvariantCond ? ScalarCond : Cond[Part],
2431          Op0[Part],
2432          Op1[Part]);
2433      }
2434      break;
2435    }
2436
2437    case Instruction::ICmp:
2438    case Instruction::FCmp: {
2439      // Widen compares. Generate vector compares.
2440      bool FCmp = (it->getOpcode() == Instruction::FCmp);
2441      CmpInst *Cmp = dyn_cast<CmpInst>(it);
2442      setDebugLocFromInst(Builder, it);
2443      VectorParts &A = getVectorValue(it->getOperand(0));
2444      VectorParts &B = getVectorValue(it->getOperand(1));
2445      for (unsigned Part = 0; Part < UF; ++Part) {
2446        Value *C = 0;
2447        if (FCmp)
2448          C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2449        else
2450          C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2451        Entry[Part] = C;
2452      }
2453      break;
2454    }
2455
2456    case Instruction::Store:
2457    case Instruction::Load:
2458        vectorizeMemoryInstruction(it, Legal);
2459        break;
2460    case Instruction::ZExt:
2461    case Instruction::SExt:
2462    case Instruction::FPToUI:
2463    case Instruction::FPToSI:
2464    case Instruction::FPExt:
2465    case Instruction::PtrToInt:
2466    case Instruction::IntToPtr:
2467    case Instruction::SIToFP:
2468    case Instruction::UIToFP:
2469    case Instruction::Trunc:
2470    case Instruction::FPTrunc:
2471    case Instruction::BitCast: {
2472      CastInst *CI = dyn_cast<CastInst>(it);
2473      setDebugLocFromInst(Builder, it);
2474      /// Optimize the special case where the source is the induction
2475      /// variable. Notice that we can only optimize the 'trunc' case
2476      /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2477      /// c. other casts depend on pointer size.
2478      if (CI->getOperand(0) == OldInduction &&
2479          it->getOpcode() == Instruction::Trunc) {
2480        Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2481                                               CI->getType());
2482        Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2483        for (unsigned Part = 0; Part < UF; ++Part)
2484          Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2485        break;
2486      }
2487      /// Vectorize casts.
2488      Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2489
2490      VectorParts &A = getVectorValue(it->getOperand(0));
2491      for (unsigned Part = 0; Part < UF; ++Part)
2492        Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2493      break;
2494    }
2495
2496    case Instruction::Call: {
2497      // Ignore dbg intrinsics.
2498      if (isa<DbgInfoIntrinsic>(it))
2499        break;
2500      setDebugLocFromInst(Builder, it);
2501
2502      Module *M = BB->getParent()->getParent();
2503      CallInst *CI = cast<CallInst>(it);
2504      Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2505      assert(ID && "Not an intrinsic call!");
2506      switch (ID) {
2507      case Intrinsic::lifetime_end:
2508      case Intrinsic::lifetime_start:
2509        scalarizeInstruction(it);
2510        break;
2511      default:
2512        for (unsigned Part = 0; Part < UF; ++Part) {
2513          SmallVector<Value *, 4> Args;
2514          for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2515            VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2516            Args.push_back(Arg[Part]);
2517          }
2518          Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) };
2519          Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2520          Entry[Part] = Builder.CreateCall(F, Args);
2521        }
2522        break;
2523      }
2524      break;
2525    }
2526
2527    default:
2528      // All other instructions are unsupported. Scalarize them.
2529      scalarizeInstruction(it);
2530      break;
2531    }// end of switch.
2532  }// end of for_each instr.
2533}
2534
2535void InnerLoopVectorizer::updateAnalysis() {
2536  // Forget the original basic block.
2537  SE->forgetLoop(OrigLoop);
2538
2539  // Update the dominator tree information.
2540  assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2541         "Entry does not dominate exit.");
2542
2543  for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2544    DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2545  DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2546  DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2547  DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2548  DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2549  DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2550  DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2551
2552  DEBUG(DT->verifyAnalysis());
2553}
2554
2555bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2556  if (!EnableIfConversion)
2557    return false;
2558
2559  assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2560  std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2561
2562  // A list of pointers that we can safely read and write to.
2563  SmallPtrSet<Value *, 8> SafePointes;
2564
2565  // Collect safe addresses.
2566  for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2567    BasicBlock *BB = LoopBlocks[i];
2568
2569    if (blockNeedsPredication(BB))
2570      continue;
2571
2572    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2573      if (LoadInst *LI = dyn_cast<LoadInst>(I))
2574        SafePointes.insert(LI->getPointerOperand());
2575      else if (StoreInst *SI = dyn_cast<StoreInst>(I))
2576        SafePointes.insert(SI->getPointerOperand());
2577    }
2578  }
2579
2580  // Collect the blocks that need predication.
2581  for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2582    BasicBlock *BB = LoopBlocks[i];
2583
2584    // We don't support switch statements inside loops.
2585    if (!isa<BranchInst>(BB->getTerminator()))
2586      return false;
2587
2588    // We must be able to predicate all blocks that need to be predicated.
2589    if (blockNeedsPredication(BB) && !blockCanBePredicated(BB, SafePointes))
2590      return false;
2591  }
2592
2593  // We can if-convert this loop.
2594  return true;
2595}
2596
2597bool LoopVectorizationLegality::canVectorize() {
2598  // We must have a loop in canonical form. Loops with indirectbr in them cannot
2599  // be canonicalized.
2600  if (!TheLoop->getLoopPreheader())
2601    return false;
2602
2603  // We can only vectorize innermost loops.
2604  if (TheLoop->getSubLoopsVector().size())
2605    return false;
2606
2607  // We must have a single backedge.
2608  if (TheLoop->getNumBackEdges() != 1)
2609    return false;
2610
2611  // We must have a single exiting block.
2612  if (!TheLoop->getExitingBlock())
2613    return false;
2614
2615  unsigned NumBlocks = TheLoop->getNumBlocks();
2616
2617  // Check if we can if-convert non single-bb loops.
2618  if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2619    DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2620    return false;
2621  }
2622
2623  // We need to have a loop header.
2624  BasicBlock *Latch = TheLoop->getLoopLatch();
2625  DEBUG(dbgs() << "LV: Found a loop: " <<
2626        TheLoop->getHeader()->getName() << "\n");
2627
2628  // ScalarEvolution needs to be able to find the exit count.
2629  const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
2630  if (ExitCount == SE->getCouldNotCompute()) {
2631    DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2632    return false;
2633  }
2634
2635  // Do not loop-vectorize loops with a tiny trip count.
2636  unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2637  if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2638    DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2639          "This loop is not worth vectorizing.\n");
2640    return false;
2641  }
2642
2643  // Check if we can vectorize the instructions and CFG in this loop.
2644  if (!canVectorizeInstrs()) {
2645    DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2646    return false;
2647  }
2648
2649  // Go over each instruction and look at memory deps.
2650  if (!canVectorizeMemory()) {
2651    DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2652    return false;
2653  }
2654
2655  // Collect all of the variables that remain uniform after vectorization.
2656  collectLoopUniforms();
2657
2658  DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2659        (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2660        <<"!\n");
2661
2662  // Okay! We can vectorize. At this point we don't have any other mem analysis
2663  // which may limit our maximum vectorization factor, so just return true with
2664  // no restrictions.
2665  return true;
2666}
2667
2668static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
2669  if (Ty->isPointerTy())
2670    return DL.getIntPtrType(Ty->getContext());
2671  return Ty;
2672}
2673
2674static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
2675  Ty0 = convertPointerToIntegerType(DL, Ty0);
2676  Ty1 = convertPointerToIntegerType(DL, Ty1);
2677  if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
2678    return Ty0;
2679  return Ty1;
2680}
2681
2682/// \brief Check that the instruction has outside loop users and is not an
2683/// identified reduction variable.
2684static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
2685                               SmallPtrSet<Value *, 4> &Reductions) {
2686  // Reduction instructions are allowed to have exit users. All other
2687  // instructions must not have external users.
2688  if (!Reductions.count(Inst))
2689    //Check that all of the users of the loop are inside the BB.
2690    for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
2691         I != E; ++I) {
2692      Instruction *U = cast<Instruction>(*I);
2693      // This user may be a reduction exit value.
2694      if (!TheLoop->contains(U)) {
2695        DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2696        return true;
2697      }
2698    }
2699  return false;
2700}
2701
2702bool LoopVectorizationLegality::canVectorizeInstrs() {
2703  BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2704  BasicBlock *Header = TheLoop->getHeader();
2705
2706  // Look for the attribute signaling the absence of NaNs.
2707  Function &F = *Header->getParent();
2708  if (F.hasFnAttribute("no-nans-fp-math"))
2709    HasFunNoNaNAttr = F.getAttributes().getAttribute(
2710      AttributeSet::FunctionIndex,
2711      "no-nans-fp-math").getValueAsString() == "true";
2712
2713  // For each block in the loop.
2714  for (Loop::block_iterator bb = TheLoop->block_begin(),
2715       be = TheLoop->block_end(); bb != be; ++bb) {
2716
2717    // Scan the instructions in the block and look for hazards.
2718    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2719         ++it) {
2720
2721      if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2722        Type *PhiTy = Phi->getType();
2723        // Check that this PHI type is allowed.
2724        if (!PhiTy->isIntegerTy() &&
2725            !PhiTy->isFloatingPointTy() &&
2726            !PhiTy->isPointerTy()) {
2727          DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2728          return false;
2729        }
2730
2731        // If this PHINode is not in the header block, then we know that we
2732        // can convert it to select during if-conversion. No need to check if
2733        // the PHIs in this block are induction or reduction variables.
2734        if (*bb != Header) {
2735          // Check that this instruction has no outside users or is an
2736          // identified reduction value with an outside user.
2737          if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
2738            continue;
2739          return false;
2740        }
2741
2742        // We only allow if-converted PHIs with more than two incoming values.
2743        if (Phi->getNumIncomingValues() != 2) {
2744          DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2745          return false;
2746        }
2747
2748        // This is the value coming from the preheader.
2749        Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2750        // Check if this is an induction variable.
2751        InductionKind IK = isInductionVariable(Phi);
2752
2753        if (IK_NoInduction != IK) {
2754          // Get the widest type.
2755          if (!WidestIndTy)
2756            WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
2757          else
2758            WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
2759
2760          // Int inductions are special because we only allow one IV.
2761          if (IK == IK_IntInduction) {
2762            // Use the phi node with the widest type as induction. Use the last
2763            // one if there are multiple (no good reason for doing this other
2764            // than it is expedient).
2765            if (!Induction || PhiTy == WidestIndTy)
2766              Induction = Phi;
2767          }
2768
2769          DEBUG(dbgs() << "LV: Found an induction variable.\n");
2770          Inductions[Phi] = InductionInfo(StartValue, IK);
2771          continue;
2772        }
2773
2774        if (AddReductionVar(Phi, RK_IntegerAdd)) {
2775          DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2776          continue;
2777        }
2778        if (AddReductionVar(Phi, RK_IntegerMult)) {
2779          DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2780          continue;
2781        }
2782        if (AddReductionVar(Phi, RK_IntegerOr)) {
2783          DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2784          continue;
2785        }
2786        if (AddReductionVar(Phi, RK_IntegerAnd)) {
2787          DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2788          continue;
2789        }
2790        if (AddReductionVar(Phi, RK_IntegerXor)) {
2791          DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2792          continue;
2793        }
2794        if (AddReductionVar(Phi, RK_IntegerMinMax)) {
2795          DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
2796          continue;
2797        }
2798        if (AddReductionVar(Phi, RK_FloatMult)) {
2799          DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2800          continue;
2801        }
2802        if (AddReductionVar(Phi, RK_FloatAdd)) {
2803          DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2804          continue;
2805        }
2806        if (AddReductionVar(Phi, RK_FloatMinMax)) {
2807          DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
2808                "\n");
2809          continue;
2810        }
2811
2812        DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2813        return false;
2814      }// end of PHI handling
2815
2816      // We still don't handle functions. However, we can ignore dbg intrinsic
2817      // calls and we do handle certain intrinsic and libm functions.
2818      CallInst *CI = dyn_cast<CallInst>(it);
2819      if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
2820        DEBUG(dbgs() << "LV: Found a call site.\n");
2821        return false;
2822      }
2823
2824      // Check that the instruction return type is vectorizable.
2825      if (!VectorType::isValidElementType(it->getType()) &&
2826          !it->getType()->isVoidTy()) {
2827        DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2828        return false;
2829      }
2830
2831      // Check that the stored type is vectorizable.
2832      if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2833        Type *T = ST->getValueOperand()->getType();
2834        if (!VectorType::isValidElementType(T))
2835          return false;
2836      }
2837
2838      // Reduction instructions are allowed to have exit users.
2839      // All other instructions must not have external users.
2840      if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
2841        return false;
2842
2843    } // next instr.
2844
2845  }
2846
2847  if (!Induction) {
2848    DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2849    if (Inductions.empty())
2850      return false;
2851  }
2852
2853  return true;
2854}
2855
2856void LoopVectorizationLegality::collectLoopUniforms() {
2857  // We now know that the loop is vectorizable!
2858  // Collect variables that will remain uniform after vectorization.
2859  std::vector<Value*> Worklist;
2860  BasicBlock *Latch = TheLoop->getLoopLatch();
2861
2862  // Start with the conditional branch and walk up the block.
2863  Worklist.push_back(Latch->getTerminator()->getOperand(0));
2864
2865  while (Worklist.size()) {
2866    Instruction *I = dyn_cast<Instruction>(Worklist.back());
2867    Worklist.pop_back();
2868
2869    // Look at instructions inside this loop.
2870    // Stop when reaching PHI nodes.
2871    // TODO: we need to follow values all over the loop, not only in this block.
2872    if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2873      continue;
2874
2875    // This is a known uniform.
2876    Uniforms.insert(I);
2877
2878    // Insert all operands.
2879    Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
2880  }
2881}
2882
2883namespace {
2884/// \brief Analyses memory accesses in a loop.
2885///
2886/// Checks whether run time pointer checks are needed and builds sets for data
2887/// dependence checking.
2888class AccessAnalysis {
2889public:
2890  /// \brief Read or write access location.
2891  typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
2892  typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
2893
2894  /// \brief Set of potential dependent memory accesses.
2895  typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
2896
2897  AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
2898    DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
2899    AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
2900
2901  /// \brief Register a load  and whether it is only read from.
2902  void addLoad(Value *Ptr, bool IsReadOnly) {
2903    Accesses.insert(MemAccessInfo(Ptr, false));
2904    if (IsReadOnly)
2905      ReadOnlyPtr.insert(Ptr);
2906  }
2907
2908  /// \brief Register a store.
2909  void addStore(Value *Ptr) {
2910    Accesses.insert(MemAccessInfo(Ptr, true));
2911  }
2912
2913  /// \brief Check whether we can check the pointers at runtime for
2914  /// non-intersection.
2915  bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
2916                       unsigned &NumComparisons, ScalarEvolution *SE,
2917                       Loop *TheLoop);
2918
2919  /// \brief Goes over all memory accesses, checks whether a RT check is needed
2920  /// and builds sets of dependent accesses.
2921  void buildDependenceSets() {
2922    // Process read-write pointers first.
2923    processMemAccesses(false);
2924    // Next, process read pointers.
2925    processMemAccesses(true);
2926  }
2927
2928  bool isRTCheckNeeded() { return IsRTCheckNeeded; }
2929
2930  bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
2931
2932  MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
2933
2934private:
2935  typedef SetVector<MemAccessInfo> PtrAccessSet;
2936  typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
2937
2938  /// \brief Go over all memory access or only the deferred ones if
2939  /// \p UseDeferred is true and check whether runtime pointer checks are needed
2940  /// and build sets of dependency check candidates.
2941  void processMemAccesses(bool UseDeferred);
2942
2943  /// Set of all accesses.
2944  PtrAccessSet Accesses;
2945
2946  /// Set of access to check after all writes have been processed.
2947  PtrAccessSet DeferredAccesses;
2948
2949  /// Map of pointers to last access encountered.
2950  UnderlyingObjToAccessMap ObjToLastAccess;
2951
2952  /// Set of accesses that need a further dependence check.
2953  MemAccessInfoSet CheckDeps;
2954
2955  /// Set of pointers that are read only.
2956  SmallPtrSet<Value*, 16> ReadOnlyPtr;
2957
2958  /// Set of underlying objects already written to.
2959  SmallPtrSet<Value*, 16> WriteObjects;
2960
2961  DataLayout *DL;
2962
2963  /// Sets of potentially dependent accesses - members of one set share an
2964  /// underlying pointer. The set "CheckDeps" identfies which sets really need a
2965  /// dependence check.
2966  DepCandidates &DepCands;
2967
2968  bool AreAllWritesIdentified;
2969  bool AreAllReadsIdentified;
2970  bool IsRTCheckNeeded;
2971};
2972
2973} // end anonymous namespace
2974
2975/// \brief Check whether a pointer can participate in a runtime bounds check.
2976static bool hasComputableBounds(ScalarEvolution *SE, Value *Ptr) {
2977  const SCEV *PtrScev = SE->getSCEV(Ptr);
2978  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
2979  if (!AR)
2980    return false;
2981
2982  return AR->isAffine();
2983}
2984
2985bool AccessAnalysis::canCheckPtrAtRT(
2986                       LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
2987                        unsigned &NumComparisons, ScalarEvolution *SE,
2988                        Loop *TheLoop) {
2989  // Find pointers with computable bounds. We are going to use this information
2990  // to place a runtime bound check.
2991  unsigned NumReadPtrChecks = 0;
2992  unsigned NumWritePtrChecks = 0;
2993  bool CanDoRT = true;
2994
2995  bool IsDepCheckNeeded = isDependencyCheckNeeded();
2996  // We assign consecutive id to access from different dependence sets.
2997  // Accesses within the same set don't need a runtime check.
2998  unsigned RunningDepId = 1;
2999  DenseMap<Value *, unsigned> DepSetId;
3000
3001  for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3002       AI != AE; ++AI) {
3003    const MemAccessInfo &Access = *AI;
3004    Value *Ptr = Access.getPointer();
3005    bool IsWrite = Access.getInt();
3006
3007    // Just add write checks if we have both.
3008    if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3009      continue;
3010
3011    if (IsWrite)
3012      ++NumWritePtrChecks;
3013    else
3014      ++NumReadPtrChecks;
3015
3016    if (hasComputableBounds(SE, Ptr)) {
3017      // The id of the dependence set.
3018      unsigned DepId;
3019
3020      if (IsDepCheckNeeded) {
3021        Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3022        unsigned &LeaderId = DepSetId[Leader];
3023        if (!LeaderId)
3024          LeaderId = RunningDepId++;
3025        DepId = LeaderId;
3026      } else
3027        // Each access has its own dependence set.
3028        DepId = RunningDepId++;
3029
3030      RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId);
3031
3032      DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr <<"\n");
3033    } else {
3034      CanDoRT = false;
3035    }
3036  }
3037
3038  if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3039    NumComparisons = 0; // Only one dependence set.
3040  else
3041    NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3042                                           NumWritePtrChecks - 1));
3043  return CanDoRT;
3044}
3045
3046static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3047  return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3048}
3049
3050void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3051  // We process the set twice: first we process read-write pointers, last we
3052  // process read-only pointers. This allows us to skip dependence tests for
3053  // read-only pointers.
3054
3055  PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3056  for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3057    const MemAccessInfo &Access = *AI;
3058    Value *Ptr = Access.getPointer();
3059    bool IsWrite = Access.getInt();
3060
3061    DepCands.insert(Access);
3062
3063    // Memorize read-only pointers for later processing and skip them in the
3064    // first round (they need to be checked after we have seen all write
3065    // pointers). Note: we also mark pointer that are not consecutive as
3066    // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3067    // second check for "!IsWrite".
3068    bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3069    if (!UseDeferred && IsReadOnlyPtr) {
3070      DeferredAccesses.insert(Access);
3071      continue;
3072    }
3073
3074    bool NeedDepCheck = false;
3075    // Check whether there is the possiblity of dependency because of underlying
3076    // objects being the same.
3077    typedef SmallVector<Value*, 16> ValueVector;
3078    ValueVector TempObjects;
3079    GetUnderlyingObjects(Ptr, TempObjects, DL);
3080    for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3081         UI != UE; ++UI) {
3082      Value *UnderlyingObj = *UI;
3083
3084      // If this is a write then it needs to be an identified object.  If this a
3085      // read and all writes (so far) are identified function scope objects we
3086      // don't need an identified underlying object but only an Argument (the
3087      // next write is going to invalidate this assumption if it is
3088      // unidentified).
3089      // This is a micro-optimization for the case where all writes are
3090      // identified and we have one argument pointer.
3091      // Otherwise, we do need a runtime check.
3092      if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3093          (!IsWrite && (!AreAllWritesIdentified ||
3094                        !isa<Argument>(UnderlyingObj)) &&
3095           !isIdentifiedObject(UnderlyingObj))) {
3096        DEBUG(dbgs() << "LV: Found an unidentified " <<
3097              (IsWrite ?  "write" : "read" ) << " ptr:" << *UnderlyingObj <<
3098              "\n");
3099        IsRTCheckNeeded = (IsRTCheckNeeded ||
3100                           !isIdentifiedObject(UnderlyingObj) ||
3101                           !AreAllReadsIdentified);
3102
3103        if (IsWrite)
3104          AreAllWritesIdentified = false;
3105        if (!IsWrite)
3106          AreAllReadsIdentified = false;
3107      }
3108
3109      // If this is a write - check other reads and writes for conflicts.  If
3110      // this is a read only check other writes for conflicts (but only if there
3111      // is no other write to the ptr - this is an optimization to catch "a[i] =
3112      // a[i] + " without having to do a dependence check).
3113      if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3114        NeedDepCheck = true;
3115
3116      if (IsWrite)
3117        WriteObjects.insert(UnderlyingObj);
3118
3119      // Create sets of pointers connected by shared underlying objects.
3120      UnderlyingObjToAccessMap::iterator Prev =
3121        ObjToLastAccess.find(UnderlyingObj);
3122      if (Prev != ObjToLastAccess.end())
3123        DepCands.unionSets(Access, Prev->second);
3124
3125      ObjToLastAccess[UnderlyingObj] = Access;
3126    }
3127
3128    if (NeedDepCheck)
3129      CheckDeps.insert(Access);
3130  }
3131}
3132
3133namespace {
3134/// \brief Checks memory dependences among accesses to the same underlying
3135/// object to determine whether there vectorization is legal or not (and at
3136/// which vectorization factor).
3137///
3138/// This class works under the assumption that we already checked that memory
3139/// locations with different underlying pointers are "must-not alias".
3140/// We use the ScalarEvolution framework to symbolically evalutate access
3141/// functions pairs. Since we currently don't restructure the loop we can rely
3142/// on the program order of memory accesses to determine their safety.
3143/// At the moment we will only deem accesses as safe for:
3144///  * A negative constant distance assuming program order.
3145///
3146///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
3147///            a[i] = tmp;                y = a[i];
3148///
3149///   The latter case is safe because later checks guarantuee that there can't
3150///   be a cycle through a phi node (that is, we check that "x" and "y" is not
3151///   the same variable: a header phi can only be an induction or a reduction, a
3152///   reduction can't have a memory sink, an induction can't have a memory
3153///   source). This is important and must not be violated (or we have to
3154///   resort to checking for cycles through memory).
3155///
3156///  * A positive constant distance assuming program order that is bigger
3157///    than the biggest memory access.
3158///
3159///     tmp = a[i]        OR              b[i] = x
3160///     a[i+2] = tmp                      y = b[i+2];
3161///
3162///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3163///
3164///  * Zero distances and all accesses have the same size.
3165///
3166class MemoryDepChecker {
3167public:
3168  typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3169  typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3170
3171  MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L) :
3172    SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0) {}
3173
3174  /// \brief Register the location (instructions are given increasing numbers)
3175  /// of a write access.
3176  void addAccess(StoreInst *SI) {
3177    Value *Ptr = SI->getPointerOperand();
3178    Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
3179    InstMap.push_back(SI);
3180    ++AccessIdx;
3181  }
3182
3183  /// \brief Register the location (instructions are given increasing numbers)
3184  /// of a write access.
3185  void addAccess(LoadInst *LI) {
3186    Value *Ptr = LI->getPointerOperand();
3187    Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
3188    InstMap.push_back(LI);
3189    ++AccessIdx;
3190  }
3191
3192  /// \brief Check whether the dependencies between the accesses are safe.
3193  ///
3194  /// Only checks sets with elements in \p CheckDeps.
3195  bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3196                   MemAccessInfoSet &CheckDeps);
3197
3198  /// \brief The maximum number of bytes of a vector register we can vectorize
3199  /// the accesses safely with.
3200  unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
3201
3202private:
3203  ScalarEvolution *SE;
3204  DataLayout *DL;
3205  const Loop *InnermostLoop;
3206
3207  /// \brief Maps access locations (ptr, read/write) to program order.
3208  DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
3209
3210  /// \brief Memory access instructions in program order.
3211  SmallVector<Instruction *, 16> InstMap;
3212
3213  /// \brief The program order index to be used for the next instruction.
3214  unsigned AccessIdx;
3215
3216  // We can access this many bytes in parallel safely.
3217  unsigned MaxSafeDepDistBytes;
3218
3219  /// \brief Check whether there is a plausible dependence between the two
3220  /// accesses.
3221  ///
3222  /// Access \p A must happen before \p B in program order. The two indices
3223  /// identify the index into the program order map.
3224  ///
3225  /// This function checks  whether there is a plausible dependence (or the
3226  /// absence of such can't be proved) between the two accesses. If there is a
3227  /// plausible dependence but the dependence distance is bigger than one
3228  /// element access it records this distance in \p MaxSafeDepDistBytes (if this
3229  /// distance is smaller than any other distance encountered so far).
3230  /// Otherwise, this function returns true signaling a possible dependence.
3231  bool isDependent(const MemAccessInfo &A, unsigned AIdx,
3232                   const MemAccessInfo &B, unsigned BIdx);
3233
3234  /// \brief Check whether the data dependence could prevent store-load
3235  /// forwarding.
3236  bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
3237};
3238
3239} // end anonymous namespace
3240
3241static bool isInBoundsGep(Value *Ptr) {
3242  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
3243    return GEP->isInBounds();
3244  return false;
3245}
3246
3247/// \brief Check whether the access through \p Ptr has a constant stride.
3248static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3249                        const Loop *Lp) {
3250  const Type *Ty = Ptr->getType();
3251  assert(Ty->isPointerTy() && "Unexpected non ptr");
3252
3253  // Make sure that the pointer does not point to aggregate types.
3254  const PointerType *PtrTy = cast<PointerType>(Ty);
3255  if (PtrTy->getElementType()->isAggregateType()) {
3256    DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
3257          "\n");
3258    return 0;
3259  }
3260
3261  const SCEV *PtrScev = SE->getSCEV(Ptr);
3262  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3263  if (!AR) {
3264    DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
3265          << *Ptr << " SCEV: " << *PtrScev << "\n");
3266    return 0;
3267  }
3268
3269  // The accesss function must stride over the innermost loop.
3270  if (Lp != AR->getLoop()) {
3271    DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
3272          *Ptr << " SCEV: " << *PtrScev << "\n");
3273  }
3274
3275  // The address calculation must not wrap. Otherwise, a dependence could be
3276  // inverted.
3277  // An inbounds getelementptr that is a AddRec with a unit stride
3278  // cannot wrap per definition. The unit stride requirement is checked later.
3279  // An getelementptr without an inbounds attribute and unit stride would have
3280  // to access the pointer value "0" which is undefined behavior in address
3281  // space 0, therefore we can also vectorize this case.
3282  bool IsInBoundsGEP = isInBoundsGep(Ptr);
3283  bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
3284  bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
3285  if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
3286    DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
3287          << *Ptr << " SCEV: " << *PtrScev << "\n");
3288    return 0;
3289  }
3290
3291  // Check the step is constant.
3292  const SCEV *Step = AR->getStepRecurrence(*SE);
3293
3294  // Calculate the pointer stride and check if it is consecutive.
3295  const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3296  if (!C) {
3297    DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
3298          " SCEV: " << *PtrScev << "\n");
3299    return 0;
3300  }
3301
3302  int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
3303  const APInt &APStepVal = C->getValue()->getValue();
3304
3305  // Huge step value - give up.
3306  if (APStepVal.getBitWidth() > 64)
3307    return 0;
3308
3309  int64_t StepVal = APStepVal.getSExtValue();
3310
3311  // Strided access.
3312  int64_t Stride = StepVal / Size;
3313  int64_t Rem = StepVal % Size;
3314  if (Rem)
3315    return 0;
3316
3317  // If the SCEV could wrap but we have an inbounds gep with a unit stride we
3318  // know we can't "wrap around the address space". In case of address space
3319  // zero we know that this won't happen without triggering undefined behavior.
3320  if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
3321      Stride != 1 && Stride != -1)
3322    return 0;
3323
3324  return Stride;
3325}
3326
3327bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
3328                                                    unsigned TypeByteSize) {
3329  // If loads occur at a distance that is not a multiple of a feasible vector
3330  // factor store-load forwarding does not take place.
3331  // Positive dependences might cause troubles because vectorizing them might
3332  // prevent store-load forwarding making vectorized code run a lot slower.
3333  //   a[i] = a[i-3] ^ a[i-8];
3334  //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
3335  //   hence on your typical architecture store-load forwarding does not take
3336  //   place. Vectorizing in such cases does not make sense.
3337  // Store-load forwarding distance.
3338  const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
3339  // Maximum vector factor.
3340  unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
3341  if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
3342    MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
3343
3344  for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
3345       vf *= 2) {
3346    if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
3347      MaxVFWithoutSLForwardIssues = (vf >>=1);
3348      break;
3349    }
3350  }
3351
3352  if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
3353    DEBUG(dbgs() << "LV: Distance " << Distance <<
3354          " that could cause a store-load forwarding conflict\n");
3355    return true;
3356  }
3357
3358  if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
3359      MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
3360    MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
3361  return false;
3362}
3363
3364bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
3365                                   const MemAccessInfo &B, unsigned BIdx) {
3366  assert (AIdx < BIdx && "Must pass arguments in program order");
3367
3368  Value *APtr = A.getPointer();
3369  Value *BPtr = B.getPointer();
3370  bool AIsWrite = A.getInt();
3371  bool BIsWrite = B.getInt();
3372
3373  // Two reads are independent.
3374  if (!AIsWrite && !BIsWrite)
3375    return false;
3376
3377  const SCEV *AScev = SE->getSCEV(APtr);
3378  const SCEV *BScev = SE->getSCEV(BPtr);
3379
3380  int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop);
3381  int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop);
3382
3383  const SCEV *Src = AScev;
3384  const SCEV *Sink = BScev;
3385
3386  // If the induction step is negative we have to invert source and sink of the
3387  // dependence.
3388  if (StrideAPtr < 0) {
3389    //Src = BScev;
3390    //Sink = AScev;
3391    std::swap(APtr, BPtr);
3392    std::swap(Src, Sink);
3393    std::swap(AIsWrite, BIsWrite);
3394    std::swap(AIdx, BIdx);
3395    std::swap(StrideAPtr, StrideBPtr);
3396  }
3397
3398  const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
3399
3400  DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
3401        << "(Induction step: " << StrideAPtr <<  ")\n");
3402  DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
3403        << *InstMap[BIdx] << ": " << *Dist << "\n");
3404
3405  // Need consecutive accesses. We don't want to vectorize
3406  // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
3407  // the address space.
3408  if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
3409    DEBUG(dbgs() << "Non-consecutive pointer access\n");
3410    return true;
3411  }
3412
3413  const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
3414  if (!C) {
3415    DEBUG(dbgs() << "LV: Dependence because of non constant distance\n");
3416    return true;
3417  }
3418
3419  Type *ATy = APtr->getType()->getPointerElementType();
3420  Type *BTy = BPtr->getType()->getPointerElementType();
3421  unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
3422
3423  // Negative distances are not plausible dependencies.
3424  const APInt &Val = C->getValue()->getValue();
3425  if (Val.isNegative()) {
3426    bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
3427    if (IsTrueDataDependence &&
3428        (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
3429         ATy != BTy))
3430      return true;
3431
3432    DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
3433    return false;
3434  }
3435
3436  // Write to the same location with the same size.
3437  // Could be improved to assert type sizes are the same (i32 == float, etc).
3438  if (Val == 0) {
3439    if (ATy == BTy)
3440      return false;
3441    DEBUG(dbgs() << "LV: Zero dependence difference but different types");
3442    return true;
3443  }
3444
3445  assert(Val.isStrictlyPositive() && "Expect a positive value");
3446
3447  // Positive distance bigger than max vectorization factor.
3448  if (ATy != BTy) {
3449    DEBUG(dbgs() <<
3450          "LV: ReadWrite-Write positive dependency with different types");
3451    return false;
3452  }
3453
3454  unsigned Distance = (unsigned) Val.getZExtValue();
3455
3456  // Bail out early if passed-in parameters make vectorization not feasible.
3457  unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
3458  unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
3459
3460  // The distance must be bigger than the size needed for a vectorized version
3461  // of the operation and the size of the vectorized operation must not be
3462  // bigger than the currrent maximum size.
3463  if (Distance < 2*TypeByteSize ||
3464      2*TypeByteSize > MaxSafeDepDistBytes ||
3465      Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
3466    DEBUG(dbgs() << "LV: Failure because of Positive distance "
3467        << Val.getSExtValue() << "\n");
3468    return true;
3469  }
3470
3471  MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
3472    Distance : MaxSafeDepDistBytes;
3473
3474  bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
3475  if (IsTrueDataDependence &&
3476      couldPreventStoreLoadForward(Distance, TypeByteSize))
3477     return true;
3478
3479  DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
3480        " with max VF=" << MaxSafeDepDistBytes/TypeByteSize << "\n");
3481
3482  return false;
3483}
3484
3485bool
3486MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3487                              MemAccessInfoSet &CheckDeps) {
3488
3489  MaxSafeDepDistBytes = -1U;
3490  while (!CheckDeps.empty()) {
3491    MemAccessInfo CurAccess = *CheckDeps.begin();
3492
3493    // Get the relevant memory access set.
3494    EquivalenceClasses<MemAccessInfo>::iterator I =
3495      AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
3496
3497    // Check accesses within this set.
3498    EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
3499    AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
3500
3501    // Check every access pair.
3502    while (AI != AE) {
3503      CheckDeps.erase(*AI);
3504      EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
3505      while (OI != AE) {
3506        // Check every accessing instruction pair in program order.
3507        for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
3508             I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
3509          for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
3510               I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
3511            if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2))
3512              return false;
3513            if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1))
3514              return false;
3515          }
3516        ++OI;
3517      }
3518      AI++;
3519    }
3520  }
3521  return true;
3522}
3523
3524bool LoopVectorizationLegality::canVectorizeMemory() {
3525
3526  typedef SmallVector<Value*, 16> ValueVector;
3527  typedef SmallPtrSet<Value*, 16> ValueSet;
3528
3529  // Holds the Load and Store *instructions*.
3530  ValueVector Loads;
3531  ValueVector Stores;
3532
3533  // Holds all the different accesses in the loop.
3534  unsigned NumReads = 0;
3535  unsigned NumReadWrites = 0;
3536
3537  PtrRtCheck.Pointers.clear();
3538  PtrRtCheck.Need = false;
3539
3540  const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
3541  MemoryDepChecker DepChecker(SE, DL, TheLoop);
3542
3543  // For each block.
3544  for (Loop::block_iterator bb = TheLoop->block_begin(),
3545       be = TheLoop->block_end(); bb != be; ++bb) {
3546
3547    // Scan the BB and collect legal loads and stores.
3548    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3549         ++it) {
3550
3551      // If this is a load, save it. If this instruction can read from memory
3552      // but is not a load, then we quit. Notice that we don't handle function
3553      // calls that read or write.
3554      if (it->mayReadFromMemory()) {
3555        // Many math library functions read the rounding mode. We will only
3556        // vectorize a loop if it contains known function calls that don't set
3557        // the flag. Therefore, it is safe to ignore this read from memory.
3558        CallInst *Call = dyn_cast<CallInst>(it);
3559        if (Call && getIntrinsicIDForCall(Call, TLI))
3560          continue;
3561
3562        LoadInst *Ld = dyn_cast<LoadInst>(it);
3563        if (!Ld) return false;
3564        if (!Ld->isSimple() && !IsAnnotatedParallel) {
3565          DEBUG(dbgs() << "LV: Found a non-simple load.\n");
3566          return false;
3567        }
3568        Loads.push_back(Ld);
3569        DepChecker.addAccess(Ld);
3570        continue;
3571      }
3572
3573      // Save 'store' instructions. Abort if other instructions write to memory.
3574      if (it->mayWriteToMemory()) {
3575        StoreInst *St = dyn_cast<StoreInst>(it);
3576        if (!St) return false;
3577        if (!St->isSimple() && !IsAnnotatedParallel) {
3578          DEBUG(dbgs() << "LV: Found a non-simple store.\n");
3579          return false;
3580        }
3581        Stores.push_back(St);
3582        DepChecker.addAccess(St);
3583      }
3584    } // next instr.
3585  } // next block.
3586
3587  // Now we have two lists that hold the loads and the stores.
3588  // Next, we find the pointers that they use.
3589
3590  // Check if we see any stores. If there are no stores, then we don't
3591  // care if the pointers are *restrict*.
3592  if (!Stores.size()) {
3593    DEBUG(dbgs() << "LV: Found a read-only loop!\n");
3594    return true;
3595  }
3596
3597  AccessAnalysis::DepCandidates DependentAccesses;
3598  AccessAnalysis Accesses(DL, DependentAccesses);
3599
3600  // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
3601  // multiple times on the same object. If the ptr is accessed twice, once
3602  // for read and once for write, it will only appear once (on the write
3603  // list). This is okay, since we are going to check for conflicts between
3604  // writes and between reads and writes, but not between reads and reads.
3605  ValueSet Seen;
3606
3607  ValueVector::iterator I, IE;
3608  for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
3609    StoreInst *ST = cast<StoreInst>(*I);
3610    Value* Ptr = ST->getPointerOperand();
3611
3612    if (isUniform(Ptr)) {
3613      DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
3614      return false;
3615    }
3616
3617    // If we did *not* see this pointer before, insert it to  the read-write
3618    // list. At this phase it is only a 'write' list.
3619    if (Seen.insert(Ptr)) {
3620      ++NumReadWrites;
3621      Accesses.addStore(Ptr);
3622    }
3623  }
3624
3625  if (IsAnnotatedParallel) {
3626    DEBUG(dbgs()
3627          << "LV: A loop annotated parallel, ignore memory dependency "
3628          << "checks.\n");
3629    return true;
3630  }
3631
3632  SmallPtrSet<Value *, 16> ReadOnlyPtr;
3633  for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
3634    LoadInst *LD = cast<LoadInst>(*I);
3635    Value* Ptr = LD->getPointerOperand();
3636    // If we did *not* see this pointer before, insert it to the
3637    // read list. If we *did* see it before, then it is already in
3638    // the read-write list. This allows us to vectorize expressions
3639    // such as A[i] += x;  Because the address of A[i] is a read-write
3640    // pointer. This only works if the index of A[i] is consecutive.
3641    // If the address of i is unknown (for example A[B[i]]) then we may
3642    // read a few words, modify, and write a few words, and some of the
3643    // words may be written to the same address.
3644    bool IsReadOnlyPtr = false;
3645    if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop)) {
3646      ++NumReads;
3647      IsReadOnlyPtr = true;
3648    }
3649    Accesses.addLoad(Ptr, IsReadOnlyPtr);
3650  }
3651
3652  // If we write (or read-write) to a single destination and there are no
3653  // other reads in this loop then is it safe to vectorize.
3654  if (NumReadWrites == 1 && NumReads == 0) {
3655    DEBUG(dbgs() << "LV: Found a write-only loop!\n");
3656    return true;
3657  }
3658
3659  // Build dependence sets and check whether we need a runtime pointer bounds
3660  // check.
3661  Accesses.buildDependenceSets();
3662  bool NeedRTCheck = Accesses.isRTCheckNeeded();
3663
3664  // Find pointers with computable bounds. We are going to use this information
3665  // to place a runtime bound check.
3666  unsigned NumComparisons = 0;
3667  bool CanDoRT = false;
3668  if (NeedRTCheck)
3669    CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop);
3670
3671
3672  DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
3673        " pointer comparisons.\n");
3674
3675  // If we only have one set of dependences to check pointers among we don't
3676  // need a runtime check.
3677  if (NumComparisons == 0 && NeedRTCheck)
3678    NeedRTCheck = false;
3679
3680  // Check that we did not collect too many pointers or found a unsizeable
3681  // pointer.
3682  if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
3683    PtrRtCheck.reset();
3684    CanDoRT = false;
3685  }
3686
3687  if (CanDoRT) {
3688    DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
3689  }
3690
3691  if (NeedRTCheck && !CanDoRT) {
3692    DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
3693          "the array bounds.\n");
3694    PtrRtCheck.reset();
3695    return false;
3696  }
3697
3698  PtrRtCheck.Need = NeedRTCheck;
3699
3700  bool CanVecMem = true;
3701  if (Accesses.isDependencyCheckNeeded()) {
3702    DEBUG(dbgs() << "LV: Checking memory dependencies\n");
3703    CanVecMem = DepChecker.areDepsSafe(DependentAccesses,
3704                                       Accesses.getDependenciesToCheck());
3705    MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
3706  }
3707
3708  DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
3709        " need a runtime memory check.\n");
3710
3711  return CanVecMem;
3712}
3713
3714static bool hasMultipleUsesOf(Instruction *I,
3715                              SmallPtrSet<Instruction *, 8> &Insts) {
3716  unsigned NumUses = 0;
3717  for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3718    if (Insts.count(dyn_cast<Instruction>(*Use)))
3719      ++NumUses;
3720    if (NumUses > 1)
3721      return true;
3722  }
3723
3724  return false;
3725}
3726
3727static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
3728  for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3729    if (!Set.count(dyn_cast<Instruction>(*Use)))
3730      return false;
3731  return true;
3732}
3733
3734bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3735                                                ReductionKind Kind) {
3736  if (Phi->getNumIncomingValues() != 2)
3737    return false;
3738
3739  // Reduction variables are only found in the loop header block.
3740  if (Phi->getParent() != TheLoop->getHeader())
3741    return false;
3742
3743  // Obtain the reduction start value from the value that comes from the loop
3744  // preheader.
3745  Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3746
3747  // ExitInstruction is the single value which is used outside the loop.
3748  // We only allow for a single reduction value to be used outside the loop.
3749  // This includes users of the reduction, variables (which form a cycle
3750  // which ends in the phi node).
3751  Instruction *ExitInstruction = 0;
3752  // Indicates that we found a reduction operation in our scan.
3753  bool FoundReduxOp = false;
3754
3755  // We start with the PHI node and scan for all of the users of this
3756  // instruction. All users must be instructions that can be used as reduction
3757  // variables (such as ADD). We must have a single out-of-block user. The cycle
3758  // must include the original PHI.
3759  bool FoundStartPHI = false;
3760
3761  // To recognize min/max patterns formed by a icmp select sequence, we store
3762  // the number of instruction we saw from the recognized min/max pattern,
3763  //  to make sure we only see exactly the two instructions.
3764  unsigned NumCmpSelectPatternInst = 0;
3765  ReductionInstDesc ReduxDesc(false, 0);
3766
3767  SmallPtrSet<Instruction *, 8> VisitedInsts;
3768  SmallVector<Instruction *, 8> Worklist;
3769  Worklist.push_back(Phi);
3770  VisitedInsts.insert(Phi);
3771
3772  // A value in the reduction can be used:
3773  //  - By the reduction:
3774  //      - Reduction operation:
3775  //        - One use of reduction value (safe).
3776  //        - Multiple use of reduction value (not safe).
3777  //      - PHI:
3778  //        - All uses of the PHI must be the reduction (safe).
3779  //        - Otherwise, not safe.
3780  //  - By one instruction outside of the loop (safe).
3781  //  - By further instructions outside of the loop (not safe).
3782  //  - By an instruction that is not part of the reduction (not safe).
3783  //    This is either:
3784  //      * An instruction type other than PHI or the reduction operation.
3785  //      * A PHI in the header other than the initial PHI.
3786  while (!Worklist.empty()) {
3787    Instruction *Cur = Worklist.back();
3788    Worklist.pop_back();
3789
3790    // No Users.
3791    // If the instruction has no users then this is a broken chain and can't be
3792    // a reduction variable.
3793    if (Cur->use_empty())
3794      return false;
3795
3796    bool IsAPhi = isa<PHINode>(Cur);
3797
3798    // A header PHI use other than the original PHI.
3799    if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3800      return false;
3801
3802    // Reductions of instructions such as Div, and Sub is only possible if the
3803    // LHS is the reduction variable.
3804    if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3805        !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3806        !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3807      return false;
3808
3809    // Any reduction instruction must be of one of the allowed kinds.
3810    ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3811    if (!ReduxDesc.IsReduction)
3812      return false;
3813
3814    // A reduction operation must only have one use of the reduction value.
3815    if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3816        hasMultipleUsesOf(Cur, VisitedInsts))
3817      return false;
3818
3819    // All inputs to a PHI node must be a reduction value.
3820    if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3821      return false;
3822
3823    if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3824                                     isa<SelectInst>(Cur)))
3825      ++NumCmpSelectPatternInst;
3826    if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3827                                   isa<SelectInst>(Cur)))
3828      ++NumCmpSelectPatternInst;
3829
3830    // Check  whether we found a reduction operator.
3831    FoundReduxOp |= !IsAPhi;
3832
3833    // Process users of current instruction. Push non PHI nodes after PHI nodes
3834    // onto the stack. This way we are going to have seen all inputs to PHI
3835    // nodes once we get to them.
3836    SmallVector<Instruction *, 8> NonPHIs;
3837    SmallVector<Instruction *, 8> PHIs;
3838    for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
3839         ++UI) {
3840      Instruction *Usr = cast<Instruction>(*UI);
3841
3842      // Check if we found the exit user.
3843      BasicBlock *Parent = Usr->getParent();
3844      if (!TheLoop->contains(Parent)) {
3845        // Exit if you find multiple outside users or if the header phi node is
3846        // being used. In this case the user uses the value of the previous
3847        // iteration, in which case we would loose "VF-1" iterations of the
3848        // reduction operation if we vectorize.
3849        if (ExitInstruction != 0 || Cur == Phi)
3850          return false;
3851
3852        ExitInstruction = Cur;
3853        continue;
3854      }
3855
3856      // Process instructions only once (termination).
3857      if (VisitedInsts.insert(Usr)) {
3858        if (isa<PHINode>(Usr))
3859          PHIs.push_back(Usr);
3860        else
3861          NonPHIs.push_back(Usr);
3862      }
3863      // Remember that we completed the cycle.
3864      if (Usr == Phi)
3865        FoundStartPHI = true;
3866    }
3867    Worklist.append(PHIs.begin(), PHIs.end());
3868    Worklist.append(NonPHIs.begin(), NonPHIs.end());
3869  }
3870
3871  // This means we have seen one but not the other instruction of the
3872  // pattern or more than just a select and cmp.
3873  if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
3874      NumCmpSelectPatternInst != 2)
3875    return false;
3876
3877  if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
3878    return false;
3879
3880  // We found a reduction var if we have reached the original phi node and we
3881  // only have a single instruction with out-of-loop users.
3882
3883  // This instruction is allowed to have out-of-loop users.
3884  AllowedExit.insert(ExitInstruction);
3885
3886  // Save the description of this reduction variable.
3887  ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
3888                         ReduxDesc.MinMaxKind);
3889  Reductions[Phi] = RD;
3890  // We've ended the cycle. This is a reduction variable if we have an
3891  // outside user and it has a binary op.
3892
3893  return true;
3894}
3895
3896/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
3897/// pattern corresponding to a min(X, Y) or max(X, Y).
3898LoopVectorizationLegality::ReductionInstDesc
3899LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
3900                                                    ReductionInstDesc &Prev) {
3901
3902  assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
3903         "Expect a select instruction");
3904  Instruction *Cmp = 0;
3905  SelectInst *Select = 0;
3906
3907  // We must handle the select(cmp()) as a single instruction. Advance to the
3908  // select.
3909  if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
3910    if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
3911      return ReductionInstDesc(false, I);
3912    return ReductionInstDesc(Select, Prev.MinMaxKind);
3913  }
3914
3915  // Only handle single use cases for now.
3916  if (!(Select = dyn_cast<SelectInst>(I)))
3917    return ReductionInstDesc(false, I);
3918  if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
3919      !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
3920    return ReductionInstDesc(false, I);
3921  if (!Cmp->hasOneUse())
3922    return ReductionInstDesc(false, I);
3923
3924  Value *CmpLeft;
3925  Value *CmpRight;
3926
3927  // Look for a min/max pattern.
3928  if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3929    return ReductionInstDesc(Select, MRK_UIntMin);
3930  else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3931    return ReductionInstDesc(Select, MRK_UIntMax);
3932  else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3933    return ReductionInstDesc(Select, MRK_SIntMax);
3934  else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3935    return ReductionInstDesc(Select, MRK_SIntMin);
3936  else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3937    return ReductionInstDesc(Select, MRK_FloatMin);
3938  else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3939    return ReductionInstDesc(Select, MRK_FloatMax);
3940  else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3941    return ReductionInstDesc(Select, MRK_FloatMin);
3942  else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3943    return ReductionInstDesc(Select, MRK_FloatMax);
3944
3945  return ReductionInstDesc(false, I);
3946}
3947
3948LoopVectorizationLegality::ReductionInstDesc
3949LoopVectorizationLegality::isReductionInstr(Instruction *I,
3950                                            ReductionKind Kind,
3951                                            ReductionInstDesc &Prev) {
3952  bool FP = I->getType()->isFloatingPointTy();
3953  bool FastMath = (FP && I->isCommutative() && I->isAssociative());
3954  switch (I->getOpcode()) {
3955  default:
3956    return ReductionInstDesc(false, I);
3957  case Instruction::PHI:
3958      if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
3959                 Kind != RK_FloatMinMax))
3960        return ReductionInstDesc(false, I);
3961    return ReductionInstDesc(I, Prev.MinMaxKind);
3962  case Instruction::Sub:
3963  case Instruction::Add:
3964    return ReductionInstDesc(Kind == RK_IntegerAdd, I);
3965  case Instruction::Mul:
3966    return ReductionInstDesc(Kind == RK_IntegerMult, I);
3967  case Instruction::And:
3968    return ReductionInstDesc(Kind == RK_IntegerAnd, I);
3969  case Instruction::Or:
3970    return ReductionInstDesc(Kind == RK_IntegerOr, I);
3971  case Instruction::Xor:
3972    return ReductionInstDesc(Kind == RK_IntegerXor, I);
3973  case Instruction::FMul:
3974    return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
3975  case Instruction::FAdd:
3976    return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
3977  case Instruction::FCmp:
3978  case Instruction::ICmp:
3979  case Instruction::Select:
3980    if (Kind != RK_IntegerMinMax &&
3981        (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
3982      return ReductionInstDesc(false, I);
3983    return isMinMaxSelectCmpPattern(I, Prev);
3984  }
3985}
3986
3987LoopVectorizationLegality::InductionKind
3988LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
3989  Type *PhiTy = Phi->getType();
3990  // We only handle integer and pointer inductions variables.
3991  if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
3992    return IK_NoInduction;
3993
3994  // Check that the PHI is consecutive.
3995  const SCEV *PhiScev = SE->getSCEV(Phi);
3996  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3997  if (!AR) {
3998    DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
3999    return IK_NoInduction;
4000  }
4001  const SCEV *Step = AR->getStepRecurrence(*SE);
4002
4003  // Integer inductions need to have a stride of one.
4004  if (PhiTy->isIntegerTy()) {
4005    if (Step->isOne())
4006      return IK_IntInduction;
4007    if (Step->isAllOnesValue())
4008      return IK_ReverseIntInduction;
4009    return IK_NoInduction;
4010  }
4011
4012  // Calculate the pointer stride and check if it is consecutive.
4013  const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4014  if (!C)
4015    return IK_NoInduction;
4016
4017  assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4018  uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4019  if (C->getValue()->equalsInt(Size))
4020    return IK_PtrInduction;
4021  else if (C->getValue()->equalsInt(0 - Size))
4022    return IK_ReversePtrInduction;
4023
4024  return IK_NoInduction;
4025}
4026
4027bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4028  Value *In0 = const_cast<Value*>(V);
4029  PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4030  if (!PN)
4031    return false;
4032
4033  return Inductions.count(PN);
4034}
4035
4036bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
4037  assert(TheLoop->contains(BB) && "Unknown block used");
4038
4039  // Blocks that do not dominate the latch need predication.
4040  BasicBlock* Latch = TheLoop->getLoopLatch();
4041  return !DT->dominates(BB, Latch);
4042}
4043
4044bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4045                                            SmallPtrSet<Value *, 8>& SafePtrs) {
4046  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4047    // We might be able to hoist the load.
4048    if (it->mayReadFromMemory()) {
4049      LoadInst *LI = dyn_cast<LoadInst>(it);
4050      if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4051        return false;
4052    }
4053
4054    // We don't predicate stores at the moment.
4055    if (it->mayWriteToMemory() || it->mayThrow())
4056      return false;
4057
4058    // The instructions below can trap.
4059    switch (it->getOpcode()) {
4060    default: continue;
4061    case Instruction::UDiv:
4062    case Instruction::SDiv:
4063    case Instruction::URem:
4064    case Instruction::SRem:
4065             return false;
4066    }
4067  }
4068
4069  return true;
4070}
4071
4072LoopVectorizationCostModel::VectorizationFactor
4073LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4074                                                      unsigned UserVF) {
4075  // Width 1 means no vectorize
4076  VectorizationFactor Factor = { 1U, 0U };
4077  if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4078    DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4079    return Factor;
4080  }
4081
4082  // Find the trip count.
4083  unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4084  DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
4085
4086  unsigned WidestType = getWidestType();
4087  unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4088  unsigned MaxSafeDepDist = -1U;
4089  if (Legal->getMaxSafeDepDistBytes() != -1U)
4090    MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4091  WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4092                    WidestRegister : MaxSafeDepDist);
4093  unsigned MaxVectorSize = WidestRegister / WidestType;
4094  DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4095  DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
4096
4097  if (MaxVectorSize == 0) {
4098    DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4099    MaxVectorSize = 1;
4100  }
4101
4102  assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4103         " into one vector!");
4104
4105  unsigned VF = MaxVectorSize;
4106
4107  // If we optimize the program for size, avoid creating the tail loop.
4108  if (OptForSize) {
4109    // If we are unable to calculate the trip count then don't try to vectorize.
4110    if (TC < 2) {
4111      DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4112      return Factor;
4113    }
4114
4115    // Find the maximum SIMD width that can fit within the trip count.
4116    VF = TC % MaxVectorSize;
4117
4118    if (VF == 0)
4119      VF = MaxVectorSize;
4120
4121    // If the trip count that we found modulo the vectorization factor is not
4122    // zero then we require a tail.
4123    if (VF < 2) {
4124      DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4125      return Factor;
4126    }
4127  }
4128
4129  if (UserVF != 0) {
4130    assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4131    DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
4132
4133    Factor.Width = UserVF;
4134    return Factor;
4135  }
4136
4137  float Cost = expectedCost(1);
4138  unsigned Width = 1;
4139  DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
4140  for (unsigned i=2; i <= VF; i*=2) {
4141    // Notice that the vector loop needs to be executed less times, so
4142    // we need to divide the cost of the vector loops by the width of
4143    // the vector elements.
4144    float VectorCost = expectedCost(i) / (float)i;
4145    DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
4146          (int)VectorCost << ".\n");
4147    if (VectorCost < Cost) {
4148      Cost = VectorCost;
4149      Width = i;
4150    }
4151  }
4152
4153  DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
4154  Factor.Width = Width;
4155  Factor.Cost = Width * Cost;
4156  return Factor;
4157}
4158
4159unsigned LoopVectorizationCostModel::getWidestType() {
4160  unsigned MaxWidth = 8;
4161
4162  // For each block.
4163  for (Loop::block_iterator bb = TheLoop->block_begin(),
4164       be = TheLoop->block_end(); bb != be; ++bb) {
4165    BasicBlock *BB = *bb;
4166
4167    // For each instruction in the loop.
4168    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4169      Type *T = it->getType();
4170
4171      // Only examine Loads, Stores and PHINodes.
4172      if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4173        continue;
4174
4175      // Examine PHI nodes that are reduction variables.
4176      if (PHINode *PN = dyn_cast<PHINode>(it))
4177        if (!Legal->getReductionVars()->count(PN))
4178          continue;
4179
4180      // Examine the stored values.
4181      if (StoreInst *ST = dyn_cast<StoreInst>(it))
4182        T = ST->getValueOperand()->getType();
4183
4184      // Ignore loaded pointer types and stored pointer types that are not
4185      // consecutive. However, we do want to take consecutive stores/loads of
4186      // pointer vectors into account.
4187      if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4188        continue;
4189
4190      MaxWidth = std::max(MaxWidth,
4191                          (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4192    }
4193  }
4194
4195  return MaxWidth;
4196}
4197
4198unsigned
4199LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4200                                               unsigned UserUF,
4201                                               unsigned VF,
4202                                               unsigned LoopCost) {
4203
4204  // -- The unroll heuristics --
4205  // We unroll the loop in order to expose ILP and reduce the loop overhead.
4206  // There are many micro-architectural considerations that we can't predict
4207  // at this level. For example frontend pressure (on decode or fetch) due to
4208  // code size, or the number and capabilities of the execution ports.
4209  //
4210  // We use the following heuristics to select the unroll factor:
4211  // 1. If the code has reductions the we unroll in order to break the cross
4212  // iteration dependency.
4213  // 2. If the loop is really small then we unroll in order to reduce the loop
4214  // overhead.
4215  // 3. We don't unroll if we think that we will spill registers to memory due
4216  // to the increased register pressure.
4217
4218  // Use the user preference, unless 'auto' is selected.
4219  if (UserUF != 0)
4220    return UserUF;
4221
4222  // When we optimize for size we don't unroll.
4223  if (OptForSize)
4224    return 1;
4225
4226  // We used the distance for the unroll factor.
4227  if (Legal->getMaxSafeDepDistBytes() != -1U)
4228    return 1;
4229
4230  // Do not unroll loops with a relatively small trip count.
4231  unsigned TC = SE->getSmallConstantTripCount(TheLoop,
4232                                              TheLoop->getLoopLatch());
4233  if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4234    return 1;
4235
4236  unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
4237  DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
4238        " vector registers\n");
4239
4240  LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4241  // We divide by these constants so assume that we have at least one
4242  // instruction that uses at least one register.
4243  R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4244  R.NumInstructions = std::max(R.NumInstructions, 1U);
4245
4246  // We calculate the unroll factor using the following formula.
4247  // Subtract the number of loop invariants from the number of available
4248  // registers. These registers are used by all of the unrolled instances.
4249  // Next, divide the remaining registers by the number of registers that is
4250  // required by the loop, in order to estimate how many parallel instances
4251  // fit without causing spills.
4252  unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
4253
4254  // Clamp the unroll factor ranges to reasonable factors.
4255  unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
4256
4257  // If we did not calculate the cost for VF (because the user selected the VF)
4258  // then we calculate the cost of VF here.
4259  if (LoopCost == 0)
4260    LoopCost = expectedCost(VF);
4261
4262  // Clamp the calculated UF to be between the 1 and the max unroll factor
4263  // that the target allows.
4264  if (UF > MaxUnrollSize)
4265    UF = MaxUnrollSize;
4266  else if (UF < 1)
4267    UF = 1;
4268
4269  if (Legal->getReductionVars()->size()) {
4270    DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
4271    return UF;
4272  }
4273
4274  // We want to unroll tiny loops in order to reduce the loop overhead.
4275  // We assume that the cost overhead is 1 and we use the cost model
4276  // to estimate the cost of the loop and unroll until the cost of the
4277  // loop overhead is about 5% of the cost of the loop.
4278  DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
4279  if (LoopCost < 20) {
4280    DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
4281    unsigned NewUF = 20/LoopCost + 1;
4282    return std::min(NewUF, UF);
4283  }
4284
4285  DEBUG(dbgs() << "LV: Not Unrolling. \n");
4286  return 1;
4287}
4288
4289LoopVectorizationCostModel::RegisterUsage
4290LoopVectorizationCostModel::calculateRegisterUsage() {
4291  // This function calculates the register usage by measuring the highest number
4292  // of values that are alive at a single location. Obviously, this is a very
4293  // rough estimation. We scan the loop in a topological order in order and
4294  // assign a number to each instruction. We use RPO to ensure that defs are
4295  // met before their users. We assume that each instruction that has in-loop
4296  // users starts an interval. We record every time that an in-loop value is
4297  // used, so we have a list of the first and last occurrences of each
4298  // instruction. Next, we transpose this data structure into a multi map that
4299  // holds the list of intervals that *end* at a specific location. This multi
4300  // map allows us to perform a linear search. We scan the instructions linearly
4301  // and record each time that a new interval starts, by placing it in a set.
4302  // If we find this value in the multi-map then we remove it from the set.
4303  // The max register usage is the maximum size of the set.
4304  // We also search for instructions that are defined outside the loop, but are
4305  // used inside the loop. We need this number separately from the max-interval
4306  // usage number because when we unroll, loop-invariant values do not take
4307  // more register.
4308  LoopBlocksDFS DFS(TheLoop);
4309  DFS.perform(LI);
4310
4311  RegisterUsage R;
4312  R.NumInstructions = 0;
4313
4314  // Each 'key' in the map opens a new interval. The values
4315  // of the map are the index of the 'last seen' usage of the
4316  // instruction that is the key.
4317  typedef DenseMap<Instruction*, unsigned> IntervalMap;
4318  // Maps instruction to its index.
4319  DenseMap<unsigned, Instruction*> IdxToInstr;
4320  // Marks the end of each interval.
4321  IntervalMap EndPoint;
4322  // Saves the list of instruction indices that are used in the loop.
4323  SmallSet<Instruction*, 8> Ends;
4324  // Saves the list of values that are used in the loop but are
4325  // defined outside the loop, such as arguments and constants.
4326  SmallPtrSet<Value*, 8> LoopInvariants;
4327
4328  unsigned Index = 0;
4329  for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4330       be = DFS.endRPO(); bb != be; ++bb) {
4331    R.NumInstructions += (*bb)->size();
4332    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4333         ++it) {
4334      Instruction *I = it;
4335      IdxToInstr[Index++] = I;
4336
4337      // Save the end location of each USE.
4338      for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4339        Value *U = I->getOperand(i);
4340        Instruction *Instr = dyn_cast<Instruction>(U);
4341
4342        // Ignore non-instruction values such as arguments, constants, etc.
4343        if (!Instr) continue;
4344
4345        // If this instruction is outside the loop then record it and continue.
4346        if (!TheLoop->contains(Instr)) {
4347          LoopInvariants.insert(Instr);
4348          continue;
4349        }
4350
4351        // Overwrite previous end points.
4352        EndPoint[Instr] = Index;
4353        Ends.insert(Instr);
4354      }
4355    }
4356  }
4357
4358  // Saves the list of intervals that end with the index in 'key'.
4359  typedef SmallVector<Instruction*, 2> InstrList;
4360  DenseMap<unsigned, InstrList> TransposeEnds;
4361
4362  // Transpose the EndPoints to a list of values that end at each index.
4363  for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4364       it != e; ++it)
4365    TransposeEnds[it->second].push_back(it->first);
4366
4367  SmallSet<Instruction*, 8> OpenIntervals;
4368  unsigned MaxUsage = 0;
4369
4370
4371  DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4372  for (unsigned int i = 0; i < Index; ++i) {
4373    Instruction *I = IdxToInstr[i];
4374    // Ignore instructions that are never used within the loop.
4375    if (!Ends.count(I)) continue;
4376
4377    // Remove all of the instructions that end at this location.
4378    InstrList &List = TransposeEnds[i];
4379    for (unsigned int j=0, e = List.size(); j < e; ++j)
4380      OpenIntervals.erase(List[j]);
4381
4382    // Count the number of live interals.
4383    MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4384
4385    DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4386          OpenIntervals.size() <<"\n");
4387
4388    // Add the current instruction to the list of open intervals.
4389    OpenIntervals.insert(I);
4390  }
4391
4392  unsigned Invariant = LoopInvariants.size();
4393  DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
4394  DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
4395  DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
4396
4397  R.LoopInvariantRegs = Invariant;
4398  R.MaxLocalUsers = MaxUsage;
4399  return R;
4400}
4401
4402unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4403  unsigned Cost = 0;
4404
4405  // For each block.
4406  for (Loop::block_iterator bb = TheLoop->block_begin(),
4407       be = TheLoop->block_end(); bb != be; ++bb) {
4408    unsigned BlockCost = 0;
4409    BasicBlock *BB = *bb;
4410
4411    // For each instruction in the old loop.
4412    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4413      // Skip dbg intrinsics.
4414      if (isa<DbgInfoIntrinsic>(it))
4415        continue;
4416
4417      unsigned C = getInstructionCost(it, VF);
4418      BlockCost += C;
4419      DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
4420            VF << " For instruction: "<< *it << "\n");
4421    }
4422
4423    // We assume that if-converted blocks have a 50% chance of being executed.
4424    // When the code is scalar then some of the blocks are avoided due to CF.
4425    // When the code is vectorized we execute all code paths.
4426    if (VF == 1 && Legal->blockNeedsPredication(*bb))
4427      BlockCost /= 2;
4428
4429    Cost += BlockCost;
4430  }
4431
4432  return Cost;
4433}
4434
4435/// \brief Check whether the address computation for a non-consecutive memory
4436/// access looks like an unlikely candidate for being merged into the indexing
4437/// mode.
4438///
4439/// We look for a GEP which has one index that is an induction variable and all
4440/// other indices are loop invariant. If the stride of this access is also
4441/// within a small bound we decide that this address computation can likely be
4442/// merged into the addressing mode.
4443/// In all other cases, we identify the address computation as complex.
4444static bool isLikelyComplexAddressComputation(Value *Ptr,
4445                                              LoopVectorizationLegality *Legal,
4446                                              ScalarEvolution *SE,
4447                                              const Loop *TheLoop) {
4448  GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
4449  if (!Gep)
4450    return true;
4451
4452  // We are looking for a gep with all loop invariant indices except for one
4453  // which should be an induction variable.
4454  unsigned NumOperands = Gep->getNumOperands();
4455  for (unsigned i = 1; i < NumOperands; ++i) {
4456    Value *Opd = Gep->getOperand(i);
4457    if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
4458        !Legal->isInductionVariable(Opd))
4459      return true;
4460  }
4461
4462  // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
4463  // can likely be merged into the address computation.
4464  unsigned MaxMergeDistance = 64;
4465
4466  const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
4467  if (!AddRec)
4468    return true;
4469
4470  // Check the step is constant.
4471  const SCEV *Step = AddRec->getStepRecurrence(*SE);
4472  // Calculate the pointer stride and check if it is consecutive.
4473  const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4474  if (!C)
4475    return true;
4476
4477  const APInt &APStepVal = C->getValue()->getValue();
4478
4479  // Huge step value - give up.
4480  if (APStepVal.getBitWidth() > 64)
4481    return true;
4482
4483  int64_t StepVal = APStepVal.getSExtValue();
4484
4485  return StepVal > MaxMergeDistance;
4486}
4487
4488unsigned
4489LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4490  // If we know that this instruction will remain uniform, check the cost of
4491  // the scalar version.
4492  if (Legal->isUniformAfterVectorization(I))
4493    VF = 1;
4494
4495  Type *RetTy = I->getType();
4496  Type *VectorTy = ToVectorTy(RetTy, VF);
4497
4498  // TODO: We need to estimate the cost of intrinsic calls.
4499  switch (I->getOpcode()) {
4500  case Instruction::GetElementPtr:
4501    // We mark this instruction as zero-cost because the cost of GEPs in
4502    // vectorized code depends on whether the corresponding memory instruction
4503    // is scalarized or not. Therefore, we handle GEPs with the memory
4504    // instruction cost.
4505    return 0;
4506  case Instruction::Br: {
4507    return TTI.getCFInstrCost(I->getOpcode());
4508  }
4509  case Instruction::PHI:
4510    //TODO: IF-converted IFs become selects.
4511    return 0;
4512  case Instruction::Add:
4513  case Instruction::FAdd:
4514  case Instruction::Sub:
4515  case Instruction::FSub:
4516  case Instruction::Mul:
4517  case Instruction::FMul:
4518  case Instruction::UDiv:
4519  case Instruction::SDiv:
4520  case Instruction::FDiv:
4521  case Instruction::URem:
4522  case Instruction::SRem:
4523  case Instruction::FRem:
4524  case Instruction::Shl:
4525  case Instruction::LShr:
4526  case Instruction::AShr:
4527  case Instruction::And:
4528  case Instruction::Or:
4529  case Instruction::Xor: {
4530    // Certain instructions can be cheaper to vectorize if they have a constant
4531    // second vector operand. One example of this are shifts on x86.
4532    TargetTransformInfo::OperandValueKind Op1VK =
4533      TargetTransformInfo::OK_AnyValue;
4534    TargetTransformInfo::OperandValueKind Op2VK =
4535      TargetTransformInfo::OK_AnyValue;
4536
4537    if (isa<ConstantInt>(I->getOperand(1)))
4538      Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4539
4540    return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
4541  }
4542  case Instruction::Select: {
4543    SelectInst *SI = cast<SelectInst>(I);
4544    const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4545    bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4546    Type *CondTy = SI->getCondition()->getType();
4547    if (!ScalarCond)
4548      CondTy = VectorType::get(CondTy, VF);
4549
4550    return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4551  }
4552  case Instruction::ICmp:
4553  case Instruction::FCmp: {
4554    Type *ValTy = I->getOperand(0)->getType();
4555    VectorTy = ToVectorTy(ValTy, VF);
4556    return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4557  }
4558  case Instruction::Store:
4559  case Instruction::Load: {
4560    StoreInst *SI = dyn_cast<StoreInst>(I);
4561    LoadInst *LI = dyn_cast<LoadInst>(I);
4562    Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4563                   LI->getType());
4564    VectorTy = ToVectorTy(ValTy, VF);
4565
4566    unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4567    unsigned AS = SI ? SI->getPointerAddressSpace() :
4568      LI->getPointerAddressSpace();
4569    Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4570    // We add the cost of address computation here instead of with the gep
4571    // instruction because only here we know whether the operation is
4572    // scalarized.
4573    if (VF == 1)
4574      return TTI.getAddressComputationCost(VectorTy) +
4575        TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4576
4577    // Scalarized loads/stores.
4578    int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4579    bool Reverse = ConsecutiveStride < 0;
4580    unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
4581    unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
4582    if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4583      bool IsComplexComputation =
4584        isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
4585      unsigned Cost = 0;
4586      // The cost of extracting from the value vector and pointer vector.
4587      Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4588      for (unsigned i = 0; i < VF; ++i) {
4589        //  The cost of extracting the pointer operand.
4590        Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4591        // In case of STORE, the cost of ExtractElement from the vector.
4592        // In case of LOAD, the cost of InsertElement into the returned
4593        // vector.
4594        Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
4595                                            Instruction::InsertElement,
4596                                            VectorTy, i);
4597      }
4598
4599      // The cost of the scalar loads/stores.
4600      Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
4601      Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
4602                                       Alignment, AS);
4603      return Cost;
4604    }
4605
4606    // Wide load/stores.
4607    unsigned Cost = TTI.getAddressComputationCost(VectorTy);
4608    Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4609
4610    if (Reverse)
4611      Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4612                                  VectorTy, 0);
4613    return Cost;
4614  }
4615  case Instruction::ZExt:
4616  case Instruction::SExt:
4617  case Instruction::FPToUI:
4618  case Instruction::FPToSI:
4619  case Instruction::FPExt:
4620  case Instruction::PtrToInt:
4621  case Instruction::IntToPtr:
4622  case Instruction::SIToFP:
4623  case Instruction::UIToFP:
4624  case Instruction::Trunc:
4625  case Instruction::FPTrunc:
4626  case Instruction::BitCast: {
4627    // We optimize the truncation of induction variable.
4628    // The cost of these is the same as the scalar operation.
4629    if (I->getOpcode() == Instruction::Trunc &&
4630        Legal->isInductionVariable(I->getOperand(0)))
4631      return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
4632                                  I->getOperand(0)->getType());
4633
4634    Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
4635    return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
4636  }
4637  case Instruction::Call: {
4638    CallInst *CI = cast<CallInst>(I);
4639    Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
4640    assert(ID && "Not an intrinsic call!");
4641    Type *RetTy = ToVectorTy(CI->getType(), VF);
4642    SmallVector<Type*, 4> Tys;
4643    for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
4644      Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
4645    return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
4646  }
4647  default: {
4648    // We are scalarizing the instruction. Return the cost of the scalar
4649    // instruction, plus the cost of insert and extract into vector
4650    // elements, times the vector width.
4651    unsigned Cost = 0;
4652
4653    if (!RetTy->isVoidTy() && VF != 1) {
4654      unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
4655                                                VectorTy);
4656      unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
4657                                                VectorTy);
4658
4659      // The cost of inserting the results plus extracting each one of the
4660      // operands.
4661      Cost += VF * (InsCost + ExtCost * I->getNumOperands());
4662    }
4663
4664    // The cost of executing VF copies of the scalar instruction. This opcode
4665    // is unknown. Assume that it is the same as 'mul'.
4666    Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
4667    return Cost;
4668  }
4669  }// end of switch.
4670}
4671
4672Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
4673  if (Scalar->isVoidTy() || VF == 1)
4674    return Scalar;
4675  return VectorType::get(Scalar, VF);
4676}
4677
4678char LoopVectorize::ID = 0;
4679static const char lv_name[] = "Loop Vectorization";
4680INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
4681INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
4682INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4683INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4684INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
4685
4686namespace llvm {
4687  Pass *createLoopVectorizePass() {
4688    return new LoopVectorize();
4689  }
4690}
4691
4692bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
4693  // Check for a store.
4694  if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
4695    return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
4696
4697  // Check for a load.
4698  if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
4699    return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
4700
4701  return false;
4702}
4703