LLVM API Documentation

LoopVectorize.cpp
Go to the documentation of this file.
00001 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
00011 // and generates target-independent LLVM-IR.
00012 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
00013 // of instructions in order to estimate the profitability of vectorization.
00014 //
00015 // The loop vectorizer combines consecutive loop iterations into a single
00016 // 'wide' iteration. After this transformation the index is incremented
00017 // by the SIMD vector width, and not by one.
00018 //
00019 // This pass has three parts:
00020 // 1. The main loop pass that drives the different parts.
00021 // 2. LoopVectorizationLegality - A unit that checks for the legality
00022 //    of the vectorization.
00023 // 3. InnerLoopVectorizer - A unit that performs the actual
00024 //    widening of instructions.
00025 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
00026 //    of vectorization. It decides on the optimal vector width, which
00027 //    can be one, if vectorization is not profitable.
00028 //
00029 //===----------------------------------------------------------------------===//
00030 //
00031 // The reduction-variable vectorization is based on the paper:
00032 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
00033 //
00034 // Variable uniformity checks are inspired by:
00035 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
00036 //
00037 // Other ideas/concepts are from:
00038 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
00039 //
00040 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
00041 //  Vectorizing Compilers.
00042 //
00043 //===----------------------------------------------------------------------===//
00044 
00045 #define LV_NAME "loop-vectorize"
00046 #define DEBUG_TYPE LV_NAME
00047 
00048 #include "llvm/Transforms/Vectorize.h"
00049 #include "llvm/ADT/DenseMap.h"
00050 #include "llvm/ADT/EquivalenceClasses.h"
00051 #include "llvm/ADT/Hashing.h"
00052 #include "llvm/ADT/MapVector.h"
00053 #include "llvm/ADT/SetVector.h"
00054 #include "llvm/ADT/SmallPtrSet.h"
00055 #include "llvm/ADT/SmallSet.h"
00056 #include "llvm/ADT/SmallVector.h"
00057 #include "llvm/ADT/StringExtras.h"
00058 #include "llvm/Analysis/AliasAnalysis.h"
00059 #include "llvm/Analysis/BlockFrequencyInfo.h"
00060 #include "llvm/Analysis/LoopInfo.h"
00061 #include "llvm/Analysis/LoopIterator.h"
00062 #include "llvm/Analysis/LoopPass.h"
00063 #include "llvm/Analysis/ScalarEvolution.h"
00064 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00065 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00066 #include "llvm/Analysis/TargetTransformInfo.h"
00067 #include "llvm/Analysis/ValueTracking.h"
00068 #include "llvm/IR/Constants.h"
00069 #include "llvm/IR/DataLayout.h"
00070 #include "llvm/IR/DebugInfo.h"
00071 #include "llvm/IR/DerivedTypes.h"
00072 #include "llvm/IR/Dominators.h"
00073 #include "llvm/IR/Function.h"
00074 #include "llvm/IR/IRBuilder.h"
00075 #include "llvm/IR/Instructions.h"
00076 #include "llvm/IR/IntrinsicInst.h"
00077 #include "llvm/IR/LLVMContext.h"
00078 #include "llvm/IR/Module.h"
00079 #include "llvm/IR/PatternMatch.h"
00080 #include "llvm/IR/Type.h"
00081 #include "llvm/IR/Value.h"
00082 #include "llvm/IR/ValueHandle.h"
00083 #include "llvm/IR/Verifier.h"
00084 #include "llvm/Pass.h"
00085 #include "llvm/Support/BranchProbability.h"
00086 #include "llvm/Support/CommandLine.h"
00087 #include "llvm/Support/Debug.h"
00088 #include "llvm/Support/Format.h"
00089 #include "llvm/Support/raw_ostream.h"
00090 #include "llvm/Target/TargetLibraryInfo.h"
00091 #include "llvm/Transforms/Scalar.h"
00092 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00093 #include "llvm/Transforms/Utils/Local.h"
00094 #include "llvm/Transforms/Utils/VectorUtils.h"
00095 #include <algorithm>
00096 #include <map>
00097 
00098 using namespace llvm;
00099 using namespace llvm::PatternMatch;
00100 
00101 static cl::opt<unsigned>
00102 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
00103                     cl::desc("Sets the SIMD width. Zero is autoselect."));
00104 
00105 static cl::opt<unsigned>
00106 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
00107                     cl::desc("Sets the vectorization unroll count. "
00108                              "Zero is autoselect."));
00109 
00110 static cl::opt<bool>
00111 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
00112                    cl::desc("Enable if-conversion during vectorization."));
00113 
00114 /// We don't vectorize loops with a known constant trip count below this number.
00115 static cl::opt<unsigned>
00116 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
00117                              cl::Hidden,
00118                              cl::desc("Don't vectorize loops with a constant "
00119                                       "trip count that is smaller than this "
00120                                       "value."));
00121 
00122 /// This enables versioning on the strides of symbolically striding memory
00123 /// accesses in code like the following.
00124 ///   for (i = 0; i < N; ++i)
00125 ///     A[i * Stride1] += B[i * Stride2] ...
00126 ///
00127 /// Will be roughly translated to
00128 ///    if (Stride1 == 1 && Stride2 == 1) {
00129 ///      for (i = 0; i < N; i+=4)
00130 ///       A[i:i+3] += ...
00131 ///    } else
00132 ///      ...
00133 static cl::opt<bool> EnableMemAccessVersioning(
00134     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
00135     cl::desc("Enable symblic stride memory access versioning"));
00136 
00137 /// We don't unroll loops with a known constant trip count below this number.
00138 static const unsigned TinyTripCountUnrollThreshold = 128;
00139 
00140 /// When performing memory disambiguation checks at runtime do not make more
00141 /// than this number of comparisons.
00142 static const unsigned RuntimeMemoryCheckThreshold = 8;
00143 
00144 /// Maximum simd width.
00145 static const unsigned MaxVectorWidth = 64;
00146 
00147 static cl::opt<unsigned> ForceTargetNumScalarRegs(
00148     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
00149     cl::desc("A flag that overrides the target's number of scalar registers."));
00150 
00151 static cl::opt<unsigned> ForceTargetNumVectorRegs(
00152     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
00153     cl::desc("A flag that overrides the target's number of vector registers."));
00154 
00155 /// Maximum vectorization unroll count.
00156 static const unsigned MaxUnrollFactor = 16;
00157 
00158 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
00159     "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
00160     cl::desc("A flag that overrides the target's max unroll factor for scalar "
00161              "loops."));
00162 
00163 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
00164     "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
00165     cl::desc("A flag that overrides the target's max unroll factor for "
00166              "vectorized loops."));
00167 
00168 static cl::opt<unsigned> ForceTargetInstructionCost(
00169     "force-target-instruction-cost", cl::init(0), cl::Hidden,
00170     cl::desc("A flag that overrides the target's expected cost for "
00171              "an instruction to a single constant value. Mostly "
00172              "useful for getting consistent testing."));
00173 
00174 static cl::opt<unsigned> SmallLoopCost(
00175     "small-loop-cost", cl::init(20), cl::Hidden,
00176     cl::desc("The cost of a loop that is considered 'small' by the unroller."));
00177 
00178 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
00179     "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
00180     cl::desc("Enable the use of the block frequency analysis to access PGO "
00181              "heuristics minimizing code growth in cold regions and being more "
00182              "aggressive in hot regions."));
00183 
00184 // Runtime unroll loops for load/store throughput.
00185 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
00186     "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
00187     cl::desc("Enable runtime unrolling until load/store ports are saturated"));
00188 
00189 /// The number of stores in a loop that are allowed to need predication.
00190 static cl::opt<unsigned> NumberOfStoresToPredicate(
00191     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
00192     cl::desc("Max number of stores to be predicated behind an if."));
00193 
00194 static cl::opt<bool> EnableIndVarRegisterHeur(
00195     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
00196     cl::desc("Count the induction variable only once when unrolling"));
00197 
00198 static cl::opt<bool> EnableCondStoresVectorization(
00199     "enable-cond-stores-vec", cl::init(false), cl::Hidden,
00200     cl::desc("Enable if predication of stores during vectorization."));
00201 
00202 namespace {
00203 
00204 // Forward declarations.
00205 class LoopVectorizationLegality;
00206 class LoopVectorizationCostModel;
00207 
00208 /// InnerLoopVectorizer vectorizes loops which contain only one basic
00209 /// block to a specified vectorization factor (VF).
00210 /// This class performs the widening of scalars into vectors, or multiple
00211 /// scalars. This class also implements the following features:
00212 /// * It inserts an epilogue loop for handling loops that don't have iteration
00213 ///   counts that are known to be a multiple of the vectorization factor.
00214 /// * It handles the code generation for reduction variables.
00215 /// * Scalarization (implementation using scalars) of un-vectorizable
00216 ///   instructions.
00217 /// InnerLoopVectorizer does not perform any vectorization-legality
00218 /// checks, and relies on the caller to check for the different legality
00219 /// aspects. The InnerLoopVectorizer relies on the
00220 /// LoopVectorizationLegality class to provide information about the induction
00221 /// and reduction variables that were found to a given vectorization factor.
00222 class InnerLoopVectorizer {
00223 public:
00224   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
00225                       DominatorTree *DT, const DataLayout *DL,
00226                       const TargetLibraryInfo *TLI, unsigned VecWidth,
00227                       unsigned UnrollFactor)
00228       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
00229         VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
00230         OldInduction(0), WidenMap(UnrollFactor), Legal(0) {}
00231 
00232   // Perform the actual loop widening (vectorization).
00233   void vectorize(LoopVectorizationLegality *L) {
00234     Legal = L;
00235     // Create a new empty loop. Unlink the old loop and connect the new one.
00236     createEmptyLoop();
00237     // Widen each instruction in the old loop to a new one in the new loop.
00238     // Use the Legality module to find the induction and reduction variables.
00239     vectorizeLoop();
00240     // Register the new loop and update the analysis passes.
00241     updateAnalysis();
00242   }
00243 
00244   virtual ~InnerLoopVectorizer() {}
00245 
00246 protected:
00247   /// A small list of PHINodes.
00248   typedef SmallVector<PHINode*, 4> PhiVector;
00249   /// When we unroll loops we have multiple vector values for each scalar.
00250   /// This data structure holds the unrolled and vectorized values that
00251   /// originated from one scalar instruction.
00252   typedef SmallVector<Value*, 2> VectorParts;
00253 
00254   // When we if-convert we need create edge masks. We have to cache values so
00255   // that we don't end up with exponential recursion/IR.
00256   typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
00257                    VectorParts> EdgeMaskCache;
00258 
00259   /// \brief Add code that checks at runtime if the accessed arrays overlap.
00260   ///
00261   /// Returns a pair of instructions where the first element is the first
00262   /// instruction generated in possibly a sequence of instructions and the
00263   /// second value is the final comparator value or NULL if no check is needed.
00264   std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
00265 
00266   /// \brief Add checks for strides that where assumed to be 1.
00267   ///
00268   /// Returns the last check instruction and the first check instruction in the
00269   /// pair as (first, last).
00270   std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
00271 
00272   /// Create an empty loop, based on the loop ranges of the old loop.
00273   void createEmptyLoop();
00274   /// Copy and widen the instructions from the old loop.
00275   virtual void vectorizeLoop();
00276 
00277   /// \brief The Loop exit block may have single value PHI nodes where the
00278   /// incoming value is 'Undef'. While vectorizing we only handled real values
00279   /// that were defined inside the loop. Here we fix the 'undef case'.
00280   /// See PR14725.
00281   void fixLCSSAPHIs();
00282 
00283   /// A helper function that computes the predicate of the block BB, assuming
00284   /// that the header block of the loop is set to True. It returns the *entry*
00285   /// mask for the block BB.
00286   VectorParts createBlockInMask(BasicBlock *BB);
00287   /// A helper function that computes the predicate of the edge between SRC
00288   /// and DST.
00289   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
00290 
00291   /// A helper function to vectorize a single BB within the innermost loop.
00292   void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
00293 
00294   /// Vectorize a single PHINode in a block. This method handles the induction
00295   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
00296   /// arbitrary length vectors.
00297   void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
00298                            unsigned UF, unsigned VF, PhiVector *PV);
00299 
00300   /// Insert the new loop to the loop hierarchy and pass manager
00301   /// and update the analysis passes.
00302   void updateAnalysis();
00303 
00304   /// This instruction is un-vectorizable. Implement it as a sequence
00305   /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
00306   /// scalarized instruction behind an if block predicated on the control
00307   /// dependence of the instruction.
00308   virtual void scalarizeInstruction(Instruction *Instr,
00309                                     bool IfPredicateStore=false);
00310 
00311   /// Vectorize Load and Store instructions,
00312   virtual void vectorizeMemoryInstruction(Instruction *Instr);
00313 
00314   /// Create a broadcast instruction. This method generates a broadcast
00315   /// instruction (shuffle) for loop invariant values and for the induction
00316   /// value. If this is the induction variable then we extend it to N, N+1, ...
00317   /// this is needed because each iteration in the loop corresponds to a SIMD
00318   /// element.
00319   virtual Value *getBroadcastInstrs(Value *V);
00320 
00321   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
00322   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
00323   /// The sequence starts at StartIndex.
00324   virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
00325 
00326   /// When we go over instructions in the basic block we rely on previous
00327   /// values within the current basic block or on loop invariant values.
00328   /// When we widen (vectorize) values we place them in the map. If the values
00329   /// are not within the map, they have to be loop invariant, so we simply
00330   /// broadcast them into a vector.
00331   VectorParts &getVectorValue(Value *V);
00332 
00333   /// Generate a shuffle sequence that will reverse the vector Vec.
00334   virtual Value *reverseVector(Value *Vec);
00335 
00336   /// This is a helper class that holds the vectorizer state. It maps scalar
00337   /// instructions to vector instructions. When the code is 'unrolled' then
00338   /// then a single scalar value is mapped to multiple vector parts. The parts
00339   /// are stored in the VectorPart type.
00340   struct ValueMap {
00341     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
00342     /// are mapped.
00343     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
00344 
00345     /// \return True if 'Key' is saved in the Value Map.
00346     bool has(Value *Key) const { return MapStorage.count(Key); }
00347 
00348     /// Initializes a new entry in the map. Sets all of the vector parts to the
00349     /// save value in 'Val'.
00350     /// \return A reference to a vector with splat values.
00351     VectorParts &splat(Value *Key, Value *Val) {
00352       VectorParts &Entry = MapStorage[Key];
00353       Entry.assign(UF, Val);
00354       return Entry;
00355     }
00356 
00357     ///\return A reference to the value that is stored at 'Key'.
00358     VectorParts &get(Value *Key) {
00359       VectorParts &Entry = MapStorage[Key];
00360       if (Entry.empty())
00361         Entry.resize(UF);
00362       assert(Entry.size() == UF);
00363       return Entry;
00364     }
00365 
00366   private:
00367     /// The unroll factor. Each entry in the map stores this number of vector
00368     /// elements.
00369     unsigned UF;
00370 
00371     /// Map storage. We use std::map and not DenseMap because insertions to a
00372     /// dense map invalidates its iterators.
00373     std::map<Value *, VectorParts> MapStorage;
00374   };
00375 
00376   /// The original loop.
00377   Loop *OrigLoop;
00378   /// Scev analysis to use.
00379   ScalarEvolution *SE;
00380   /// Loop Info.
00381   LoopInfo *LI;
00382   /// Dominator Tree.
00383   DominatorTree *DT;
00384   /// Data Layout.
00385   const DataLayout *DL;
00386   /// Target Library Info.
00387   const TargetLibraryInfo *TLI;
00388 
00389   /// The vectorization SIMD factor to use. Each vector will have this many
00390   /// vector elements.
00391   unsigned VF;
00392 
00393 protected:
00394   /// The vectorization unroll factor to use. Each scalar is vectorized to this
00395   /// many different vector instructions.
00396   unsigned UF;
00397 
00398   /// The builder that we use
00399   IRBuilder<> Builder;
00400 
00401   // --- Vectorization state ---
00402 
00403   /// The vector-loop preheader.
00404   BasicBlock *LoopVectorPreHeader;
00405   /// The scalar-loop preheader.
00406   BasicBlock *LoopScalarPreHeader;
00407   /// Middle Block between the vector and the scalar.
00408   BasicBlock *LoopMiddleBlock;
00409   ///The ExitBlock of the scalar loop.
00410   BasicBlock *LoopExitBlock;
00411   ///The vector loop body.
00412   SmallVector<BasicBlock *, 4> LoopVectorBody;
00413   ///The scalar loop body.
00414   BasicBlock *LoopScalarBody;
00415   /// A list of all bypass blocks. The first block is the entry of the loop.
00416   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
00417 
00418   /// The new Induction variable which was added to the new block.
00419   PHINode *Induction;
00420   /// The induction variable of the old basic block.
00421   PHINode *OldInduction;
00422   /// Holds the extended (to the widest induction type) start index.
00423   Value *ExtendedIdx;
00424   /// Maps scalars to widened vectors.
00425   ValueMap WidenMap;
00426   EdgeMaskCache MaskCache;
00427 
00428   LoopVectorizationLegality *Legal;
00429 };
00430 
00431 class InnerLoopUnroller : public InnerLoopVectorizer {
00432 public:
00433   InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
00434                     DominatorTree *DT, const DataLayout *DL,
00435                     const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
00436     InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
00437 
00438 private:
00439   void scalarizeInstruction(Instruction *Instr,
00440                             bool IfPredicateStore = false) override;
00441   void vectorizeMemoryInstruction(Instruction *Instr) override;
00442   Value *getBroadcastInstrs(Value *V) override;
00443   Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
00444   Value *reverseVector(Value *Vec) override;
00445 };
00446 
00447 /// \brief Look for a meaningful debug location on the instruction or it's
00448 /// operands.
00449 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
00450   if (!I)
00451     return I;
00452 
00453   DebugLoc Empty;
00454   if (I->getDebugLoc() != Empty)
00455     return I;
00456 
00457   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
00458     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
00459       if (OpInst->getDebugLoc() != Empty)
00460         return OpInst;
00461   }
00462 
00463   return I;
00464 }
00465 
00466 /// \brief Set the debug location in the builder using the debug location in the
00467 /// instruction.
00468 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
00469   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
00470     B.SetCurrentDebugLocation(Inst->getDebugLoc());
00471   else
00472     B.SetCurrentDebugLocation(DebugLoc());
00473 }
00474 
00475 #ifndef NDEBUG
00476 /// \return string containing a file name and a line # for the given
00477 /// instruction.
00478 static format_object3<const char *, const char *, unsigned>
00479 getDebugLocString(const Instruction *I) {
00480   if (!I)
00481     return format<const char *, const char *, unsigned>("", "", "", 0U);
00482   MDNode *N = I->getMetadata("dbg");
00483   if (!N) {
00484     const StringRef ModuleName =
00485         I->getParent()->getParent()->getParent()->getModuleIdentifier();
00486     return format<const char *, const char *, unsigned>("%s", ModuleName.data(),
00487                                                         "", 0U);
00488   }
00489   const DILocation Loc(N);
00490   const unsigned LineNo = Loc.getLineNumber();
00491   const char *DirName = Loc.getDirectory().data();
00492   const char *FileName = Loc.getFilename().data();
00493   return format("%s/%s:%u", DirName, FileName, LineNo);
00494 }
00495 #endif
00496 
00497 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
00498 /// to what vectorization factor.
00499 /// This class does not look at the profitability of vectorization, only the
00500 /// legality. This class has two main kinds of checks:
00501 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
00502 ///   will change the order of memory accesses in a way that will change the
00503 ///   correctness of the program.
00504 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
00505 /// checks for a number of different conditions, such as the availability of a
00506 /// single induction variable, that all types are supported and vectorize-able,
00507 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
00508 /// This class is also used by InnerLoopVectorizer for identifying
00509 /// induction variable and the different reduction variables.
00510 class LoopVectorizationLegality {
00511 public:
00512   unsigned NumLoads;
00513   unsigned NumStores;
00514   unsigned NumPredStores;
00515 
00516   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
00517                             DominatorTree *DT, TargetLibraryInfo *TLI)
00518       : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
00519         DT(DT), TLI(TLI), Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
00520         MaxSafeDepDistBytes(-1U) {}
00521 
00522   /// This enum represents the kinds of reductions that we support.
00523   enum ReductionKind {
00524     RK_NoReduction, ///< Not a reduction.
00525     RK_IntegerAdd,  ///< Sum of integers.
00526     RK_IntegerMult, ///< Product of integers.
00527     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
00528     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
00529     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
00530     RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
00531     RK_FloatAdd,    ///< Sum of floats.
00532     RK_FloatMult,   ///< Product of floats.
00533     RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
00534   };
00535 
00536   /// This enum represents the kinds of inductions that we support.
00537   enum InductionKind {
00538     IK_NoInduction,         ///< Not an induction variable.
00539     IK_IntInduction,        ///< Integer induction variable. Step = 1.
00540     IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
00541     IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
00542     IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
00543   };
00544 
00545   // This enum represents the kind of minmax reduction.
00546   enum MinMaxReductionKind {
00547     MRK_Invalid,
00548     MRK_UIntMin,
00549     MRK_UIntMax,
00550     MRK_SIntMin,
00551     MRK_SIntMax,
00552     MRK_FloatMin,
00553     MRK_FloatMax
00554   };
00555 
00556   /// This struct holds information about reduction variables.
00557   struct ReductionDescriptor {
00558     ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
00559       Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
00560 
00561     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
00562                         MinMaxReductionKind MK)
00563         : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
00564 
00565     // The starting value of the reduction.
00566     // It does not have to be zero!
00567     TrackingVH<Value> StartValue;
00568     // The instruction who's value is used outside the loop.
00569     Instruction *LoopExitInstr;
00570     // The kind of the reduction.
00571     ReductionKind Kind;
00572     // If this a min/max reduction the kind of reduction.
00573     MinMaxReductionKind MinMaxKind;
00574   };
00575 
00576   /// This POD struct holds information about a potential reduction operation.
00577   struct ReductionInstDesc {
00578     ReductionInstDesc(bool IsRedux, Instruction *I) :
00579       IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
00580 
00581     ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
00582       IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
00583 
00584     // Is this instruction a reduction candidate.
00585     bool IsReduction;
00586     // The last instruction in a min/max pattern (select of the select(icmp())
00587     // pattern), or the current reduction instruction otherwise.
00588     Instruction *PatternLastInst;
00589     // If this is a min/max pattern the comparison predicate.
00590     MinMaxReductionKind MinMaxKind;
00591   };
00592 
00593   /// This struct holds information about the memory runtime legality
00594   /// check that a group of pointers do not overlap.
00595   struct RuntimePointerCheck {
00596     RuntimePointerCheck() : Need(false) {}
00597 
00598     /// Reset the state of the pointer runtime information.
00599     void reset() {
00600       Need = false;
00601       Pointers.clear();
00602       Starts.clear();
00603       Ends.clear();
00604       IsWritePtr.clear();
00605       DependencySetId.clear();
00606     }
00607 
00608     /// Insert a pointer and calculate the start and end SCEVs.
00609     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
00610                 unsigned DepSetId, ValueToValueMap &Strides);
00611 
00612     /// This flag indicates if we need to add the runtime check.
00613     bool Need;
00614     /// Holds the pointers that we need to check.
00615     SmallVector<TrackingVH<Value>, 2> Pointers;
00616     /// Holds the pointer value at the beginning of the loop.
00617     SmallVector<const SCEV*, 2> Starts;
00618     /// Holds the pointer value at the end of the loop.
00619     SmallVector<const SCEV*, 2> Ends;
00620     /// Holds the information if this pointer is used for writing to memory.
00621     SmallVector<bool, 2> IsWritePtr;
00622     /// Holds the id of the set of pointers that could be dependent because of a
00623     /// shared underlying object.
00624     SmallVector<unsigned, 2> DependencySetId;
00625   };
00626 
00627   /// A struct for saving information about induction variables.
00628   struct InductionInfo {
00629     InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
00630     InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
00631     /// Start value.
00632     TrackingVH<Value> StartValue;
00633     /// Induction kind.
00634     InductionKind IK;
00635   };
00636 
00637   /// ReductionList contains the reduction descriptors for all
00638   /// of the reductions that were found in the loop.
00639   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
00640 
00641   /// InductionList saves induction variables and maps them to the
00642   /// induction descriptor.
00643   typedef MapVector<PHINode*, InductionInfo> InductionList;
00644 
00645   /// Returns true if it is legal to vectorize this loop.
00646   /// This does not mean that it is profitable to vectorize this
00647   /// loop, only that it is legal to do so.
00648   bool canVectorize();
00649 
00650   /// Returns the Induction variable.
00651   PHINode *getInduction() { return Induction; }
00652 
00653   /// Returns the reduction variables found in the loop.
00654   ReductionList *getReductionVars() { return &Reductions; }
00655 
00656   /// Returns the induction variables found in the loop.
00657   InductionList *getInductionVars() { return &Inductions; }
00658 
00659   /// Returns the widest induction type.
00660   Type *getWidestInductionType() { return WidestIndTy; }
00661 
00662   /// Returns True if V is an induction variable in this loop.
00663   bool isInductionVariable(const Value *V);
00664 
00665   /// Return true if the block BB needs to be predicated in order for the loop
00666   /// to be vectorized.
00667   bool blockNeedsPredication(BasicBlock *BB);
00668 
00669   /// Check if this  pointer is consecutive when vectorizing. This happens
00670   /// when the last index of the GEP is the induction variable, or that the
00671   /// pointer itself is an induction variable.
00672   /// This check allows us to vectorize A[idx] into a wide load/store.
00673   /// Returns:
00674   /// 0 - Stride is unknown or non-consecutive.
00675   /// 1 - Address is consecutive.
00676   /// -1 - Address is consecutive, and decreasing.
00677   int isConsecutivePtr(Value *Ptr);
00678 
00679   /// Returns true if the value V is uniform within the loop.
00680   bool isUniform(Value *V);
00681 
00682   /// Returns true if this instruction will remain scalar after vectorization.
00683   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
00684 
00685   /// Returns the information that we collected about runtime memory check.
00686   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
00687 
00688   /// This function returns the identity element (or neutral element) for
00689   /// the operation K.
00690   static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
00691 
00692   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
00693 
00694   bool hasStride(Value *V) { return StrideSet.count(V); }
00695   bool mustCheckStrides() { return !StrideSet.empty(); }
00696   SmallPtrSet<Value *, 8>::iterator strides_begin() {
00697     return StrideSet.begin();
00698   }
00699   SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
00700 
00701 private:
00702   /// Check if a single basic block loop is vectorizable.
00703   /// At this point we know that this is a loop with a constant trip count
00704   /// and we only need to check individual instructions.
00705   bool canVectorizeInstrs();
00706 
00707   /// When we vectorize loops we may change the order in which
00708   /// we read and write from memory. This method checks if it is
00709   /// legal to vectorize the code, considering only memory constrains.
00710   /// Returns true if the loop is vectorizable
00711   bool canVectorizeMemory();
00712 
00713   /// Return true if we can vectorize this loop using the IF-conversion
00714   /// transformation.
00715   bool canVectorizeWithIfConvert();
00716 
00717   /// Collect the variables that need to stay uniform after vectorization.
00718   void collectLoopUniforms();
00719 
00720   /// Return true if all of the instructions in the block can be speculatively
00721   /// executed. \p SafePtrs is a list of addresses that are known to be legal
00722   /// and we know that we can read from them without segfault.
00723   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
00724 
00725   /// Returns True, if 'Phi' is the kind of reduction variable for type
00726   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
00727   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
00728   /// Returns a struct describing if the instruction 'I' can be a reduction
00729   /// variable of type 'Kind'. If the reduction is a min/max pattern of
00730   /// select(icmp()) this function advances the instruction pointer 'I' from the
00731   /// compare instruction to the select instruction and stores this pointer in
00732   /// 'PatternLastInst' member of the returned struct.
00733   ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
00734                                      ReductionInstDesc &Desc);
00735   /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
00736   /// pattern corresponding to a min(X, Y) or max(X, Y).
00737   static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
00738                                                     ReductionInstDesc &Prev);
00739   /// Returns the induction kind of Phi. This function may return NoInduction
00740   /// if the PHI is not an induction variable.
00741   InductionKind isInductionVariable(PHINode *Phi);
00742 
00743   /// \brief Collect memory access with loop invariant strides.
00744   ///
00745   /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
00746   /// invariant.
00747   void collectStridedAcccess(Value *LoadOrStoreInst);
00748 
00749   /// The loop that we evaluate.
00750   Loop *TheLoop;
00751   /// Scev analysis.
00752   ScalarEvolution *SE;
00753   /// DataLayout analysis.
00754   const DataLayout *DL;
00755   /// Dominators.
00756   DominatorTree *DT;
00757   /// Target Library Info.
00758   TargetLibraryInfo *TLI;
00759 
00760   //  ---  vectorization state --- //
00761 
00762   /// Holds the integer induction variable. This is the counter of the
00763   /// loop.
00764   PHINode *Induction;
00765   /// Holds the reduction variables.
00766   ReductionList Reductions;
00767   /// Holds all of the induction variables that we found in the loop.
00768   /// Notice that inductions don't need to start at zero and that induction
00769   /// variables can be pointers.
00770   InductionList Inductions;
00771   /// Holds the widest induction type encountered.
00772   Type *WidestIndTy;
00773 
00774   /// Allowed outside users. This holds the reduction
00775   /// vars which can be accessed from outside the loop.
00776   SmallPtrSet<Value*, 4> AllowedExit;
00777   /// This set holds the variables which are known to be uniform after
00778   /// vectorization.
00779   SmallPtrSet<Instruction*, 4> Uniforms;
00780   /// We need to check that all of the pointers in this list are disjoint
00781   /// at runtime.
00782   RuntimePointerCheck PtrRtCheck;
00783   /// Can we assume the absence of NaNs.
00784   bool HasFunNoNaNAttr;
00785 
00786   unsigned MaxSafeDepDistBytes;
00787 
00788   ValueToValueMap Strides;
00789   SmallPtrSet<Value *, 8> StrideSet;
00790 };
00791 
00792 /// LoopVectorizationCostModel - estimates the expected speedups due to
00793 /// vectorization.
00794 /// In many cases vectorization is not profitable. This can happen because of
00795 /// a number of reasons. In this class we mainly attempt to predict the
00796 /// expected speedup/slowdowns due to the supported instruction set. We use the
00797 /// TargetTransformInfo to query the different backends for the cost of
00798 /// different operations.
00799 class LoopVectorizationCostModel {
00800 public:
00801   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
00802                              LoopVectorizationLegality *Legal,
00803                              const TargetTransformInfo &TTI,
00804                              const DataLayout *DL, const TargetLibraryInfo *TLI)
00805       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
00806 
00807   /// Information about vectorization costs
00808   struct VectorizationFactor {
00809     unsigned Width; // Vector width with best cost
00810     unsigned Cost; // Cost of the loop with that width
00811   };
00812   /// \return The most profitable vectorization factor and the cost of that VF.
00813   /// This method checks every power of two up to VF. If UserVF is not ZERO
00814   /// then this vectorization factor will be selected if vectorization is
00815   /// possible.
00816   VectorizationFactor selectVectorizationFactor(bool OptForSize,
00817                                                 unsigned UserVF);
00818 
00819   /// \return The size (in bits) of the widest type in the code that
00820   /// needs to be vectorized. We ignore values that remain scalar such as
00821   /// 64 bit loop indices.
00822   unsigned getWidestType();
00823 
00824   /// \return The most profitable unroll factor.
00825   /// If UserUF is non-zero then this method finds the best unroll-factor
00826   /// based on register pressure and other parameters.
00827   /// VF and LoopCost are the selected vectorization factor and the cost of the
00828   /// selected VF.
00829   unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
00830                               unsigned LoopCost);
00831 
00832   /// \brief A struct that represents some properties of the register usage
00833   /// of a loop.
00834   struct RegisterUsage {
00835     /// Holds the number of loop invariant values that are used in the loop.
00836     unsigned LoopInvariantRegs;
00837     /// Holds the maximum number of concurrent live intervals in the loop.
00838     unsigned MaxLocalUsers;
00839     /// Holds the number of instructions in the loop.
00840     unsigned NumInstructions;
00841   };
00842 
00843   /// \return  information about the register usage of the loop.
00844   RegisterUsage calculateRegisterUsage();
00845 
00846 private:
00847   /// Returns the expected execution cost. The unit of the cost does
00848   /// not matter because we use the 'cost' units to compare different
00849   /// vector widths. The cost that is returned is *not* normalized by
00850   /// the factor width.
00851   unsigned expectedCost(unsigned VF);
00852 
00853   /// Returns the execution time cost of an instruction for a given vector
00854   /// width. Vector width of one means scalar.
00855   unsigned getInstructionCost(Instruction *I, unsigned VF);
00856 
00857   /// A helper function for converting Scalar types to vector types.
00858   /// If the incoming type is void, we return void. If the VF is 1, we return
00859   /// the scalar type.
00860   static Type* ToVectorTy(Type *Scalar, unsigned VF);
00861 
00862   /// Returns whether the instruction is a load or store and will be a emitted
00863   /// as a vector operation.
00864   bool isConsecutiveLoadOrStore(Instruction *I);
00865 
00866   /// The loop that we evaluate.
00867   Loop *TheLoop;
00868   /// Scev analysis.
00869   ScalarEvolution *SE;
00870   /// Loop Info analysis.
00871   LoopInfo *LI;
00872   /// Vectorization legality.
00873   LoopVectorizationLegality *Legal;
00874   /// Vector target information.
00875   const TargetTransformInfo &TTI;
00876   /// Target data layout information.
00877   const DataLayout *DL;
00878   /// Target Library Info.
00879   const TargetLibraryInfo *TLI;
00880 };
00881 
00882 /// Utility class for getting and setting loop vectorizer hints in the form
00883 /// of loop metadata.
00884 struct LoopVectorizeHints {
00885   /// Vectorization width.
00886   unsigned Width;
00887   /// Vectorization unroll factor.
00888   unsigned Unroll;
00889   /// Vectorization forced (-1 not selected, 0 force disabled, 1 force enabled)
00890   int Force;
00891 
00892   LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
00893   : Width(VectorizationFactor)
00894   , Unroll(DisableUnrolling ? 1 : VectorizationUnroll)
00895   , Force(-1)
00896   , LoopID(L->getLoopID()) {
00897     getHints(L);
00898     // The command line options override any loop metadata except for when
00899     // width == 1 which is used to indicate the loop is already vectorized.
00900     if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
00901       Width = VectorizationFactor;
00902     if (VectorizationUnroll.getNumOccurrences() > 0)
00903       Unroll = VectorizationUnroll;
00904 
00905     DEBUG(if (DisableUnrolling && Unroll == 1)
00906             dbgs() << "LV: Unrolling disabled by the pass manager\n");
00907   }
00908 
00909   /// Return the loop vectorizer metadata prefix.
00910   static StringRef Prefix() { return "llvm.vectorizer."; }
00911 
00912   MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
00913     SmallVector<Value*, 2> Vals;
00914     Vals.push_back(MDString::get(Context, Name));
00915     Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
00916     return MDNode::get(Context, Vals);
00917   }
00918 
00919   /// Mark the loop L as already vectorized by setting the width to 1.
00920   void setAlreadyVectorized(Loop *L) {
00921     LLVMContext &Context = L->getHeader()->getContext();
00922 
00923     Width = 1;
00924 
00925     // Create a new loop id with one more operand for the already_vectorized
00926     // hint. If the loop already has a loop id then copy the existing operands.
00927     SmallVector<Value*, 4> Vals(1);
00928     if (LoopID)
00929       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
00930         Vals.push_back(LoopID->getOperand(i));
00931 
00932     Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
00933     Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
00934 
00935     MDNode *NewLoopID = MDNode::get(Context, Vals);
00936     // Set operand 0 to refer to the loop id itself.
00937     NewLoopID->replaceOperandWith(0, NewLoopID);
00938 
00939     L->setLoopID(NewLoopID);
00940     if (LoopID)
00941       LoopID->replaceAllUsesWith(NewLoopID);
00942 
00943     LoopID = NewLoopID;
00944   }
00945 
00946 private:
00947   MDNode *LoopID;
00948 
00949   /// Find hints specified in the loop metadata.
00950   void getHints(const Loop *L) {
00951     if (!LoopID)
00952       return;
00953 
00954     // First operand should refer to the loop id itself.
00955     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
00956     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
00957 
00958     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
00959       const MDString *S = 0;
00960       SmallVector<Value*, 4> Args;
00961 
00962       // The expected hint is either a MDString or a MDNode with the first
00963       // operand a MDString.
00964       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
00965         if (!MD || MD->getNumOperands() == 0)
00966           continue;
00967         S = dyn_cast<MDString>(MD->getOperand(0));
00968         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
00969           Args.push_back(MD->getOperand(i));
00970       } else {
00971         S = dyn_cast<MDString>(LoopID->getOperand(i));
00972         assert(Args.size() == 0 && "too many arguments for MDString");
00973       }
00974 
00975       if (!S)
00976         continue;
00977 
00978       // Check if the hint starts with the vectorizer prefix.
00979       StringRef Hint = S->getString();
00980       if (!Hint.startswith(Prefix()))
00981         continue;
00982       // Remove the prefix.
00983       Hint = Hint.substr(Prefix().size(), StringRef::npos);
00984 
00985       if (Args.size() == 1)
00986         getHint(Hint, Args[0]);
00987     }
00988   }
00989 
00990   // Check string hint with one operand.
00991   void getHint(StringRef Hint, Value *Arg) {
00992     const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
00993     if (!C) return;
00994     unsigned Val = C->getZExtValue();
00995 
00996     if (Hint == "width") {
00997       if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
00998         Width = Val;
00999       else
01000         DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
01001     } else if (Hint == "unroll") {
01002       if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
01003         Unroll = Val;
01004       else
01005         DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
01006     } else if (Hint == "enable") {
01007       if (C->getBitWidth() == 1)
01008         Force = Val;
01009       else
01010         DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
01011     } else {
01012       DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
01013     }
01014   }
01015 };
01016 
01017 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
01018   if (L.empty())
01019     return V.push_back(&L);
01020 
01021   for (Loop *InnerL : L)
01022     addInnerLoop(*InnerL, V);
01023 }
01024 
01025 /// The LoopVectorize Pass.
01026 struct LoopVectorize : public FunctionPass {
01027   /// Pass identification, replacement for typeid
01028   static char ID;
01029 
01030   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
01031     : FunctionPass(ID),
01032       DisableUnrolling(NoUnrolling),
01033       AlwaysVectorize(AlwaysVectorize) {
01034     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
01035   }
01036 
01037   ScalarEvolution *SE;
01038   const DataLayout *DL;
01039   LoopInfo *LI;
01040   TargetTransformInfo *TTI;
01041   DominatorTree *DT;
01042   BlockFrequencyInfo *BFI;
01043   TargetLibraryInfo *TLI;
01044   bool DisableUnrolling;
01045   bool AlwaysVectorize;
01046 
01047   BlockFrequency ColdEntryFreq;
01048 
01049   bool runOnFunction(Function &F) override {
01050     SE = &getAnalysis<ScalarEvolution>();
01051     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01052     DL = DLP ? &DLP->getDataLayout() : 0;
01053     LI = &getAnalysis<LoopInfo>();
01054     TTI = &getAnalysis<TargetTransformInfo>();
01055     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01056     BFI = &getAnalysis<BlockFrequencyInfo>();
01057     TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
01058 
01059     // Compute some weights outside of the loop over the loops. Compute this
01060     // using a BranchProbability to re-use its scaling math.
01061     const BranchProbability ColdProb(1, 5); // 20%
01062     ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
01063 
01064     // If the target claims to have no vector registers don't attempt
01065     // vectorization.
01066     if (!TTI->getNumberOfRegisters(true))
01067       return false;
01068 
01069     if (DL == NULL) {
01070       DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
01071                    << ": Missing data layout\n");
01072       return false;
01073     }
01074 
01075     // Build up a worklist of inner-loops to vectorize. This is necessary as
01076     // the act of vectorizing or partially unrolling a loop creates new loops
01077     // and can invalidate iterators across the loops.
01078     SmallVector<Loop *, 8> Worklist;
01079 
01080     for (Loop *L : *LI)
01081       addInnerLoop(*L, Worklist);
01082 
01083     // Now walk the identified inner loops.
01084     bool Changed = false;
01085     while (!Worklist.empty())
01086       Changed |= processLoop(Worklist.pop_back_val());
01087 
01088     // Process each loop nest in the function.
01089     return Changed;
01090   }
01091 
01092   bool processLoop(Loop *L) {
01093     assert(L->empty() && "Only process inner loops.");
01094     DEBUG(dbgs() << "\nLV: Checking a loop in \""
01095                  << L->getHeader()->getParent()->getName() << "\" from "
01096                  << getDebugLocString(L->getHeader()->getFirstNonPHIOrDbg())
01097                  << "\n");
01098 
01099     LoopVectorizeHints Hints(L, DisableUnrolling);
01100 
01101     DEBUG(dbgs() << "LV: Loop hints:"
01102                  << " force=" << (Hints.Force == 0
01103                                       ? "disabled"
01104                                       : (Hints.Force == 1 ? "enabled" : "?"))
01105                  << " width=" << Hints.Width << " unroll=" << Hints.Unroll
01106                  << "\n");
01107 
01108     if (Hints.Force == 0) {
01109       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
01110       return false;
01111     }
01112 
01113     if (!AlwaysVectorize && Hints.Force != 1) {
01114       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
01115       return false;
01116     }
01117 
01118     if (Hints.Width == 1 && Hints.Unroll == 1) {
01119       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
01120       return false;
01121     }
01122 
01123     // Check if it is legal to vectorize the loop.
01124     LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
01125     if (!LVL.canVectorize()) {
01126       DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
01127       return false;
01128     }
01129 
01130     // Use the cost model.
01131     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
01132 
01133     // Check the function attributes to find out if this function should be
01134     // optimized for size.
01135     Function *F = L->getHeader()->getParent();
01136     bool OptForSize =
01137         Hints.Force != 1 && F->hasFnAttribute(Attribute::OptimizeForSize);
01138 
01139     // Compute the weighted frequency of this loop being executed and see if it
01140     // is less than 20% of the function entry baseline frequency. Note that we
01141     // always have a canonical loop here because we think we *can* vectoriez.
01142     // FIXME: This is hidden behind a flag due to pervasive problems with
01143     // exactly what block frequency models.
01144     if (LoopVectorizeWithBlockFrequency) {
01145       BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
01146       if (Hints.Force != 1 && LoopEntryFreq < ColdEntryFreq)
01147         OptForSize = true;
01148     }
01149 
01150     // Check the function attributes to see if implicit floats are allowed.a
01151     // FIXME: This check doesn't seem possibly correct -- what if the loop is
01152     // an integer loop and the vector instructions selected are purely integer
01153     // vector instructions?
01154     if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
01155       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
01156             "attribute is used.\n");
01157       return false;
01158     }
01159 
01160     // Select the optimal vectorization factor.
01161     const LoopVectorizationCostModel::VectorizationFactor VF =
01162                           CM.selectVectorizationFactor(OptForSize, Hints.Width);
01163     // Select the unroll factor.
01164     const unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
01165                                         VF.Cost);
01166 
01167     DEBUG(dbgs() << "LV: Found a vectorizable loop ("
01168                  << VF.Width << ") in "
01169                  << getDebugLocString(L->getHeader()->getFirstNonPHIOrDbg())
01170                  << '\n');
01171     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
01172 
01173     if (VF.Width == 1) {
01174       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
01175       if (UF == 1)
01176         return false;
01177       DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
01178       // We decided not to vectorize, but we may want to unroll.
01179       InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
01180       Unroller.vectorize(&LVL);
01181     } else {
01182       // If we decided that it is *legal* to vectorize the loop then do it.
01183       InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
01184       LB.vectorize(&LVL);
01185     }
01186 
01187     // Mark the loop as already vectorized to avoid vectorizing again.
01188     Hints.setAlreadyVectorized(L);
01189 
01190     DEBUG(verifyFunction(*L->getHeader()->getParent()));
01191     return true;
01192   }
01193 
01194   void getAnalysisUsage(AnalysisUsage &AU) const override {
01195     AU.addRequiredID(LoopSimplifyID);
01196     AU.addRequiredID(LCSSAID);
01197     AU.addRequired<BlockFrequencyInfo>();
01198     AU.addRequired<DominatorTreeWrapperPass>();
01199     AU.addRequired<LoopInfo>();
01200     AU.addRequired<ScalarEvolution>();
01201     AU.addRequired<TargetTransformInfo>();
01202     AU.addPreserved<LoopInfo>();
01203     AU.addPreserved<DominatorTreeWrapperPass>();
01204   }
01205 
01206 };
01207 
01208 } // end anonymous namespace
01209 
01210 //===----------------------------------------------------------------------===//
01211 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
01212 // LoopVectorizationCostModel.
01213 //===----------------------------------------------------------------------===//
01214 
01215 static Value *stripIntegerCast(Value *V) {
01216   if (CastInst *CI = dyn_cast<CastInst>(V))
01217     if (CI->getOperand(0)->getType()->isIntegerTy())
01218       return CI->getOperand(0);
01219   return V;
01220 }
01221 
01222 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
01223 ///
01224 /// If \p OrigPtr is not null, use it to look up the stride value instead of
01225 /// \p Ptr.
01226 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
01227                                              ValueToValueMap &PtrToStride,
01228                                              Value *Ptr, Value *OrigPtr = 0) {
01229 
01230   const SCEV *OrigSCEV = SE->getSCEV(Ptr);
01231 
01232   // If there is an entry in the map return the SCEV of the pointer with the
01233   // symbolic stride replaced by one.
01234   ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
01235   if (SI != PtrToStride.end()) {
01236     Value *StrideVal = SI->second;
01237 
01238     // Strip casts.
01239     StrideVal = stripIntegerCast(StrideVal);
01240 
01241     // Replace symbolic stride by one.
01242     Value *One = ConstantInt::get(StrideVal->getType(), 1);
01243     ValueToValueMap RewriteMap;
01244     RewriteMap[StrideVal] = One;
01245 
01246     const SCEV *ByOne =
01247         SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
01248     DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
01249                  << "\n");
01250     return ByOne;
01251   }
01252 
01253   // Otherwise, just return the SCEV of the original pointer.
01254   return SE->getSCEV(Ptr);
01255 }
01256 
01257 void LoopVectorizationLegality::RuntimePointerCheck::insert(
01258     ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
01259     ValueToValueMap &Strides) {
01260   // Get the stride replaced scev.
01261   const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
01262   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
01263   assert(AR && "Invalid addrec expression");
01264   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
01265   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
01266   Pointers.push_back(Ptr);
01267   Starts.push_back(AR->getStart());
01268   Ends.push_back(ScEnd);
01269   IsWritePtr.push_back(WritePtr);
01270   DependencySetId.push_back(DepSetId);
01271 }
01272 
01273 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
01274   // We need to place the broadcast of invariant variables outside the loop.
01275   Instruction *Instr = dyn_cast<Instruction>(V);
01276   bool NewInstr =
01277       (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
01278                           Instr->getParent()) != LoopVectorBody.end());
01279   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
01280 
01281   // Place the code for broadcasting invariant variables in the new preheader.
01282   IRBuilder<>::InsertPointGuard Guard(Builder);
01283   if (Invariant)
01284     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
01285 
01286   // Broadcast the scalar into all locations in the vector.
01287   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
01288 
01289   return Shuf;
01290 }
01291 
01292 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
01293                                                  bool Negate) {
01294   assert(Val->getType()->isVectorTy() && "Must be a vector");
01295   assert(Val->getType()->getScalarType()->isIntegerTy() &&
01296          "Elem must be an integer");
01297   // Create the types.
01298   Type *ITy = Val->getType()->getScalarType();
01299   VectorType *Ty = cast<VectorType>(Val->getType());
01300   int VLen = Ty->getNumElements();
01301   SmallVector<Constant*, 8> Indices;
01302 
01303   // Create a vector of consecutive numbers from zero to VF.
01304   for (int i = 0; i < VLen; ++i) {
01305     int64_t Idx = Negate ? (-i) : i;
01306     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
01307   }
01308 
01309   // Add the consecutive indices to the vector value.
01310   Constant *Cv = ConstantVector::get(Indices);
01311   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
01312   return Builder.CreateAdd(Val, Cv, "induction");
01313 }
01314 
01315 /// \brief Find the operand of the GEP that should be checked for consecutive
01316 /// stores. This ignores trailing indices that have no effect on the final
01317 /// pointer.
01318 static unsigned getGEPInductionOperand(const DataLayout *DL,
01319                                        const GetElementPtrInst *Gep) {
01320   unsigned LastOperand = Gep->getNumOperands() - 1;
01321   unsigned GEPAllocSize = DL->getTypeAllocSize(
01322       cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
01323 
01324   // Walk backwards and try to peel off zeros.
01325   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
01326     // Find the type we're currently indexing into.
01327     gep_type_iterator GEPTI = gep_type_begin(Gep);
01328     std::advance(GEPTI, LastOperand - 1);
01329 
01330     // If it's a type with the same allocation size as the result of the GEP we
01331     // can peel off the zero index.
01332     if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
01333       break;
01334     --LastOperand;
01335   }
01336 
01337   return LastOperand;
01338 }
01339 
01340 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
01341   assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
01342   // Make sure that the pointer does not point to structs.
01343   if (Ptr->getType()->getPointerElementType()->isAggregateType())
01344     return 0;
01345 
01346   // If this value is a pointer induction variable we know it is consecutive.
01347   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
01348   if (Phi && Inductions.count(Phi)) {
01349     InductionInfo II = Inductions[Phi];
01350     if (IK_PtrInduction == II.IK)
01351       return 1;
01352     else if (IK_ReversePtrInduction == II.IK)
01353       return -1;
01354   }
01355 
01356   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
01357   if (!Gep)
01358     return 0;
01359 
01360   unsigned NumOperands = Gep->getNumOperands();
01361   Value *GpPtr = Gep->getPointerOperand();
01362   // If this GEP value is a consecutive pointer induction variable and all of
01363   // the indices are constant then we know it is consecutive. We can
01364   Phi = dyn_cast<PHINode>(GpPtr);
01365   if (Phi && Inductions.count(Phi)) {
01366 
01367     // Make sure that the pointer does not point to structs.
01368     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
01369     if (GepPtrType->getElementType()->isAggregateType())
01370       return 0;
01371 
01372     // Make sure that all of the index operands are loop invariant.
01373     for (unsigned i = 1; i < NumOperands; ++i)
01374       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
01375         return 0;
01376 
01377     InductionInfo II = Inductions[Phi];
01378     if (IK_PtrInduction == II.IK)
01379       return 1;
01380     else if (IK_ReversePtrInduction == II.IK)
01381       return -1;
01382   }
01383 
01384   unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
01385 
01386   // Check that all of the gep indices are uniform except for our induction
01387   // operand.
01388   for (unsigned i = 0; i != NumOperands; ++i)
01389     if (i != InductionOperand &&
01390         !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
01391       return 0;
01392 
01393   // We can emit wide load/stores only if the last non-zero index is the
01394   // induction variable.
01395   const SCEV *Last = 0;
01396   if (!Strides.count(Gep))
01397     Last = SE->getSCEV(Gep->getOperand(InductionOperand));
01398   else {
01399     // Because of the multiplication by a stride we can have a s/zext cast.
01400     // We are going to replace this stride by 1 so the cast is safe to ignore.
01401     //
01402     //  %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
01403     //  %0 = trunc i64 %indvars.iv to i32
01404     //  %mul = mul i32 %0, %Stride1
01405     //  %idxprom = zext i32 %mul to i64  << Safe cast.
01406     //  %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
01407     //
01408     Last = replaceSymbolicStrideSCEV(SE, Strides,
01409                                      Gep->getOperand(InductionOperand), Gep);
01410     if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
01411       Last =
01412           (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
01413               ? C->getOperand()
01414               : Last;
01415   }
01416   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
01417     const SCEV *Step = AR->getStepRecurrence(*SE);
01418 
01419     // The memory is consecutive because the last index is consecutive
01420     // and all other indices are loop invariant.
01421     if (Step->isOne())
01422       return 1;
01423     if (Step->isAllOnesValue())
01424       return -1;
01425   }
01426 
01427   return 0;
01428 }
01429 
01430 bool LoopVectorizationLegality::isUniform(Value *V) {
01431   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
01432 }
01433 
01434 InnerLoopVectorizer::VectorParts&
01435 InnerLoopVectorizer::getVectorValue(Value *V) {
01436   assert(V != Induction && "The new induction variable should not be used.");
01437   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
01438 
01439   // If we have a stride that is replaced by one, do it here.
01440   if (Legal->hasStride(V))
01441     V = ConstantInt::get(V->getType(), 1);
01442 
01443   // If we have this scalar in the map, return it.
01444   if (WidenMap.has(V))
01445     return WidenMap.get(V);
01446 
01447   // If this scalar is unknown, assume that it is a constant or that it is
01448   // loop invariant. Broadcast V and save the value for future uses.
01449   Value *B = getBroadcastInstrs(V);
01450   return WidenMap.splat(V, B);
01451 }
01452 
01453 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
01454   assert(Vec->getType()->isVectorTy() && "Invalid type");
01455   SmallVector<Constant*, 8> ShuffleMask;
01456   for (unsigned i = 0; i < VF; ++i)
01457     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
01458 
01459   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
01460                                      ConstantVector::get(ShuffleMask),
01461                                      "reverse");
01462 }
01463 
01464 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
01465   // Attempt to issue a wide load.
01466   LoadInst *LI = dyn_cast<LoadInst>(Instr);
01467   StoreInst *SI = dyn_cast<StoreInst>(Instr);
01468 
01469   assert((LI || SI) && "Invalid Load/Store instruction");
01470 
01471   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
01472   Type *DataTy = VectorType::get(ScalarDataTy, VF);
01473   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
01474   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
01475   // An alignment of 0 means target abi alignment. We need to use the scalar's
01476   // target abi alignment in such a case.
01477   if (!Alignment)
01478     Alignment = DL->getABITypeAlignment(ScalarDataTy);
01479   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
01480   unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
01481   unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
01482 
01483   if (SI && Legal->blockNeedsPredication(SI->getParent()))
01484     return scalarizeInstruction(Instr, true);
01485 
01486   if (ScalarAllocatedSize != VectorElementSize)
01487     return scalarizeInstruction(Instr);
01488 
01489   // If the pointer is loop invariant or if it is non-consecutive,
01490   // scalarize the load.
01491   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
01492   bool Reverse = ConsecutiveStride < 0;
01493   bool UniformLoad = LI && Legal->isUniform(Ptr);
01494   if (!ConsecutiveStride || UniformLoad)
01495     return scalarizeInstruction(Instr);
01496 
01497   Constant *Zero = Builder.getInt32(0);
01498   VectorParts &Entry = WidenMap.get(Instr);
01499 
01500   // Handle consecutive loads/stores.
01501   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
01502   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
01503     setDebugLocFromInst(Builder, Gep);
01504     Value *PtrOperand = Gep->getPointerOperand();
01505     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
01506     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
01507 
01508     // Create the new GEP with the new induction variable.
01509     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
01510     Gep2->setOperand(0, FirstBasePtr);
01511     Gep2->setName("gep.indvar.base");
01512     Ptr = Builder.Insert(Gep2);
01513   } else if (Gep) {
01514     setDebugLocFromInst(Builder, Gep);
01515     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
01516                                OrigLoop) && "Base ptr must be invariant");
01517 
01518     // The last index does not have to be the induction. It can be
01519     // consecutive and be a function of the index. For example A[I+1];
01520     unsigned NumOperands = Gep->getNumOperands();
01521     unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
01522     // Create the new GEP with the new induction variable.
01523     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
01524 
01525     for (unsigned i = 0; i < NumOperands; ++i) {
01526       Value *GepOperand = Gep->getOperand(i);
01527       Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
01528 
01529       // Update last index or loop invariant instruction anchored in loop.
01530       if (i == InductionOperand ||
01531           (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
01532         assert((i == InductionOperand ||
01533                SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
01534                "Must be last index or loop invariant");
01535 
01536         VectorParts &GEPParts = getVectorValue(GepOperand);
01537         Value *Index = GEPParts[0];
01538         Index = Builder.CreateExtractElement(Index, Zero);
01539         Gep2->setOperand(i, Index);
01540         Gep2->setName("gep.indvar.idx");
01541       }
01542     }
01543     Ptr = Builder.Insert(Gep2);
01544   } else {
01545     // Use the induction element ptr.
01546     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
01547     setDebugLocFromInst(Builder, Ptr);
01548     VectorParts &PtrVal = getVectorValue(Ptr);
01549     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
01550   }
01551 
01552   // Handle Stores:
01553   if (SI) {
01554     assert(!Legal->isUniform(SI->getPointerOperand()) &&
01555            "We do not allow storing to uniform addresses");
01556     setDebugLocFromInst(Builder, SI);
01557     // We don't want to update the value in the map as it might be used in
01558     // another expression. So don't use a reference type for "StoredVal".
01559     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
01560 
01561     for (unsigned Part = 0; Part < UF; ++Part) {
01562       // Calculate the pointer for the specific unroll-part.
01563       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
01564 
01565       if (Reverse) {
01566         // If we store to reverse consecutive memory locations then we need
01567         // to reverse the order of elements in the stored value.
01568         StoredVal[Part] = reverseVector(StoredVal[Part]);
01569         // If the address is consecutive but reversed, then the
01570         // wide store needs to start at the last vector element.
01571         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
01572         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
01573       }
01574 
01575       Value *VecPtr = Builder.CreateBitCast(PartPtr,
01576                                             DataTy->getPointerTo(AddressSpace));
01577       Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
01578     }
01579     return;
01580   }
01581 
01582   // Handle loads.
01583   assert(LI && "Must have a load instruction");
01584   setDebugLocFromInst(Builder, LI);
01585   for (unsigned Part = 0; Part < UF; ++Part) {
01586     // Calculate the pointer for the specific unroll-part.
01587     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
01588 
01589     if (Reverse) {
01590       // If the address is consecutive but reversed, then the
01591       // wide store needs to start at the last vector element.
01592       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
01593       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
01594     }
01595 
01596     Value *VecPtr = Builder.CreateBitCast(PartPtr,
01597                                           DataTy->getPointerTo(AddressSpace));
01598     Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
01599     cast<LoadInst>(LI)->setAlignment(Alignment);
01600     Entry[Part] = Reverse ? reverseVector(LI) :  LI;
01601   }
01602 }
01603 
01604 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
01605   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
01606   // Holds vector parameters or scalars, in case of uniform vals.
01607   SmallVector<VectorParts, 4> Params;
01608 
01609   setDebugLocFromInst(Builder, Instr);
01610 
01611   // Find all of the vectorized parameters.
01612   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
01613     Value *SrcOp = Instr->getOperand(op);
01614 
01615     // If we are accessing the old induction variable, use the new one.
01616     if (SrcOp == OldInduction) {
01617       Params.push_back(getVectorValue(SrcOp));
01618       continue;
01619     }
01620 
01621     // Try using previously calculated values.
01622     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
01623 
01624     // If the src is an instruction that appeared earlier in the basic block
01625     // then it should already be vectorized.
01626     if (SrcInst && OrigLoop->contains(SrcInst)) {
01627       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
01628       // The parameter is a vector value from earlier.
01629       Params.push_back(WidenMap.get(SrcInst));
01630     } else {
01631       // The parameter is a scalar from outside the loop. Maybe even a constant.
01632       VectorParts Scalars;
01633       Scalars.append(UF, SrcOp);
01634       Params.push_back(Scalars);
01635     }
01636   }
01637 
01638   assert(Params.size() == Instr->getNumOperands() &&
01639          "Invalid number of operands");
01640 
01641   // Does this instruction return a value ?
01642   bool IsVoidRetTy = Instr->getType()->isVoidTy();
01643 
01644   Value *UndefVec = IsVoidRetTy ? 0 :
01645     UndefValue::get(VectorType::get(Instr->getType(), VF));
01646   // Create a new entry in the WidenMap and initialize it to Undef or Null.
01647   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
01648 
01649   Instruction *InsertPt = Builder.GetInsertPoint();
01650   BasicBlock *IfBlock = Builder.GetInsertBlock();
01651   BasicBlock *CondBlock = 0;
01652 
01653   VectorParts Cond;
01654   Loop *VectorLp = 0;
01655   if (IfPredicateStore) {
01656     assert(Instr->getParent()->getSinglePredecessor() &&
01657            "Only support single predecessor blocks");
01658     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
01659                           Instr->getParent());
01660     VectorLp = LI->getLoopFor(IfBlock);
01661     assert(VectorLp && "Must have a loop for this block");
01662   }
01663 
01664   // For each vector unroll 'part':
01665   for (unsigned Part = 0; Part < UF; ++Part) {
01666     // For each scalar that we create:
01667     for (unsigned Width = 0; Width < VF; ++Width) {
01668 
01669       // Start if-block.
01670       Value *Cmp = 0;
01671       if (IfPredicateStore) {
01672         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
01673         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
01674         CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
01675         LoopVectorBody.push_back(CondBlock);
01676         VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
01677         // Update Builder with newly created basic block.
01678         Builder.SetInsertPoint(InsertPt);
01679       }
01680 
01681       Instruction *Cloned = Instr->clone();
01682       if (!IsVoidRetTy)
01683         Cloned->setName(Instr->getName() + ".cloned");
01684       // Replace the operands of the cloned instructions with extracted scalars.
01685       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
01686         Value *Op = Params[op][Part];
01687         // Param is a vector. Need to extract the right lane.
01688         if (Op->getType()->isVectorTy())
01689           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
01690         Cloned->setOperand(op, Op);
01691       }
01692 
01693       // Place the cloned scalar in the new loop.
01694       Builder.Insert(Cloned);
01695 
01696       // If the original scalar returns a value we need to place it in a vector
01697       // so that future users will be able to use it.
01698       if (!IsVoidRetTy)
01699         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
01700                                                        Builder.getInt32(Width));
01701       // End if-block.
01702       if (IfPredicateStore) {
01703          BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
01704          LoopVectorBody.push_back(NewIfBlock);
01705          VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
01706          Builder.SetInsertPoint(InsertPt);
01707          Instruction *OldBr = IfBlock->getTerminator();
01708          BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
01709          OldBr->eraseFromParent();
01710          IfBlock = NewIfBlock;
01711       }
01712     }
01713   }
01714 }
01715 
01716 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
01717                                  Instruction *Loc) {
01718   if (FirstInst)
01719     return FirstInst;
01720   if (Instruction *I = dyn_cast<Instruction>(V))
01721     return I->getParent() == Loc->getParent() ? I : 0;
01722   return 0;
01723 }
01724 
01725 std::pair<Instruction *, Instruction *>
01726 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
01727   Instruction *tnullptr = 0;
01728   if (!Legal->mustCheckStrides())
01729     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
01730 
01731   IRBuilder<> ChkBuilder(Loc);
01732 
01733   // Emit checks.
01734   Value *Check = 0;
01735   Instruction *FirstInst = 0;
01736   for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
01737                                          SE = Legal->strides_end();
01738        SI != SE; ++SI) {
01739     Value *Ptr = stripIntegerCast(*SI);
01740     Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
01741                                        "stride.chk");
01742     // Store the first instruction we create.
01743     FirstInst = getFirstInst(FirstInst, C, Loc);
01744     if (Check)
01745       Check = ChkBuilder.CreateOr(Check, C);
01746     else
01747       Check = C;
01748   }
01749 
01750   // We have to do this trickery because the IRBuilder might fold the check to a
01751   // constant expression in which case there is no Instruction anchored in a
01752   // the block.
01753   LLVMContext &Ctx = Loc->getContext();
01754   Instruction *TheCheck =
01755       BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
01756   ChkBuilder.Insert(TheCheck, "stride.not.one");
01757   FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
01758 
01759   return std::make_pair(FirstInst, TheCheck);
01760 }
01761 
01762 std::pair<Instruction *, Instruction *>
01763 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
01764   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
01765   Legal->getRuntimePointerCheck();
01766 
01767   Instruction *tnullptr = 0;
01768   if (!PtrRtCheck->Need)
01769     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
01770 
01771   unsigned NumPointers = PtrRtCheck->Pointers.size();
01772   SmallVector<TrackingVH<Value> , 2> Starts;
01773   SmallVector<TrackingVH<Value> , 2> Ends;
01774 
01775   LLVMContext &Ctx = Loc->getContext();
01776   SCEVExpander Exp(*SE, "induction");
01777   Instruction *FirstInst = 0;
01778 
01779   for (unsigned i = 0; i < NumPointers; ++i) {
01780     Value *Ptr = PtrRtCheck->Pointers[i];
01781     const SCEV *Sc = SE->getSCEV(Ptr);
01782 
01783     if (SE->isLoopInvariant(Sc, OrigLoop)) {
01784       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
01785             *Ptr <<"\n");
01786       Starts.push_back(Ptr);
01787       Ends.push_back(Ptr);
01788     } else {
01789       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
01790       unsigned AS = Ptr->getType()->getPointerAddressSpace();
01791 
01792       // Use this type for pointer arithmetic.
01793       Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
01794 
01795       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
01796       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
01797       Starts.push_back(Start);
01798       Ends.push_back(End);
01799     }
01800   }
01801 
01802   IRBuilder<> ChkBuilder(Loc);
01803   // Our instructions might fold to a constant.
01804   Value *MemoryRuntimeCheck = 0;
01805   for (unsigned i = 0; i < NumPointers; ++i) {
01806     for (unsigned j = i+1; j < NumPointers; ++j) {
01807       // No need to check if two readonly pointers intersect.
01808       if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
01809         continue;
01810 
01811       // Only need to check pointers between two different dependency sets.
01812       if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
01813        continue;
01814 
01815       unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
01816       unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
01817 
01818       assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
01819              (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
01820              "Trying to bounds check pointers with different address spaces");
01821 
01822       Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
01823       Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
01824 
01825       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
01826       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
01827       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy1, "bc");
01828       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy0, "bc");
01829 
01830       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
01831       FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
01832       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
01833       FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
01834       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
01835       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
01836       if (MemoryRuntimeCheck) {
01837         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
01838                                          "conflict.rdx");
01839         FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
01840       }
01841       MemoryRuntimeCheck = IsConflict;
01842     }
01843   }
01844 
01845   // We have to do this trickery because the IRBuilder might fold the check to a
01846   // constant expression in which case there is no Instruction anchored in a
01847   // the block.
01848   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
01849                                                  ConstantInt::getTrue(Ctx));
01850   ChkBuilder.Insert(Check, "memcheck.conflict");
01851   FirstInst = getFirstInst(FirstInst, Check, Loc);
01852   return std::make_pair(FirstInst, Check);
01853 }
01854 
01855 void InnerLoopVectorizer::createEmptyLoop() {
01856   /*
01857    In this function we generate a new loop. The new loop will contain
01858    the vectorized instructions while the old loop will continue to run the
01859    scalar remainder.
01860 
01861        [ ] <-- vector loop bypass (may consist of multiple blocks).
01862      /  |
01863     /   v
01864    |   [ ]     <-- vector pre header.
01865    |    |
01866    |    v
01867    |   [  ] \
01868    |   [  ]_|   <-- vector loop.
01869    |    |
01870     \   v
01871       >[ ]   <--- middle-block.
01872      /  |
01873     /   v
01874    |   [ ]     <--- new preheader.
01875    |    |
01876    |    v
01877    |   [ ] \
01878    |   [ ]_|   <-- old scalar loop to handle remainder.
01879     \   |
01880      \  v
01881       >[ ]     <-- exit block.
01882    ...
01883    */
01884 
01885   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
01886   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
01887   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
01888   assert(ExitBlock && "Must have an exit block");
01889 
01890   // Some loops have a single integer induction variable, while other loops
01891   // don't. One example is c++ iterators that often have multiple pointer
01892   // induction variables. In the code below we also support a case where we
01893   // don't have a single induction variable.
01894   OldInduction = Legal->getInduction();
01895   Type *IdxTy = Legal->getWidestInductionType();
01896 
01897   // Find the loop boundaries.
01898   const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
01899   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
01900 
01901   // The exit count might have the type of i64 while the phi is i32. This can
01902   // happen if we have an induction variable that is sign extended before the
01903   // compare. The only way that we get a backedge taken count is that the
01904   // induction variable was signed and as such will not overflow. In such a case
01905   // truncation is legal.
01906   if (ExitCount->getType()->getPrimitiveSizeInBits() >
01907       IdxTy->getPrimitiveSizeInBits())
01908     ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
01909 
01910   ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
01911   // Get the total trip count from the count by adding 1.
01912   ExitCount = SE->getAddExpr(ExitCount,
01913                              SE->getConstant(ExitCount->getType(), 1));
01914 
01915   // Expand the trip count and place the new instructions in the preheader.
01916   // Notice that the pre-header does not change, only the loop body.
01917   SCEVExpander Exp(*SE, "induction");
01918 
01919   // Count holds the overall loop count (N).
01920   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
01921                                    BypassBlock->getTerminator());
01922 
01923   // The loop index does not have to start at Zero. Find the original start
01924   // value from the induction PHI node. If we don't have an induction variable
01925   // then we know that it starts at zero.
01926   Builder.SetInsertPoint(BypassBlock->getTerminator());
01927   Value *StartIdx = ExtendedIdx = OldInduction ?
01928     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
01929                        IdxTy):
01930     ConstantInt::get(IdxTy, 0);
01931 
01932   assert(BypassBlock && "Invalid loop structure");
01933   LoopBypassBlocks.push_back(BypassBlock);
01934 
01935   // Split the single block loop into the two loop structure described above.
01936   BasicBlock *VectorPH =
01937   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
01938   BasicBlock *VecBody =
01939   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
01940   BasicBlock *MiddleBlock =
01941   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
01942   BasicBlock *ScalarPH =
01943   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
01944 
01945   // Create and register the new vector loop.
01946   Loop* Lp = new Loop();
01947   Loop *ParentLoop = OrigLoop->getParentLoop();
01948 
01949   // Insert the new loop into the loop nest and register the new basic blocks
01950   // before calling any utilities such as SCEV that require valid LoopInfo.
01951   if (ParentLoop) {
01952     ParentLoop->addChildLoop(Lp);
01953     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
01954     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
01955     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
01956   } else {
01957     LI->addTopLevelLoop(Lp);
01958   }
01959   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
01960 
01961   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
01962   // inside the loop.
01963   Builder.SetInsertPoint(VecBody->getFirstNonPHI());
01964 
01965   // Generate the induction variable.
01966   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
01967   Induction = Builder.CreatePHI(IdxTy, 2, "index");
01968   // The loop step is equal to the vectorization factor (num of SIMD elements)
01969   // times the unroll factor (num of SIMD instructions).
01970   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
01971 
01972   // This is the IR builder that we use to add all of the logic for bypassing
01973   // the new vector loop.
01974   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
01975   setDebugLocFromInst(BypassBuilder,
01976                       getDebugLocFromInstOrOperands(OldInduction));
01977 
01978   // We may need to extend the index in case there is a type mismatch.
01979   // We know that the count starts at zero and does not overflow.
01980   if (Count->getType() != IdxTy) {
01981     // The exit count can be of pointer type. Convert it to the correct
01982     // integer type.
01983     if (ExitCount->getType()->isPointerTy())
01984       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
01985     else
01986       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
01987   }
01988 
01989   // Add the start index to the loop count to get the new end index.
01990   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
01991 
01992   // Now we need to generate the expression for N - (N % VF), which is
01993   // the part that the vectorized body will execute.
01994   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
01995   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
01996   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
01997                                                      "end.idx.rnd.down");
01998 
01999   // Now, compare the new count to zero. If it is zero skip the vector loop and
02000   // jump to the scalar loop.
02001   Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
02002                                           "cmp.zero");
02003 
02004   BasicBlock *LastBypassBlock = BypassBlock;
02005 
02006   // Generate the code to check that the strides we assumed to be one are really
02007   // one. We want the new basic block to start at the first instruction in a
02008   // sequence of instructions that form a check.
02009   Instruction *StrideCheck;
02010   Instruction *FirstCheckInst;
02011   std::tie(FirstCheckInst, StrideCheck) =
02012       addStrideCheck(BypassBlock->getTerminator());
02013   if (StrideCheck) {
02014     // Create a new block containing the stride check.
02015     BasicBlock *CheckBlock =
02016         BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
02017     if (ParentLoop)
02018       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
02019     LoopBypassBlocks.push_back(CheckBlock);
02020 
02021     // Replace the branch into the memory check block with a conditional branch
02022     // for the "few elements case".
02023     Instruction *OldTerm = BypassBlock->getTerminator();
02024     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
02025     OldTerm->eraseFromParent();
02026 
02027     Cmp = StrideCheck;
02028     LastBypassBlock = CheckBlock;
02029   }
02030 
02031   // Generate the code that checks in runtime if arrays overlap. We put the
02032   // checks into a separate block to make the more common case of few elements
02033   // faster.
02034   Instruction *MemRuntimeCheck;
02035   std::tie(FirstCheckInst, MemRuntimeCheck) =
02036       addRuntimeCheck(LastBypassBlock->getTerminator());
02037   if (MemRuntimeCheck) {
02038     // Create a new block containing the memory check.
02039     BasicBlock *CheckBlock =
02040         LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
02041     if (ParentLoop)
02042       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
02043     LoopBypassBlocks.push_back(CheckBlock);
02044 
02045     // Replace the branch into the memory check block with a conditional branch
02046     // for the "few elements case".
02047     Instruction *OldTerm = LastBypassBlock->getTerminator();
02048     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
02049     OldTerm->eraseFromParent();
02050 
02051     Cmp = MemRuntimeCheck;
02052     LastBypassBlock = CheckBlock;
02053   }
02054 
02055   LastBypassBlock->getTerminator()->eraseFromParent();
02056   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
02057                      LastBypassBlock);
02058 
02059   // We are going to resume the execution of the scalar loop.
02060   // Go over all of the induction variables that we found and fix the
02061   // PHIs that are left in the scalar version of the loop.
02062   // The starting values of PHI nodes depend on the counter of the last
02063   // iteration in the vectorized loop.
02064   // If we come from a bypass edge then we need to start from the original
02065   // start value.
02066 
02067   // This variable saves the new starting index for the scalar loop.
02068   PHINode *ResumeIndex = 0;
02069   LoopVectorizationLegality::InductionList::iterator I, E;
02070   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
02071   // Set builder to point to last bypass block.
02072   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
02073   for (I = List->begin(), E = List->end(); I != E; ++I) {
02074     PHINode *OrigPhi = I->first;
02075     LoopVectorizationLegality::InductionInfo II = I->second;
02076 
02077     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
02078     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
02079                                          MiddleBlock->getTerminator());
02080     // We might have extended the type of the induction variable but we need a
02081     // truncated version for the scalar loop.
02082     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
02083       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
02084                       MiddleBlock->getTerminator()) : 0;
02085 
02086     Value *EndValue = 0;
02087     switch (II.IK) {
02088     case LoopVectorizationLegality::IK_NoInduction:
02089       llvm_unreachable("Unknown induction");
02090     case LoopVectorizationLegality::IK_IntInduction: {
02091       // Handle the integer induction counter.
02092       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
02093 
02094       // We have the canonical induction variable.
02095       if (OrigPhi == OldInduction) {
02096         // Create a truncated version of the resume value for the scalar loop,
02097         // we might have promoted the type to a larger width.
02098         EndValue =
02099           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
02100         // The new PHI merges the original incoming value, in case of a bypass,
02101         // or the value at the end of the vectorized loop.
02102         for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
02103           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
02104         TruncResumeVal->addIncoming(EndValue, VecBody);
02105 
02106         // We know what the end value is.
02107         EndValue = IdxEndRoundDown;
02108         // We also know which PHI node holds it.
02109         ResumeIndex = ResumeVal;
02110         break;
02111       }
02112 
02113       // Not the canonical induction variable - add the vector loop count to the
02114       // start value.
02115       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
02116                                                    II.StartValue->getType(),
02117                                                    "cast.crd");
02118       EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
02119       break;
02120     }
02121     case LoopVectorizationLegality::IK_ReverseIntInduction: {
02122       // Convert the CountRoundDown variable to the PHI size.
02123       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
02124                                                    II.StartValue->getType(),
02125                                                    "cast.crd");
02126       // Handle reverse integer induction counter.
02127       EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
02128       break;
02129     }
02130     case LoopVectorizationLegality::IK_PtrInduction: {
02131       // For pointer induction variables, calculate the offset using
02132       // the end index.
02133       EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
02134                                          "ptr.ind.end");
02135       break;
02136     }
02137     case LoopVectorizationLegality::IK_ReversePtrInduction: {
02138       // The value at the end of the loop for the reverse pointer is calculated
02139       // by creating a GEP with a negative index starting from the start value.
02140       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
02141       Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
02142                                               "rev.ind.end");
02143       EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
02144                                          "rev.ptr.ind.end");
02145       break;
02146     }
02147     }// end of case
02148 
02149     // The new PHI merges the original incoming value, in case of a bypass,
02150     // or the value at the end of the vectorized loop.
02151     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
02152       if (OrigPhi == OldInduction)
02153         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
02154       else
02155         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
02156     }
02157     ResumeVal->addIncoming(EndValue, VecBody);
02158 
02159     // Fix the scalar body counter (PHI node).
02160     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
02161     // The old inductions phi node in the scalar body needs the truncated value.
02162     if (OrigPhi == OldInduction)
02163       OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
02164     else
02165       OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
02166   }
02167 
02168   // If we are generating a new induction variable then we also need to
02169   // generate the code that calculates the exit value. This value is not
02170   // simply the end of the counter because we may skip the vectorized body
02171   // in case of a runtime check.
02172   if (!OldInduction){
02173     assert(!ResumeIndex && "Unexpected resume value found");
02174     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
02175                                   MiddleBlock->getTerminator());
02176     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
02177       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
02178     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
02179   }
02180 
02181   // Make sure that we found the index where scalar loop needs to continue.
02182   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
02183          "Invalid resume Index");
02184 
02185   // Add a check in the middle block to see if we have completed
02186   // all of the iterations in the first vector loop.
02187   // If (N - N%VF) == N, then we *don't* need to run the remainder.
02188   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
02189                                 ResumeIndex, "cmp.n",
02190                                 MiddleBlock->getTerminator());
02191 
02192   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
02193   // Remove the old terminator.
02194   MiddleBlock->getTerminator()->eraseFromParent();
02195 
02196   // Create i+1 and fill the PHINode.
02197   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
02198   Induction->addIncoming(StartIdx, VectorPH);
02199   Induction->addIncoming(NextIdx, VecBody);
02200   // Create the compare.
02201   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
02202   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
02203 
02204   // Now we have two terminators. Remove the old one from the block.
02205   VecBody->getTerminator()->eraseFromParent();
02206 
02207   // Get ready to start creating new instructions into the vectorized body.
02208   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
02209 
02210   // Save the state.
02211   LoopVectorPreHeader = VectorPH;
02212   LoopScalarPreHeader = ScalarPH;
02213   LoopMiddleBlock = MiddleBlock;
02214   LoopExitBlock = ExitBlock;
02215   LoopVectorBody.push_back(VecBody);
02216   LoopScalarBody = OldBasicBlock;
02217 
02218   LoopVectorizeHints Hints(Lp, true);
02219   Hints.setAlreadyVectorized(Lp);
02220 }
02221 
02222 /// This function returns the identity element (or neutral element) for
02223 /// the operation K.
02224 Constant*
02225 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
02226   switch (K) {
02227   case RK_IntegerXor:
02228   case RK_IntegerAdd:
02229   case RK_IntegerOr:
02230     // Adding, Xoring, Oring zero to a number does not change it.
02231     return ConstantInt::get(Tp, 0);
02232   case RK_IntegerMult:
02233     // Multiplying a number by 1 does not change it.
02234     return ConstantInt::get(Tp, 1);
02235   case RK_IntegerAnd:
02236     // AND-ing a number with an all-1 value does not change it.
02237     return ConstantInt::get(Tp, -1, true);
02238   case  RK_FloatMult:
02239     // Multiplying a number by 1 does not change it.
02240     return ConstantFP::get(Tp, 1.0L);
02241   case  RK_FloatAdd:
02242     // Adding zero to a number does not change it.
02243     return ConstantFP::get(Tp, 0.0L);
02244   default:
02245     llvm_unreachable("Unknown reduction kind");
02246   }
02247 }
02248 
02249 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
02250                                               Intrinsic::ID ValidIntrinsicID) {
02251   if (I.getNumArgOperands() != 1 ||
02252       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
02253       I.getType() != I.getArgOperand(0)->getType() ||
02254       !I.onlyReadsMemory())
02255     return Intrinsic::not_intrinsic;
02256 
02257   return ValidIntrinsicID;
02258 }
02259 
02260 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
02261                                                Intrinsic::ID ValidIntrinsicID) {
02262   if (I.getNumArgOperands() != 2 ||
02263       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
02264       !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
02265       I.getType() != I.getArgOperand(0)->getType() ||
02266       I.getType() != I.getArgOperand(1)->getType() ||
02267       !I.onlyReadsMemory())
02268     return Intrinsic::not_intrinsic;
02269 
02270   return ValidIntrinsicID;
02271 }
02272 
02273 
02274 static Intrinsic::ID
02275 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
02276   // If we have an intrinsic call, check if it is trivially vectorizable.
02277   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
02278     Intrinsic::ID ID = II->getIntrinsicID();
02279     if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
02280         ID == Intrinsic::lifetime_end)
02281       return ID;
02282     else
02283       return Intrinsic::not_intrinsic;
02284   }
02285 
02286   if (!TLI)
02287     return Intrinsic::not_intrinsic;
02288 
02289   LibFunc::Func Func;
02290   Function *F = CI->getCalledFunction();
02291   // We're going to make assumptions on the semantics of the functions, check
02292   // that the target knows that it's available in this environment and it does
02293   // not have local linkage.
02294   if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
02295     return Intrinsic::not_intrinsic;
02296 
02297   // Otherwise check if we have a call to a function that can be turned into a
02298   // vector intrinsic.
02299   switch (Func) {
02300   default:
02301     break;
02302   case LibFunc::sin:
02303   case LibFunc::sinf:
02304   case LibFunc::sinl:
02305     return checkUnaryFloatSignature(*CI, Intrinsic::sin);
02306   case LibFunc::cos:
02307   case LibFunc::cosf:
02308   case LibFunc::cosl:
02309     return checkUnaryFloatSignature(*CI, Intrinsic::cos);
02310   case LibFunc::exp:
02311   case LibFunc::expf:
02312   case LibFunc::expl:
02313     return checkUnaryFloatSignature(*CI, Intrinsic::exp);
02314   case LibFunc::exp2:
02315   case LibFunc::exp2f:
02316   case LibFunc::exp2l:
02317     return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
02318   case LibFunc::log:
02319   case LibFunc::logf:
02320   case LibFunc::logl:
02321     return checkUnaryFloatSignature(*CI, Intrinsic::log);
02322   case LibFunc::log10:
02323   case LibFunc::log10f:
02324   case LibFunc::log10l:
02325     return checkUnaryFloatSignature(*CI, Intrinsic::log10);
02326   case LibFunc::log2:
02327   case LibFunc::log2f:
02328   case LibFunc::log2l:
02329     return checkUnaryFloatSignature(*CI, Intrinsic::log2);
02330   case LibFunc::fabs:
02331   case LibFunc::fabsf:
02332   case LibFunc::fabsl:
02333     return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
02334   case LibFunc::copysign:
02335   case LibFunc::copysignf:
02336   case LibFunc::copysignl:
02337     return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
02338   case LibFunc::floor:
02339   case LibFunc::floorf:
02340   case LibFunc::floorl:
02341     return checkUnaryFloatSignature(*CI, Intrinsic::floor);
02342   case LibFunc::ceil:
02343   case LibFunc::ceilf:
02344   case LibFunc::ceill:
02345     return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
02346   case LibFunc::trunc:
02347   case LibFunc::truncf:
02348   case LibFunc::truncl:
02349     return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
02350   case LibFunc::rint:
02351   case LibFunc::rintf:
02352   case LibFunc::rintl:
02353     return checkUnaryFloatSignature(*CI, Intrinsic::rint);
02354   case LibFunc::nearbyint:
02355   case LibFunc::nearbyintf:
02356   case LibFunc::nearbyintl:
02357     return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
02358   case LibFunc::round:
02359   case LibFunc::roundf:
02360   case LibFunc::roundl:
02361     return checkUnaryFloatSignature(*CI, Intrinsic::round);
02362   case LibFunc::pow:
02363   case LibFunc::powf:
02364   case LibFunc::powl:
02365     return checkBinaryFloatSignature(*CI, Intrinsic::pow);
02366   }
02367 
02368   return Intrinsic::not_intrinsic;
02369 }
02370 
02371 /// This function translates the reduction kind to an LLVM binary operator.
02372 static unsigned
02373 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
02374   switch (Kind) {
02375     case LoopVectorizationLegality::RK_IntegerAdd:
02376       return Instruction::Add;
02377     case LoopVectorizationLegality::RK_IntegerMult:
02378       return Instruction::Mul;
02379     case LoopVectorizationLegality::RK_IntegerOr:
02380       return Instruction::Or;
02381     case LoopVectorizationLegality::RK_IntegerAnd:
02382       return Instruction::And;
02383     case LoopVectorizationLegality::RK_IntegerXor:
02384       return Instruction::Xor;
02385     case LoopVectorizationLegality::RK_FloatMult:
02386       return Instruction::FMul;
02387     case LoopVectorizationLegality::RK_FloatAdd:
02388       return Instruction::FAdd;
02389     case LoopVectorizationLegality::RK_IntegerMinMax:
02390       return Instruction::ICmp;
02391     case LoopVectorizationLegality::RK_FloatMinMax:
02392       return Instruction::FCmp;
02393     default:
02394       llvm_unreachable("Unknown reduction operation");
02395   }
02396 }
02397 
02398 Value *createMinMaxOp(IRBuilder<> &Builder,
02399                       LoopVectorizationLegality::MinMaxReductionKind RK,
02400                       Value *Left,
02401                       Value *Right) {
02402   CmpInst::Predicate P = CmpInst::ICMP_NE;
02403   switch (RK) {
02404   default:
02405     llvm_unreachable("Unknown min/max reduction kind");
02406   case LoopVectorizationLegality::MRK_UIntMin:
02407     P = CmpInst::ICMP_ULT;
02408     break;
02409   case LoopVectorizationLegality::MRK_UIntMax:
02410     P = CmpInst::ICMP_UGT;
02411     break;
02412   case LoopVectorizationLegality::MRK_SIntMin:
02413     P = CmpInst::ICMP_SLT;
02414     break;
02415   case LoopVectorizationLegality::MRK_SIntMax:
02416     P = CmpInst::ICMP_SGT;
02417     break;
02418   case LoopVectorizationLegality::MRK_FloatMin:
02419     P = CmpInst::FCMP_OLT;
02420     break;
02421   case LoopVectorizationLegality::MRK_FloatMax:
02422     P = CmpInst::FCMP_OGT;
02423     break;
02424   }
02425 
02426   Value *Cmp;
02427   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
02428       RK == LoopVectorizationLegality::MRK_FloatMax)
02429     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
02430   else
02431     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
02432 
02433   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
02434   return Select;
02435 }
02436 
02437 namespace {
02438 struct CSEDenseMapInfo {
02439   static bool canHandle(Instruction *I) {
02440     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
02441            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
02442   }
02443   static inline Instruction *getEmptyKey() {
02444     return DenseMapInfo<Instruction *>::getEmptyKey();
02445   }
02446   static inline Instruction *getTombstoneKey() {
02447     return DenseMapInfo<Instruction *>::getTombstoneKey();
02448   }
02449   static unsigned getHashValue(Instruction *I) {
02450     assert(canHandle(I) && "Unknown instruction!");
02451     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
02452                                                            I->value_op_end()));
02453   }
02454   static bool isEqual(Instruction *LHS, Instruction *RHS) {
02455     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
02456         LHS == getTombstoneKey() || RHS == getTombstoneKey())
02457       return LHS == RHS;
02458     return LHS->isIdenticalTo(RHS);
02459   }
02460 };
02461 }
02462 
02463 /// \brief Check whether this block is a predicated block.
02464 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
02465 /// = ...;  " blocks. We start with one vectorized basic block. For every
02466 /// conditional block we split this vectorized block. Therefore, every second
02467 /// block will be a predicated one.
02468 static bool isPredicatedBlock(unsigned BlockNum) {
02469   return BlockNum % 2;
02470 }
02471 
02472 ///\brief Perform cse of induction variable instructions.
02473 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
02474   // Perform simple cse.
02475   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
02476   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
02477     BasicBlock *BB = BBs[i];
02478     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
02479       Instruction *In = I++;
02480 
02481       if (!CSEDenseMapInfo::canHandle(In))
02482         continue;
02483 
02484       // Check if we can replace this instruction with any of the
02485       // visited instructions.
02486       if (Instruction *V = CSEMap.lookup(In)) {
02487         In->replaceAllUsesWith(V);
02488         In->eraseFromParent();
02489         continue;
02490       }
02491       // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
02492       // ...;" blocks for predicated stores. Every second block is a predicated
02493       // block.
02494       if (isPredicatedBlock(i))
02495         continue;
02496 
02497       CSEMap[In] = In;
02498     }
02499   }
02500 }
02501 
02502 /// \brief Adds a 'fast' flag to floating point operations.
02503 static Value *addFastMathFlag(Value *V) {
02504   if (isa<FPMathOperator>(V)){
02505     FastMathFlags Flags;
02506     Flags.setUnsafeAlgebra();
02507     cast<Instruction>(V)->setFastMathFlags(Flags);
02508   }
02509   return V;
02510 }
02511 
02512 void InnerLoopVectorizer::vectorizeLoop() {
02513   //===------------------------------------------------===//
02514   //
02515   // Notice: any optimization or new instruction that go
02516   // into the code below should be also be implemented in
02517   // the cost-model.
02518   //
02519   //===------------------------------------------------===//
02520   Constant *Zero = Builder.getInt32(0);
02521 
02522   // In order to support reduction variables we need to be able to vectorize
02523   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
02524   // stages. First, we create a new vector PHI node with no incoming edges.
02525   // We use this value when we vectorize all of the instructions that use the
02526   // PHI. Next, after all of the instructions in the block are complete we
02527   // add the new incoming edges to the PHI. At this point all of the
02528   // instructions in the basic block are vectorized, so we can use them to
02529   // construct the PHI.
02530   PhiVector RdxPHIsToFix;
02531 
02532   // Scan the loop in a topological order to ensure that defs are vectorized
02533   // before users.
02534   LoopBlocksDFS DFS(OrigLoop);
02535   DFS.perform(LI);
02536 
02537   // Vectorize all of the blocks in the original loop.
02538   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
02539        be = DFS.endRPO(); bb != be; ++bb)
02540     vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
02541 
02542   // At this point every instruction in the original loop is widened to
02543   // a vector form. We are almost done. Now, we need to fix the PHI nodes
02544   // that we vectorized. The PHI nodes are currently empty because we did
02545   // not want to introduce cycles. Notice that the remaining PHI nodes
02546   // that we need to fix are reduction variables.
02547 
02548   // Create the 'reduced' values for each of the induction vars.
02549   // The reduced values are the vector values that we scalarize and combine
02550   // after the loop is finished.
02551   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
02552        it != e; ++it) {
02553     PHINode *RdxPhi = *it;
02554     assert(RdxPhi && "Unable to recover vectorized PHI");
02555 
02556     // Find the reduction variable descriptor.
02557     assert(Legal->getReductionVars()->count(RdxPhi) &&
02558            "Unable to find the reduction variable");
02559     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
02560     (*Legal->getReductionVars())[RdxPhi];
02561 
02562     setDebugLocFromInst(Builder, RdxDesc.StartValue);
02563 
02564     // We need to generate a reduction vector from the incoming scalar.
02565     // To do so, we need to generate the 'identity' vector and override
02566     // one of the elements with the incoming scalar reduction. We need
02567     // to do it in the vector-loop preheader.
02568     Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
02569 
02570     // This is the vector-clone of the value that leaves the loop.
02571     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
02572     Type *VecTy = VectorExit[0]->getType();
02573 
02574     // Find the reduction identity variable. Zero for addition, or, xor,
02575     // one for multiplication, -1 for And.
02576     Value *Identity;
02577     Value *VectorStart;
02578     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
02579         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
02580       // MinMax reduction have the start value as their identify.
02581       if (VF == 1) {
02582         VectorStart = Identity = RdxDesc.StartValue;
02583       } else {
02584         VectorStart = Identity = Builder.CreateVectorSplat(VF,
02585                                                            RdxDesc.StartValue,
02586                                                            "minmax.ident");
02587       }
02588     } else {
02589       // Handle other reduction kinds:
02590       Constant *Iden =
02591       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
02592                                                       VecTy->getScalarType());
02593       if (VF == 1) {
02594         Identity = Iden;
02595         // This vector is the Identity vector where the first element is the
02596         // incoming scalar reduction.
02597         VectorStart = RdxDesc.StartValue;
02598       } else {
02599         Identity = ConstantVector::getSplat(VF, Iden);
02600 
02601         // This vector is the Identity vector where the first element is the
02602         // incoming scalar reduction.
02603         VectorStart = Builder.CreateInsertElement(Identity,
02604                                                   RdxDesc.StartValue, Zero);
02605       }
02606     }
02607 
02608     // Fix the vector-loop phi.
02609     // We created the induction variable so we know that the
02610     // preheader is the first entry.
02611     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
02612 
02613     // Reductions do not have to start at zero. They can start with
02614     // any loop invariant values.
02615     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
02616     BasicBlock *Latch = OrigLoop->getLoopLatch();
02617     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
02618     VectorParts &Val = getVectorValue(LoopVal);
02619     for (unsigned part = 0; part < UF; ++part) {
02620       // Make sure to add the reduction stat value only to the
02621       // first unroll part.
02622       Value *StartVal = (part == 0) ? VectorStart : Identity;
02623       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
02624       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
02625                                                   LoopVectorBody.back());
02626     }
02627 
02628     // Before each round, move the insertion point right between
02629     // the PHIs and the values we are going to write.
02630     // This allows us to write both PHINodes and the extractelement
02631     // instructions.
02632     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
02633 
02634     VectorParts RdxParts;
02635     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
02636     for (unsigned part = 0; part < UF; ++part) {
02637       // This PHINode contains the vectorized reduction variable, or
02638       // the initial value vector, if we bypass the vector loop.
02639       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
02640       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
02641       Value *StartVal = (part == 0) ? VectorStart : Identity;
02642       for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
02643         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
02644       NewPhi->addIncoming(RdxExitVal[part],
02645                           LoopVectorBody.back());
02646       RdxParts.push_back(NewPhi);
02647     }
02648 
02649     // Reduce all of the unrolled parts into a single vector.
02650     Value *ReducedPartRdx = RdxParts[0];
02651     unsigned Op = getReductionBinOp(RdxDesc.Kind);
02652     setDebugLocFromInst(Builder, ReducedPartRdx);
02653     for (unsigned part = 1; part < UF; ++part) {
02654       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
02655         // Floating point operations had to be 'fast' to enable the reduction.
02656         ReducedPartRdx = addFastMathFlag(
02657             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
02658                                 ReducedPartRdx, "bin.rdx"));
02659       else
02660         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
02661                                         ReducedPartRdx, RdxParts[part]);
02662     }
02663 
02664     if (VF > 1) {
02665       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
02666       // and vector ops, reducing the set of values being computed by half each
02667       // round.
02668       assert(isPowerOf2_32(VF) &&
02669              "Reduction emission only supported for pow2 vectors!");
02670       Value *TmpVec = ReducedPartRdx;
02671       SmallVector<Constant*, 32> ShuffleMask(VF, 0);
02672       for (unsigned i = VF; i != 1; i >>= 1) {
02673         // Move the upper half of the vector to the lower half.
02674         for (unsigned j = 0; j != i/2; ++j)
02675           ShuffleMask[j] = Builder.getInt32(i/2 + j);
02676 
02677         // Fill the rest of the mask with undef.
02678         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
02679                   UndefValue::get(Builder.getInt32Ty()));
02680 
02681         Value *Shuf =
02682         Builder.CreateShuffleVector(TmpVec,
02683                                     UndefValue::get(TmpVec->getType()),
02684                                     ConstantVector::get(ShuffleMask),
02685                                     "rdx.shuf");
02686 
02687         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
02688           // Floating point operations had to be 'fast' to enable the reduction.
02689           TmpVec = addFastMathFlag(Builder.CreateBinOp(
02690               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
02691         else
02692           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
02693       }
02694 
02695       // The result is in the first element of the vector.
02696       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
02697                                                     Builder.getInt32(0));
02698     }
02699 
02700     // Now, we need to fix the users of the reduction variable
02701     // inside and outside of the scalar remainder loop.
02702     // We know that the loop is in LCSSA form. We need to update the
02703     // PHI nodes in the exit blocks.
02704     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
02705          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
02706       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
02707       if (!LCSSAPhi) break;
02708 
02709       // All PHINodes need to have a single entry edge, or two if
02710       // we already fixed them.
02711       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
02712 
02713       // We found our reduction value exit-PHI. Update it with the
02714       // incoming bypass edge.
02715       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
02716         // Add an edge coming from the bypass.
02717         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
02718         break;
02719       }
02720     }// end of the LCSSA phi scan.
02721 
02722     // Fix the scalar loop reduction variable with the incoming reduction sum
02723     // from the vector body and from the backedge value.
02724     int IncomingEdgeBlockIdx =
02725     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
02726     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
02727     // Pick the other block.
02728     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
02729     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
02730     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
02731   }// end of for each redux variable.
02732 
02733   fixLCSSAPHIs();
02734 
02735   // Remove redundant induction instructions.
02736   cse(LoopVectorBody);
02737 }
02738 
02739 void InnerLoopVectorizer::fixLCSSAPHIs() {
02740   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
02741        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
02742     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
02743     if (!LCSSAPhi) break;
02744     if (LCSSAPhi->getNumIncomingValues() == 1)
02745       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
02746                             LoopMiddleBlock);
02747   }
02748 } 
02749 
02750 InnerLoopVectorizer::VectorParts
02751 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
02752   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
02753          "Invalid edge");
02754 
02755   // Look for cached value.
02756   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
02757   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
02758   if (ECEntryIt != MaskCache.end())
02759     return ECEntryIt->second;
02760 
02761   VectorParts SrcMask = createBlockInMask(Src);
02762 
02763   // The terminator has to be a branch inst!
02764   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
02765   assert(BI && "Unexpected terminator found");
02766 
02767   if (BI->isConditional()) {
02768     VectorParts EdgeMask = getVectorValue(BI->getCondition());
02769 
02770     if (BI->getSuccessor(0) != Dst)
02771       for (unsigned part = 0; part < UF; ++part)
02772         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
02773 
02774     for (unsigned part = 0; part < UF; ++part)
02775       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
02776 
02777     MaskCache[Edge] = EdgeMask;
02778     return EdgeMask;
02779   }
02780 
02781   MaskCache[Edge] = SrcMask;
02782   return SrcMask;
02783 }
02784 
02785 InnerLoopVectorizer::VectorParts
02786 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
02787   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
02788 
02789   // Loop incoming mask is all-one.
02790   if (OrigLoop->getHeader() == BB) {
02791     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
02792     return getVectorValue(C);
02793   }
02794 
02795   // This is the block mask. We OR all incoming edges, and with zero.
02796   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
02797   VectorParts BlockMask = getVectorValue(Zero);
02798 
02799   // For each pred:
02800   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
02801     VectorParts EM = createEdgeMask(*it, BB);
02802     for (unsigned part = 0; part < UF; ++part)
02803       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
02804   }
02805 
02806   return BlockMask;
02807 }
02808 
02809 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
02810                                               InnerLoopVectorizer::VectorParts &Entry,
02811                                               unsigned UF, unsigned VF, PhiVector *PV) {
02812   PHINode* P = cast<PHINode>(PN);
02813   // Handle reduction variables:
02814   if (Legal->getReductionVars()->count(P)) {
02815     for (unsigned part = 0; part < UF; ++part) {
02816       // This is phase one of vectorizing PHIs.
02817       Type *VecTy = (VF == 1) ? PN->getType() :
02818       VectorType::get(PN->getType(), VF);
02819       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
02820                                     LoopVectorBody.back()-> getFirstInsertionPt());
02821     }
02822     PV->push_back(P);
02823     return;
02824   }
02825 
02826   setDebugLocFromInst(Builder, P);
02827   // Check for PHI nodes that are lowered to vector selects.
02828   if (P->getParent() != OrigLoop->getHeader()) {
02829     // We know that all PHIs in non-header blocks are converted into
02830     // selects, so we don't have to worry about the insertion order and we
02831     // can just use the builder.
02832     // At this point we generate the predication tree. There may be
02833     // duplications since this is a simple recursive scan, but future
02834     // optimizations will clean it up.
02835 
02836     unsigned NumIncoming = P->getNumIncomingValues();
02837 
02838     // Generate a sequence of selects of the form:
02839     // SELECT(Mask3, In3,
02840     //      SELECT(Mask2, In2,
02841     //                   ( ...)))
02842     for (unsigned In = 0; In < NumIncoming; In++) {
02843       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
02844                                         P->getParent());
02845       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
02846 
02847       for (unsigned part = 0; part < UF; ++part) {
02848         // We might have single edge PHIs (blocks) - use an identity
02849         // 'select' for the first PHI operand.
02850         if (In == 0)
02851           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
02852                                              In0[part]);
02853         else
02854           // Select between the current value and the previous incoming edge
02855           // based on the incoming mask.
02856           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
02857                                              Entry[part], "predphi");
02858       }
02859     }
02860     return;
02861   }
02862 
02863   // This PHINode must be an induction variable.
02864   // Make sure that we know about it.
02865   assert(Legal->getInductionVars()->count(P) &&
02866          "Not an induction variable");
02867 
02868   LoopVectorizationLegality::InductionInfo II =
02869   Legal->getInductionVars()->lookup(P);
02870 
02871   switch (II.IK) {
02872     case LoopVectorizationLegality::IK_NoInduction:
02873       llvm_unreachable("Unknown induction");
02874     case LoopVectorizationLegality::IK_IntInduction: {
02875       assert(P->getType() == II.StartValue->getType() && "Types must match");
02876       Type *PhiTy = P->getType();
02877       Value *Broadcasted;
02878       if (P == OldInduction) {
02879         // Handle the canonical induction variable. We might have had to
02880         // extend the type.
02881         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
02882       } else {
02883         // Handle other induction variables that are now based on the
02884         // canonical one.
02885         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
02886                                                  "normalized.idx");
02887         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
02888         Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
02889                                         "offset.idx");
02890       }
02891       Broadcasted = getBroadcastInstrs(Broadcasted);
02892       // After broadcasting the induction variable we need to make the vector
02893       // consecutive by adding 0, 1, 2, etc.
02894       for (unsigned part = 0; part < UF; ++part)
02895         Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
02896       return;
02897     }
02898     case LoopVectorizationLegality::IK_ReverseIntInduction:
02899     case LoopVectorizationLegality::IK_PtrInduction:
02900     case LoopVectorizationLegality::IK_ReversePtrInduction:
02901       // Handle reverse integer and pointer inductions.
02902       Value *StartIdx = ExtendedIdx;
02903       // This is the normalized GEP that starts counting at zero.
02904       Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
02905                                                "normalized.idx");
02906 
02907       // Handle the reverse integer induction variable case.
02908       if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
02909         IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
02910         Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
02911                                                "resize.norm.idx");
02912         Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
02913                                                "reverse.idx");
02914 
02915         // This is a new value so do not hoist it out.
02916         Value *Broadcasted = getBroadcastInstrs(ReverseInd);
02917         // After broadcasting the induction variable we need to make the
02918         // vector consecutive by adding  ... -3, -2, -1, 0.
02919         for (unsigned part = 0; part < UF; ++part)
02920           Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
02921                                              true);
02922         return;
02923       }
02924 
02925       // Handle the pointer induction variable case.
02926       assert(P->getType()->isPointerTy() && "Unexpected type.");
02927 
02928       // Is this a reverse induction ptr or a consecutive induction ptr.
02929       bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
02930                       II.IK);
02931 
02932       // This is the vector of results. Notice that we don't generate
02933       // vector geps because scalar geps result in better code.
02934       for (unsigned part = 0; part < UF; ++part) {
02935         if (VF == 1) {
02936           int EltIndex = (part) * (Reverse ? -1 : 1);
02937           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
02938           Value *GlobalIdx;
02939           if (Reverse)
02940             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
02941           else
02942             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
02943 
02944           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
02945                                              "next.gep");
02946           Entry[part] = SclrGep;
02947           continue;
02948         }
02949 
02950         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
02951         for (unsigned int i = 0; i < VF; ++i) {
02952           int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
02953           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
02954           Value *GlobalIdx;
02955           if (!Reverse)
02956             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
02957           else
02958             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
02959 
02960           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
02961                                              "next.gep");
02962           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
02963                                                Builder.getInt32(i),
02964                                                "insert.gep");
02965         }
02966         Entry[part] = VecVal;
02967       }
02968       return;
02969   }
02970 }
02971 
02972 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
02973   // For each instruction in the old loop.
02974   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
02975     VectorParts &Entry = WidenMap.get(it);
02976     switch (it->getOpcode()) {
02977     case Instruction::Br:
02978       // Nothing to do for PHIs and BR, since we already took care of the
02979       // loop control flow instructions.
02980       continue;
02981     case Instruction::PHI:{
02982       // Vectorize PHINodes.
02983       widenPHIInstruction(it, Entry, UF, VF, PV);
02984       continue;
02985     }// End of PHI.
02986 
02987     case Instruction::Add:
02988     case Instruction::FAdd:
02989     case Instruction::Sub:
02990     case Instruction::FSub:
02991     case Instruction::Mul:
02992     case Instruction::FMul:
02993     case Instruction::UDiv:
02994     case Instruction::SDiv:
02995     case Instruction::FDiv:
02996     case Instruction::URem:
02997     case Instruction::SRem:
02998     case Instruction::FRem:
02999     case Instruction::Shl:
03000     case Instruction::LShr:
03001     case Instruction::AShr:
03002     case Instruction::And:
03003     case Instruction::Or:
03004     case Instruction::Xor: {
03005       // Just widen binops.
03006       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
03007       setDebugLocFromInst(Builder, BinOp);
03008       VectorParts &A = getVectorValue(it->getOperand(0));
03009       VectorParts &B = getVectorValue(it->getOperand(1));
03010 
03011       // Use this vector value for all users of the original instruction.
03012       for (unsigned Part = 0; Part < UF; ++Part) {
03013         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
03014 
03015         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
03016         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
03017         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
03018           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
03019           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
03020         }
03021         if (VecOp && isa<PossiblyExactOperator>(VecOp))
03022           VecOp->setIsExact(BinOp->isExact());
03023 
03024         // Copy the fast-math flags.
03025         if (VecOp && isa<FPMathOperator>(V))
03026           VecOp->setFastMathFlags(it->getFastMathFlags());
03027 
03028         Entry[Part] = V;
03029       }
03030       break;
03031     }
03032     case Instruction::Select: {
03033       // Widen selects.
03034       // If the selector is loop invariant we can create a select
03035       // instruction with a scalar condition. Otherwise, use vector-select.
03036       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
03037                                                OrigLoop);
03038       setDebugLocFromInst(Builder, it);
03039 
03040       // The condition can be loop invariant  but still defined inside the
03041       // loop. This means that we can't just use the original 'cond' value.
03042       // We have to take the 'vectorized' value and pick the first lane.
03043       // Instcombine will make this a no-op.
03044       VectorParts &Cond = getVectorValue(it->getOperand(0));
03045       VectorParts &Op0  = getVectorValue(it->getOperand(1));
03046       VectorParts &Op1  = getVectorValue(it->getOperand(2));
03047 
03048       Value *ScalarCond = (VF == 1) ? Cond[0] :
03049         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
03050 
03051       for (unsigned Part = 0; Part < UF; ++Part) {
03052         Entry[Part] = Builder.CreateSelect(
03053           InvariantCond ? ScalarCond : Cond[Part],
03054           Op0[Part],
03055           Op1[Part]);
03056       }
03057       break;
03058     }
03059 
03060     case Instruction::ICmp:
03061     case Instruction::FCmp: {
03062       // Widen compares. Generate vector compares.
03063       bool FCmp = (it->getOpcode() == Instruction::FCmp);
03064       CmpInst *Cmp = dyn_cast<CmpInst>(it);
03065       setDebugLocFromInst(Builder, it);
03066       VectorParts &A = getVectorValue(it->getOperand(0));
03067       VectorParts &B = getVectorValue(it->getOperand(1));
03068       for (unsigned Part = 0; Part < UF; ++Part) {
03069         Value *C = 0;
03070         if (FCmp)
03071           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
03072         else
03073           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
03074         Entry[Part] = C;
03075       }
03076       break;
03077     }
03078 
03079     case Instruction::Store:
03080     case Instruction::Load:
03081       vectorizeMemoryInstruction(it);
03082         break;
03083     case Instruction::ZExt:
03084     case Instruction::SExt:
03085     case Instruction::FPToUI:
03086     case Instruction::FPToSI:
03087     case Instruction::FPExt:
03088     case Instruction::PtrToInt:
03089     case Instruction::IntToPtr:
03090     case Instruction::SIToFP:
03091     case Instruction::UIToFP:
03092     case Instruction::Trunc:
03093     case Instruction::FPTrunc:
03094     case Instruction::BitCast: {
03095       CastInst *CI = dyn_cast<CastInst>(it);
03096       setDebugLocFromInst(Builder, it);
03097       /// Optimize the special case where the source is the induction
03098       /// variable. Notice that we can only optimize the 'trunc' case
03099       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
03100       /// c. other casts depend on pointer size.
03101       if (CI->getOperand(0) == OldInduction &&
03102           it->getOpcode() == Instruction::Trunc) {
03103         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
03104                                                CI->getType());
03105         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
03106         for (unsigned Part = 0; Part < UF; ++Part)
03107           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
03108         break;
03109       }
03110       /// Vectorize casts.
03111       Type *DestTy = (VF == 1) ? CI->getType() :
03112                                  VectorType::get(CI->getType(), VF);
03113 
03114       VectorParts &A = getVectorValue(it->getOperand(0));
03115       for (unsigned Part = 0; Part < UF; ++Part)
03116         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
03117       break;
03118     }
03119 
03120     case Instruction::Call: {
03121       // Ignore dbg intrinsics.
03122       if (isa<DbgInfoIntrinsic>(it))
03123         break;
03124       setDebugLocFromInst(Builder, it);
03125 
03126       Module *M = BB->getParent()->getParent();
03127       CallInst *CI = cast<CallInst>(it);
03128       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
03129       assert(ID && "Not an intrinsic call!");
03130       switch (ID) {
03131       case Intrinsic::lifetime_end:
03132       case Intrinsic::lifetime_start:
03133         scalarizeInstruction(it);
03134         break;
03135       default:
03136         for (unsigned Part = 0; Part < UF; ++Part) {
03137           SmallVector<Value *, 4> Args;
03138           for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
03139             VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
03140             Args.push_back(Arg[Part]);
03141           }
03142           Type *Tys[] = {CI->getType()};
03143           if (VF > 1)
03144             Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
03145 
03146           Function *F = Intrinsic::getDeclaration(M, ID, Tys);
03147           Entry[Part] = Builder.CreateCall(F, Args);
03148         }
03149         break;
03150       }
03151       break;
03152     }
03153 
03154     default:
03155       // All other instructions are unsupported. Scalarize them.
03156       scalarizeInstruction(it);
03157       break;
03158     }// end of switch.
03159   }// end of for_each instr.
03160 }
03161 
03162 void InnerLoopVectorizer::updateAnalysis() {
03163   // Forget the original basic block.
03164   SE->forgetLoop(OrigLoop);
03165 
03166   // Update the dominator tree information.
03167   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
03168          "Entry does not dominate exit.");
03169 
03170   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
03171     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
03172   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
03173 
03174   // Due to if predication of stores we might create a sequence of "if(pred)
03175   // a[i] = ...;  " blocks.
03176   for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
03177     if (i == 0)
03178       DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
03179     else if (isPredicatedBlock(i)) {
03180       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
03181     } else {
03182       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
03183     }
03184   }
03185 
03186   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
03187   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
03188   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
03189   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
03190 
03191   DEBUG(DT->verifyDomTree());
03192 }
03193 
03194 /// \brief Check whether it is safe to if-convert this phi node.
03195 ///
03196 /// Phi nodes with constant expressions that can trap are not safe to if
03197 /// convert.
03198 static bool canIfConvertPHINodes(BasicBlock *BB) {
03199   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
03200     PHINode *Phi = dyn_cast<PHINode>(I);
03201     if (!Phi)
03202       return true;
03203     for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
03204       if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
03205         if (C->canTrap())
03206           return false;
03207   }
03208   return true;
03209 }
03210 
03211 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
03212   if (!EnableIfConversion)
03213     return false;
03214 
03215   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
03216 
03217   // A list of pointers that we can safely read and write to.
03218   SmallPtrSet<Value *, 8> SafePointes;
03219 
03220   // Collect safe addresses.
03221   for (Loop::block_iterator BI = TheLoop->block_begin(),
03222          BE = TheLoop->block_end(); BI != BE; ++BI) {
03223     BasicBlock *BB = *BI;
03224 
03225     if (blockNeedsPredication(BB))
03226       continue;
03227 
03228     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
03229       if (LoadInst *LI = dyn_cast<LoadInst>(I))
03230         SafePointes.insert(LI->getPointerOperand());
03231       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
03232         SafePointes.insert(SI->getPointerOperand());
03233     }
03234   }
03235 
03236   // Collect the blocks that need predication.
03237   BasicBlock *Header = TheLoop->getHeader();
03238   for (Loop::block_iterator BI = TheLoop->block_begin(),
03239          BE = TheLoop->block_end(); BI != BE; ++BI) {
03240     BasicBlock *BB = *BI;
03241 
03242     // We don't support switch statements inside loops.
03243     if (!isa<BranchInst>(BB->getTerminator()))
03244       return false;
03245 
03246     // We must be able to predicate all blocks that need to be predicated.
03247     if (blockNeedsPredication(BB)) {
03248       if (!blockCanBePredicated(BB, SafePointes))
03249         return false;
03250     } else if (BB != Header && !canIfConvertPHINodes(BB))
03251       return false;
03252 
03253   }
03254 
03255   // We can if-convert this loop.
03256   return true;
03257 }
03258 
03259 bool LoopVectorizationLegality::canVectorize() {
03260   // We must have a loop in canonical form. Loops with indirectbr in them cannot
03261   // be canonicalized.
03262   if (!TheLoop->getLoopPreheader())
03263     return false;
03264 
03265   // We can only vectorize innermost loops.
03266   if (TheLoop->getSubLoopsVector().size())
03267     return false;
03268 
03269   // We must have a single backedge.
03270   if (TheLoop->getNumBackEdges() != 1)
03271     return false;
03272 
03273   // We must have a single exiting block.
03274   if (!TheLoop->getExitingBlock())
03275     return false;
03276 
03277   // We need to have a loop header.
03278   DEBUG(dbgs() << "LV: Found a loop: " <<
03279         TheLoop->getHeader()->getName() << '\n');
03280 
03281   // Check if we can if-convert non-single-bb loops.
03282   unsigned NumBlocks = TheLoop->getNumBlocks();
03283   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
03284     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
03285     return false;
03286   }
03287 
03288   // ScalarEvolution needs to be able to find the exit count.
03289   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
03290   if (ExitCount == SE->getCouldNotCompute()) {
03291     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
03292     return false;
03293   }
03294 
03295   // Do not loop-vectorize loops with a tiny trip count.
03296   BasicBlock *Latch = TheLoop->getLoopLatch();
03297   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
03298   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
03299     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
03300           "This loop is not worth vectorizing.\n");
03301     return false;
03302   }
03303 
03304   // Check if we can vectorize the instructions and CFG in this loop.
03305   if (!canVectorizeInstrs()) {
03306     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
03307     return false;
03308   }
03309 
03310   // Go over each instruction and look at memory deps.
03311   if (!canVectorizeMemory()) {
03312     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
03313     return false;
03314   }
03315 
03316   // Collect all of the variables that remain uniform after vectorization.
03317   collectLoopUniforms();
03318 
03319   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
03320         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
03321         <<"!\n");
03322 
03323   // Okay! We can vectorize. At this point we don't have any other mem analysis
03324   // which may limit our maximum vectorization factor, so just return true with
03325   // no restrictions.
03326   return true;
03327 }
03328 
03329 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
03330   if (Ty->isPointerTy())
03331     return DL.getIntPtrType(Ty);
03332 
03333   // It is possible that char's or short's overflow when we ask for the loop's
03334   // trip count, work around this by changing the type size.
03335   if (Ty->getScalarSizeInBits() < 32)
03336     return Type::getInt32Ty(Ty->getContext());
03337 
03338   return Ty;
03339 }
03340 
03341 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
03342   Ty0 = convertPointerToIntegerType(DL, Ty0);
03343   Ty1 = convertPointerToIntegerType(DL, Ty1);
03344   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
03345     return Ty0;
03346   return Ty1;
03347 }
03348 
03349 /// \brief Check that the instruction has outside loop users and is not an
03350 /// identified reduction variable.
03351 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
03352                                SmallPtrSet<Value *, 4> &Reductions) {
03353   // Reduction instructions are allowed to have exit users. All other
03354   // instructions must not have external users.
03355   if (!Reductions.count(Inst))
03356     //Check that all of the users of the loop are inside the BB.
03357     for (User *U : Inst->users()) {
03358       Instruction *UI = cast<Instruction>(U);
03359       // This user may be a reduction exit value.
03360       if (!TheLoop->contains(UI)) {
03361         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
03362         return true;
03363       }
03364     }
03365   return false;
03366 }
03367 
03368 bool LoopVectorizationLegality::canVectorizeInstrs() {
03369   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
03370   BasicBlock *Header = TheLoop->getHeader();
03371 
03372   // Look for the attribute signaling the absence of NaNs.
03373   Function &F = *Header->getParent();
03374   if (F.hasFnAttribute("no-nans-fp-math"))
03375     HasFunNoNaNAttr = F.getAttributes().getAttribute(
03376       AttributeSet::FunctionIndex,
03377       "no-nans-fp-math").getValueAsString() == "true";
03378 
03379   // For each block in the loop.
03380   for (Loop::block_iterator bb = TheLoop->block_begin(),
03381        be = TheLoop->block_end(); bb != be; ++bb) {
03382 
03383     // Scan the instructions in the block and look for hazards.
03384     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
03385          ++it) {
03386 
03387       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
03388         Type *PhiTy = Phi->getType();
03389         // Check that this PHI type is allowed.
03390         if (!PhiTy->isIntegerTy() &&
03391             !PhiTy->isFloatingPointTy() &&
03392             !PhiTy->isPointerTy()) {
03393           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
03394           return false;
03395         }
03396 
03397         // If this PHINode is not in the header block, then we know that we
03398         // can convert it to select during if-conversion. No need to check if
03399         // the PHIs in this block are induction or reduction variables.
03400         if (*bb != Header) {
03401           // Check that this instruction has no outside users or is an
03402           // identified reduction value with an outside user.
03403           if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
03404             continue;
03405           return false;
03406         }
03407 
03408         // We only allow if-converted PHIs with more than two incoming values.
03409         if (Phi->getNumIncomingValues() != 2) {
03410           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
03411           return false;
03412         }
03413 
03414         // This is the value coming from the preheader.
03415         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
03416         // Check if this is an induction variable.
03417         InductionKind IK = isInductionVariable(Phi);
03418 
03419         if (IK_NoInduction != IK) {
03420           // Get the widest type.
03421           if (!WidestIndTy)
03422             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
03423           else
03424             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
03425 
03426           // Int inductions are special because we only allow one IV.
03427           if (IK == IK_IntInduction) {
03428             // Use the phi node with the widest type as induction. Use the last
03429             // one if there are multiple (no good reason for doing this other
03430             // than it is expedient).
03431             if (!Induction || PhiTy == WidestIndTy)
03432               Induction = Phi;
03433           }
03434 
03435           DEBUG(dbgs() << "LV: Found an induction variable.\n");
03436           Inductions[Phi] = InductionInfo(StartValue, IK);
03437 
03438           // Until we explicitly handle the case of an induction variable with
03439           // an outside loop user we have to give up vectorizing this loop.
03440           if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
03441             return false;
03442 
03443           continue;
03444         }
03445 
03446         if (AddReductionVar(Phi, RK_IntegerAdd)) {
03447           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
03448           continue;
03449         }
03450         if (AddReductionVar(Phi, RK_IntegerMult)) {
03451           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
03452           continue;
03453         }
03454         if (AddReductionVar(Phi, RK_IntegerOr)) {
03455           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
03456           continue;
03457         }
03458         if (AddReductionVar(Phi, RK_IntegerAnd)) {
03459           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
03460           continue;
03461         }
03462         if (AddReductionVar(Phi, RK_IntegerXor)) {
03463           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
03464           continue;
03465         }
03466         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
03467           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
03468           continue;
03469         }
03470         if (AddReductionVar(Phi, RK_FloatMult)) {
03471           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
03472           continue;
03473         }
03474         if (AddReductionVar(Phi, RK_FloatAdd)) {
03475           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
03476           continue;
03477         }
03478         if (AddReductionVar(Phi, RK_FloatMinMax)) {
03479           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
03480                 "\n");
03481           continue;
03482         }
03483 
03484         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
03485         return false;
03486       }// end of PHI handling
03487 
03488       // We still don't handle functions. However, we can ignore dbg intrinsic
03489       // calls and we do handle certain intrinsic and libm functions.
03490       CallInst *CI = dyn_cast<CallInst>(it);
03491       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
03492         DEBUG(dbgs() << "LV: Found a call site.\n");
03493         return false;
03494       }
03495 
03496       // Check that the instruction return type is vectorizable.
03497       // Also, we can't vectorize extractelement instructions.
03498       if ((!VectorType::isValidElementType(it->getType()) &&
03499            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
03500         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
03501         return false;
03502       }
03503 
03504       // Check that the stored type is vectorizable.
03505       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
03506         Type *T = ST->getValueOperand()->getType();
03507         if (!VectorType::isValidElementType(T))
03508           return false;
03509         if (EnableMemAccessVersioning)
03510           collectStridedAcccess(ST);
03511       }
03512 
03513       if (EnableMemAccessVersioning)
03514         if (LoadInst *LI = dyn_cast<LoadInst>(it))
03515           collectStridedAcccess(LI);
03516 
03517       // Reduction instructions are allowed to have exit users.
03518       // All other instructions must not have external users.
03519       if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
03520         return false;
03521 
03522     } // next instr.
03523 
03524   }
03525 
03526   if (!Induction) {
03527     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
03528     if (Inductions.empty())
03529       return false;
03530   }
03531 
03532   return true;
03533 }
03534 
03535 ///\brief Remove GEPs whose indices but the last one are loop invariant and
03536 /// return the induction operand of the gep pointer.
03537 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
03538                                  const DataLayout *DL, Loop *Lp) {
03539   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
03540   if (!GEP)
03541     return Ptr;
03542 
03543   unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
03544 
03545   // Check that all of the gep indices are uniform except for our induction
03546   // operand.
03547   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
03548     if (i != InductionOperand &&
03549         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
03550       return Ptr;
03551   return GEP->getOperand(InductionOperand);
03552 }
03553 
03554 ///\brief Look for a cast use of the passed value.
03555 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
03556   Value *UniqueCast = 0;
03557   for (User *U : Ptr->users()) {
03558     CastInst *CI = dyn_cast<CastInst>(U);
03559     if (CI && CI->getType() == Ty) {
03560       if (!UniqueCast)
03561         UniqueCast = CI;
03562       else
03563         return 0;
03564     }
03565   }
03566   return UniqueCast;
03567 }
03568 
03569 ///\brief Get the stride of a pointer access in a loop.
03570 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
03571 /// pointer to the Value, or null otherwise.
03572 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
03573                                    const DataLayout *DL, Loop *Lp) {
03574   const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
03575   if (!PtrTy || PtrTy->isAggregateType())
03576     return 0;
03577 
03578   // Try to remove a gep instruction to make the pointer (actually index at this
03579   // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
03580   // pointer, otherwise, we are analyzing the index.
03581   Value *OrigPtr = Ptr;
03582 
03583   // The size of the pointer access.
03584   int64_t PtrAccessSize = 1;
03585 
03586   Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
03587   const SCEV *V = SE->getSCEV(Ptr);
03588 
03589   if (Ptr != OrigPtr)
03590     // Strip off casts.
03591     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
03592       V = C->getOperand();
03593 
03594   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
03595   if (!S)
03596     return 0;
03597 
03598   V = S->getStepRecurrence(*SE);
03599   if (!V)
03600     return 0;
03601 
03602   // Strip off the size of access multiplication if we are still analyzing the
03603   // pointer.
03604   if (OrigPtr == Ptr) {
03605     DL->getTypeAllocSize(PtrTy->getElementType());
03606     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
03607       if (M->getOperand(0)->getSCEVType() != scConstant)
03608         return 0;
03609 
03610       const APInt &APStepVal =
03611           cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
03612 
03613       // Huge step value - give up.
03614       if (APStepVal.getBitWidth() > 64)
03615         return 0;
03616 
03617       int64_t StepVal = APStepVal.getSExtValue();
03618       if (PtrAccessSize != StepVal)
03619         return 0;
03620       V = M->getOperand(1);
03621     }
03622   }
03623 
03624   // Strip off casts.
03625   Type *StripedOffRecurrenceCast = 0;
03626   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
03627     StripedOffRecurrenceCast = C->getType();
03628     V = C->getOperand();
03629   }
03630 
03631   // Look for the loop invariant symbolic value.
03632   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
03633   if (!U)
03634     return 0;
03635 
03636   Value *Stride = U->getValue();
03637   if (!Lp->isLoopInvariant(Stride))
03638     return 0;
03639 
03640   // If we have stripped off the recurrence cast we have to make sure that we
03641   // return the value that is used in this loop so that we can replace it later.
03642   if (StripedOffRecurrenceCast)
03643     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
03644 
03645   return Stride;
03646 }
03647 
03648 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
03649   Value *Ptr = 0;
03650   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
03651     Ptr = LI->getPointerOperand();
03652   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
03653     Ptr = SI->getPointerOperand();
03654   else
03655     return;
03656 
03657   Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
03658   if (!Stride)
03659     return;
03660 
03661   DEBUG(dbgs() << "LV: Found a strided access that we can version");
03662   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
03663   Strides[Ptr] = Stride;
03664   StrideSet.insert(Stride);
03665 }
03666 
03667 void LoopVectorizationLegality::collectLoopUniforms() {
03668   // We now know that the loop is vectorizable!
03669   // Collect variables that will remain uniform after vectorization.
03670   std::vector<Value*> Worklist;
03671   BasicBlock *Latch = TheLoop->getLoopLatch();
03672 
03673   // Start with the conditional branch and walk up the block.
03674   Worklist.push_back(Latch->getTerminator()->getOperand(0));
03675 
03676   // Also add all consecutive pointer values; these values will be uniform
03677   // after vectorization (and subsequent cleanup) and, until revectorization is
03678   // supported, all dependencies must also be uniform.
03679   for (Loop::block_iterator B = TheLoop->block_begin(),
03680        BE = TheLoop->block_end(); B != BE; ++B)
03681     for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
03682          I != IE; ++I)
03683       if (I->getType()->isPointerTy() && isConsecutivePtr(I))
03684         Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
03685 
03686   while (Worklist.size()) {
03687     Instruction *I = dyn_cast<Instruction>(Worklist.back());
03688     Worklist.pop_back();
03689 
03690     // Look at instructions inside this loop.
03691     // Stop when reaching PHI nodes.
03692     // TODO: we need to follow values all over the loop, not only in this block.
03693     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
03694       continue;
03695 
03696     // This is a known uniform.
03697     Uniforms.insert(I);
03698 
03699     // Insert all operands.
03700     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
03701   }
03702 }
03703 
03704 namespace {
03705 /// \brief Analyses memory accesses in a loop.
03706 ///
03707 /// Checks whether run time pointer checks are needed and builds sets for data
03708 /// dependence checking.
03709 class AccessAnalysis {
03710 public:
03711   /// \brief Read or write access location.
03712   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
03713   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
03714 
03715   /// \brief Set of potential dependent memory accesses.
03716   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
03717 
03718   AccessAnalysis(const DataLayout *Dl, DepCandidates &DA) :
03719     DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
03720     AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
03721 
03722   /// \brief Register a load  and whether it is only read from.
03723   void addLoad(Value *Ptr, bool IsReadOnly) {
03724     Accesses.insert(MemAccessInfo(Ptr, false));
03725     if (IsReadOnly)
03726       ReadOnlyPtr.insert(Ptr);
03727   }
03728 
03729   /// \brief Register a store.
03730   void addStore(Value *Ptr) {
03731     Accesses.insert(MemAccessInfo(Ptr, true));
03732   }
03733 
03734   /// \brief Check whether we can check the pointers at runtime for
03735   /// non-intersection.
03736   bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
03737                        unsigned &NumComparisons, ScalarEvolution *SE,
03738                        Loop *TheLoop, ValueToValueMap &Strides,
03739                        bool ShouldCheckStride = false);
03740 
03741   /// \brief Goes over all memory accesses, checks whether a RT check is needed
03742   /// and builds sets of dependent accesses.
03743   void buildDependenceSets() {
03744     // Process read-write pointers first.
03745     processMemAccesses(false);
03746     // Next, process read pointers.
03747     processMemAccesses(true);
03748   }
03749 
03750   bool isRTCheckNeeded() { return IsRTCheckNeeded; }
03751 
03752   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
03753   void resetDepChecks() { CheckDeps.clear(); }
03754 
03755   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
03756 
03757 private:
03758   typedef SetVector<MemAccessInfo> PtrAccessSet;
03759   typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
03760 
03761   /// \brief Go over all memory access or only the deferred ones if
03762   /// \p UseDeferred is true and check whether runtime pointer checks are needed
03763   /// and build sets of dependency check candidates.
03764   void processMemAccesses(bool UseDeferred);
03765 
03766   /// Set of all accesses.
03767   PtrAccessSet Accesses;
03768 
03769   /// Set of access to check after all writes have been processed.
03770   PtrAccessSet DeferredAccesses;
03771 
03772   /// Map of pointers to last access encountered.
03773   UnderlyingObjToAccessMap ObjToLastAccess;
03774 
03775   /// Set of accesses that need a further dependence check.
03776   MemAccessInfoSet CheckDeps;
03777 
03778   /// Set of pointers that are read only.
03779   SmallPtrSet<Value*, 16> ReadOnlyPtr;
03780 
03781   /// Set of underlying objects already written to.
03782   SmallPtrSet<Value*, 16> WriteObjects;
03783 
03784   const DataLayout *DL;
03785 
03786   /// Sets of potentially dependent accesses - members of one set share an
03787   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
03788   /// dependence check.
03789   DepCandidates &DepCands;
03790 
03791   bool AreAllWritesIdentified;
03792   bool AreAllReadsIdentified;
03793   bool IsRTCheckNeeded;
03794 };
03795 
03796 } // end anonymous namespace
03797 
03798 /// \brief Check whether a pointer can participate in a runtime bounds check.
03799 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
03800                                 Value *Ptr) {
03801   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
03802   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
03803   if (!AR)
03804     return false;
03805 
03806   return AR->isAffine();
03807 }
03808 
03809 /// \brief Check the stride of the pointer and ensure that it does not wrap in
03810 /// the address space.
03811 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
03812                         const Loop *Lp, ValueToValueMap &StridesMap);
03813 
03814 bool AccessAnalysis::canCheckPtrAtRT(
03815     LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
03816     unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
03817     ValueToValueMap &StridesMap, bool ShouldCheckStride) {
03818   // Find pointers with computable bounds. We are going to use this information
03819   // to place a runtime bound check.
03820   unsigned NumReadPtrChecks = 0;
03821   unsigned NumWritePtrChecks = 0;
03822   bool CanDoRT = true;
03823 
03824   bool IsDepCheckNeeded = isDependencyCheckNeeded();
03825   // We assign consecutive id to access from different dependence sets.
03826   // Accesses within the same set don't need a runtime check.
03827   unsigned RunningDepId = 1;
03828   DenseMap<Value *, unsigned> DepSetId;
03829 
03830   for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
03831        AI != AE; ++AI) {
03832     const MemAccessInfo &Access = *AI;
03833     Value *Ptr = Access.getPointer();
03834     bool IsWrite = Access.getInt();
03835 
03836     // Just add write checks if we have both.
03837     if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
03838       continue;
03839 
03840     if (IsWrite)
03841       ++NumWritePtrChecks;
03842     else
03843       ++NumReadPtrChecks;
03844 
03845     if (hasComputableBounds(SE, StridesMap, Ptr) &&
03846         // When we run after a failing dependency check we have to make sure we
03847         // don't have wrapping pointers.
03848         (!ShouldCheckStride ||
03849          isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
03850       // The id of the dependence set.
03851       unsigned DepId;
03852 
03853       if (IsDepCheckNeeded) {
03854         Value *Leader = DepCands.getLeaderValue(Access).getPointer();
03855         unsigned &LeaderId = DepSetId[Leader];
03856         if (!LeaderId)
03857           LeaderId = RunningDepId++;
03858         DepId = LeaderId;
03859       } else
03860         // Each access has its own dependence set.
03861         DepId = RunningDepId++;
03862 
03863       RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
03864 
03865       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
03866     } else {
03867       CanDoRT = false;
03868     }
03869   }
03870 
03871   if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
03872     NumComparisons = 0; // Only one dependence set.
03873   else {
03874     NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
03875                                            NumWritePtrChecks - 1));
03876   }
03877 
03878   // If the pointers that we would use for the bounds comparison have different
03879   // address spaces, assume the values aren't directly comparable, so we can't
03880   // use them for the runtime check. We also have to assume they could
03881   // overlap. In the future there should be metadata for whether address spaces
03882   // are disjoint.
03883   unsigned NumPointers = RtCheck.Pointers.size();
03884   for (unsigned i = 0; i < NumPointers; ++i) {
03885     for (unsigned j = i + 1; j < NumPointers; ++j) {
03886       // Only need to check pointers between two different dependency sets.
03887       if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
03888        continue;
03889 
03890       Value *PtrI = RtCheck.Pointers[i];
03891       Value *PtrJ = RtCheck.Pointers[j];
03892 
03893       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
03894       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
03895       if (ASi != ASj) {
03896         DEBUG(dbgs() << "LV: Runtime check would require comparison between"
03897                        " different address spaces\n");
03898         return false;
03899       }
03900     }
03901   }
03902 
03903   return CanDoRT;
03904 }
03905 
03906 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
03907   return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
03908 }
03909 
03910 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
03911   // We process the set twice: first we process read-write pointers, last we
03912   // process read-only pointers. This allows us to skip dependence tests for
03913   // read-only pointers.
03914 
03915   PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
03916   for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
03917     const MemAccessInfo &Access = *AI;
03918     Value *Ptr = Access.getPointer();
03919     bool IsWrite = Access.getInt();
03920 
03921     DepCands.insert(Access);
03922 
03923     // Memorize read-only pointers for later processing and skip them in the
03924     // first round (they need to be checked after we have seen all write
03925     // pointers). Note: we also mark pointer that are not consecutive as
03926     // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
03927     // second check for "!IsWrite".
03928     bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
03929     if (!UseDeferred && IsReadOnlyPtr) {
03930       DeferredAccesses.insert(Access);
03931       continue;
03932     }
03933 
03934     bool NeedDepCheck = false;
03935     // Check whether there is the possibility of dependency because of
03936     // underlying objects being the same.
03937     typedef SmallVector<Value*, 16> ValueVector;
03938     ValueVector TempObjects;
03939     GetUnderlyingObjects(Ptr, TempObjects, DL);
03940     for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
03941          UI != UE; ++UI) {
03942       Value *UnderlyingObj = *UI;
03943 
03944       // If this is a write then it needs to be an identified object.  If this a
03945       // read and all writes (so far) are identified function scope objects we
03946       // don't need an identified underlying object but only an Argument (the
03947       // next write is going to invalidate this assumption if it is
03948       // unidentified).
03949       // This is a micro-optimization for the case where all writes are
03950       // identified and we have one argument pointer.
03951       // Otherwise, we do need a runtime check.
03952       if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
03953           (!IsWrite && (!AreAllWritesIdentified ||
03954                         !isa<Argument>(UnderlyingObj)) &&
03955            !isIdentifiedObject(UnderlyingObj))) {
03956         DEBUG(dbgs() << "LV: Found an unidentified " <<
03957               (IsWrite ?  "write" : "read" ) << " ptr: " << *UnderlyingObj <<
03958               "\n");
03959         IsRTCheckNeeded = (IsRTCheckNeeded ||
03960                            !isIdentifiedObject(UnderlyingObj) ||
03961                            !AreAllReadsIdentified);
03962 
03963         if (IsWrite)
03964           AreAllWritesIdentified = false;
03965         if (!IsWrite)
03966           AreAllReadsIdentified = false;
03967       }
03968 
03969       // If this is a write - check other reads and writes for conflicts.  If
03970       // this is a read only check other writes for conflicts (but only if there
03971       // is no other write to the ptr - this is an optimization to catch "a[i] =
03972       // a[i] + " without having to do a dependence check).
03973       if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
03974         NeedDepCheck = true;
03975 
03976       if (IsWrite)
03977         WriteObjects.insert(UnderlyingObj);
03978 
03979       // Create sets of pointers connected by shared underlying objects.
03980       UnderlyingObjToAccessMap::iterator Prev =
03981         ObjToLastAccess.find(UnderlyingObj);
03982       if (Prev != ObjToLastAccess.end())
03983         DepCands.unionSets(Access, Prev->second);
03984 
03985       ObjToLastAccess[UnderlyingObj] = Access;
03986     }
03987 
03988     if (NeedDepCheck)
03989       CheckDeps.insert(Access);
03990   }
03991 }
03992 
03993 namespace {
03994 /// \brief Checks memory dependences among accesses to the same underlying
03995 /// object to determine whether there vectorization is legal or not (and at
03996 /// which vectorization factor).
03997 ///
03998 /// This class works under the assumption that we already checked that memory
03999 /// locations with different underlying pointers are "must-not alias".
04000 /// We use the ScalarEvolution framework to symbolically evalutate access
04001 /// functions pairs. Since we currently don't restructure the loop we can rely
04002 /// on the program order of memory accesses to determine their safety.
04003 /// At the moment we will only deem accesses as safe for:
04004 ///  * A negative constant distance assuming program order.
04005 ///
04006 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
04007 ///            a[i] = tmp;                y = a[i];
04008 ///
04009 ///   The latter case is safe because later checks guarantuee that there can't
04010 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
04011 ///   the same variable: a header phi can only be an induction or a reduction, a
04012 ///   reduction can't have a memory sink, an induction can't have a memory
04013 ///   source). This is important and must not be violated (or we have to
04014 ///   resort to checking for cycles through memory).
04015 ///
04016 ///  * A positive constant distance assuming program order that is bigger
04017 ///    than the biggest memory access.
04018 ///
04019 ///     tmp = a[i]        OR              b[i] = x
04020 ///     a[i+2] = tmp                      y = b[i+2];
04021 ///
04022 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
04023 ///
04024 ///  * Zero distances and all accesses have the same size.
04025 ///
04026 class MemoryDepChecker {
04027 public:
04028   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
04029   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
04030 
04031   MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
04032       : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
04033         ShouldRetryWithRuntimeCheck(false) {}
04034 
04035   /// \brief Register the location (instructions are given increasing numbers)
04036   /// of a write access.
04037   void addAccess(StoreInst *SI) {
04038     Value *Ptr = SI->getPointerOperand();
04039     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
04040     InstMap.push_back(SI);
04041     ++AccessIdx;
04042   }
04043 
04044   /// \brief Register the location (instructions are given increasing numbers)
04045   /// of a write access.
04046   void addAccess(LoadInst *LI) {
04047     Value *Ptr = LI->getPointerOperand();
04048     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
04049     InstMap.push_back(LI);
04050     ++AccessIdx;
04051   }
04052 
04053   /// \brief Check whether the dependencies between the accesses are safe.
04054   ///
04055   /// Only checks sets with elements in \p CheckDeps.
04056   bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
04057                    MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
04058 
04059   /// \brief The maximum number of bytes of a vector register we can vectorize
04060   /// the accesses safely with.
04061   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
04062 
04063   /// \brief In same cases when the dependency check fails we can still
04064   /// vectorize the loop with a dynamic array access check.
04065   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
04066 
04067 private:
04068   ScalarEvolution *SE;
04069   const DataLayout *DL;
04070   const Loop *InnermostLoop;
04071 
04072   /// \brief Maps access locations (ptr, read/write) to program order.
04073   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
04074 
04075   /// \brief Memory access instructions in program order.
04076   SmallVector<Instruction *, 16> InstMap;
04077 
04078   /// \brief The program order index to be used for the next instruction.
04079   unsigned AccessIdx;
04080 
04081   // We can access this many bytes in parallel safely.
04082   unsigned MaxSafeDepDistBytes;
04083 
04084   /// \brief If we see a non-constant dependence distance we can still try to
04085   /// vectorize this loop with runtime checks.
04086   bool ShouldRetryWithRuntimeCheck;
04087 
04088   /// \brief Check whether there is a plausible dependence between the two
04089   /// accesses.
04090   ///
04091   /// Access \p A must happen before \p B in program order. The two indices
04092   /// identify the index into the program order map.
04093   ///
04094   /// This function checks  whether there is a plausible dependence (or the
04095   /// absence of such can't be proved) between the two accesses. If there is a
04096   /// plausible dependence but the dependence distance is bigger than one
04097   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
04098   /// distance is smaller than any other distance encountered so far).
04099   /// Otherwise, this function returns true signaling a possible dependence.
04100   bool isDependent(const MemAccessInfo &A, unsigned AIdx,
04101                    const MemAccessInfo &B, unsigned BIdx,
04102                    ValueToValueMap &Strides);
04103 
04104   /// \brief Check whether the data dependence could prevent store-load
04105   /// forwarding.
04106   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
04107 };
04108 
04109 } // end anonymous namespace
04110 
04111 static bool isInBoundsGep(Value *Ptr) {
04112   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
04113     return GEP->isInBounds();
04114   return false;
04115 }
04116 
04117 /// \brief Check whether the access through \p Ptr has a constant stride.
04118 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
04119                         const Loop *Lp, ValueToValueMap &StridesMap) {
04120   const Type *Ty = Ptr->getType();
04121   assert(Ty->isPointerTy() && "Unexpected non-ptr");
04122 
04123   // Make sure that the pointer does not point to aggregate types.
04124   const PointerType *PtrTy = cast<PointerType>(Ty);
04125   if (PtrTy->getElementType()->isAggregateType()) {
04126     DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
04127           "\n");
04128     return 0;
04129   }
04130 
04131   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
04132 
04133   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
04134   if (!AR) {
04135     DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
04136           << *Ptr << " SCEV: " << *PtrScev << "\n");
04137     return 0;
04138   }
04139 
04140   // The accesss function must stride over the innermost loop.
04141   if (Lp != AR->getLoop()) {
04142     DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
04143           *Ptr << " SCEV: " << *PtrScev << "\n");
04144   }
04145 
04146   // The address calculation must not wrap. Otherwise, a dependence could be
04147   // inverted.
04148   // An inbounds getelementptr that is a AddRec with a unit stride
04149   // cannot wrap per definition. The unit stride requirement is checked later.
04150   // An getelementptr without an inbounds attribute and unit stride would have
04151   // to access the pointer value "0" which is undefined behavior in address
04152   // space 0, therefore we can also vectorize this case.
04153   bool IsInBoundsGEP = isInBoundsGep(Ptr);
04154   bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
04155   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
04156   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
04157     DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
04158           << *Ptr << " SCEV: " << *PtrScev << "\n");
04159     return 0;
04160   }
04161 
04162   // Check the step is constant.
04163   const SCEV *Step = AR->getStepRecurrence(*SE);
04164 
04165   // Calculate the pointer stride and check if it is consecutive.
04166   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
04167   if (!C) {
04168     DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
04169           " SCEV: " << *PtrScev << "\n");
04170     return 0;
04171   }
04172 
04173   int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
04174   const APInt &APStepVal = C->getValue()->getValue();
04175 
04176   // Huge step value - give up.
04177   if (APStepVal.getBitWidth() > 64)
04178     return 0;
04179 
04180   int64_t StepVal = APStepVal.getSExtValue();
04181 
04182   // Strided access.
04183   int64_t Stride = StepVal / Size;
04184   int64_t Rem = StepVal % Size;
04185   if (Rem)
04186     return 0;
04187 
04188   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
04189   // know we can't "wrap around the address space". In case of address space
04190   // zero we know that this won't happen without triggering undefined behavior.
04191   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
04192       Stride != 1 && Stride != -1)
04193     return 0;
04194 
04195   return Stride;
04196 }
04197 
04198 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
04199                                                     unsigned TypeByteSize) {
04200   // If loads occur at a distance that is not a multiple of a feasible vector
04201   // factor store-load forwarding does not take place.
04202   // Positive dependences might cause troubles because vectorizing them might
04203   // prevent store-load forwarding making vectorized code run a lot slower.
04204   //   a[i] = a[i-3] ^ a[i-8];
04205   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
04206   //   hence on your typical architecture store-load forwarding does not take
04207   //   place. Vectorizing in such cases does not make sense.
04208   // Store-load forwarding distance.
04209   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
04210   // Maximum vector factor.
04211   unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
04212   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
04213     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
04214 
04215   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
04216        vf *= 2) {
04217     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
04218       MaxVFWithoutSLForwardIssues = (vf >>=1);
04219       break;
04220     }
04221   }
04222 
04223   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
04224     DEBUG(dbgs() << "LV: Distance " << Distance <<
04225           " that could cause a store-load forwarding conflict\n");
04226     return true;
04227   }
04228 
04229   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
04230       MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
04231     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
04232   return false;
04233 }
04234 
04235 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
04236                                    const MemAccessInfo &B, unsigned BIdx,
04237                                    ValueToValueMap &Strides) {
04238   assert (AIdx < BIdx && "Must pass arguments in program order");
04239 
04240   Value *APtr = A.getPointer();
04241   Value *BPtr = B.getPointer();
04242   bool AIsWrite = A.getInt();
04243   bool BIsWrite = B.getInt();
04244 
04245   // Two reads are independent.
04246   if (!AIsWrite && !BIsWrite)
04247     return false;
04248 
04249   const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
04250   const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
04251 
04252   int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
04253   int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
04254 
04255   const SCEV *Src = AScev;
04256   const SCEV *Sink = BScev;
04257 
04258   // If the induction step is negative we have to invert source and sink of the
04259   // dependence.
04260   if (StrideAPtr < 0) {
04261     //Src = BScev;
04262     //Sink = AScev;
04263     std::swap(APtr, BPtr);
04264     std::swap(Src, Sink);
04265     std::swap(AIsWrite, BIsWrite);
04266     std::swap(AIdx, BIdx);
04267     std::swap(StrideAPtr, StrideBPtr);
04268   }
04269 
04270   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
04271 
04272   DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
04273         << "(Induction step: " << StrideAPtr <<  ")\n");
04274   DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
04275         << *InstMap[BIdx] << ": " << *Dist << "\n");
04276 
04277   // Need consecutive accesses. We don't want to vectorize
04278   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
04279   // the address space.
04280   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
04281     DEBUG(dbgs() << "Non-consecutive pointer access\n");
04282     return true;
04283   }
04284 
04285   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
04286   if (!C) {
04287     DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
04288     ShouldRetryWithRuntimeCheck = true;
04289     return true;
04290   }
04291 
04292   Type *ATy = APtr->getType()->getPointerElementType();
04293   Type *BTy = BPtr->getType()->getPointerElementType();
04294   unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
04295 
04296   // Negative distances are not plausible dependencies.
04297   const APInt &Val = C->getValue()->getValue();
04298   if (Val.isNegative()) {
04299     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
04300     if (IsTrueDataDependence &&
04301         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
04302          ATy != BTy))
04303       return true;
04304 
04305     DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
04306     return false;
04307   }
04308 
04309   // Write to the same location with the same size.
04310   // Could be improved to assert type sizes are the same (i32 == float, etc).
04311   if (Val == 0) {
04312     if (ATy == BTy)
04313       return false;
04314     DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
04315     return true;
04316   }
04317 
04318   assert(Val.isStrictlyPositive() && "Expect a positive value");
04319 
04320   // Positive distance bigger than max vectorization factor.
04321   if (ATy != BTy) {
04322     DEBUG(dbgs() <<
04323           "LV: ReadWrite-Write positive dependency with different types\n");
04324     return false;
04325   }
04326 
04327   unsigned Distance = (unsigned) Val.getZExtValue();
04328 
04329   // Bail out early if passed-in parameters make vectorization not feasible.
04330   unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
04331   unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
04332 
04333   // The distance must be bigger than the size needed for a vectorized version
04334   // of the operation and the size of the vectorized operation must not be
04335   // bigger than the currrent maximum size.
04336   if (Distance < 2*TypeByteSize ||
04337       2*TypeByteSize > MaxSafeDepDistBytes ||
04338       Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
04339     DEBUG(dbgs() << "LV: Failure because of Positive distance "
04340         << Val.getSExtValue() << '\n');
04341     return true;
04342   }
04343 
04344   MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
04345     Distance : MaxSafeDepDistBytes;
04346 
04347   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
04348   if (IsTrueDataDependence &&
04349       couldPreventStoreLoadForward(Distance, TypeByteSize))
04350      return true;
04351 
04352   DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
04353         " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
04354 
04355   return false;
04356 }
04357 
04358 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
04359                                    MemAccessInfoSet &CheckDeps,
04360                                    ValueToValueMap &Strides) {
04361 
04362   MaxSafeDepDistBytes = -1U;
04363   while (!CheckDeps.empty()) {
04364     MemAccessInfo CurAccess = *CheckDeps.begin();
04365 
04366     // Get the relevant memory access set.
04367     EquivalenceClasses<MemAccessInfo>::iterator I =
04368       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
04369 
04370     // Check accesses within this set.
04371     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
04372     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
04373 
04374     // Check every access pair.
04375     while (AI != AE) {
04376       CheckDeps.erase(*AI);
04377       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
04378       while (OI != AE) {
04379         // Check every accessing instruction pair in program order.
04380         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
04381              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
04382           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
04383                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
04384             if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
04385               return false;
04386             if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
04387               return false;
04388           }
04389         ++OI;
04390       }
04391       AI++;
04392     }
04393   }
04394   return true;
04395 }
04396 
04397 bool LoopVectorizationLegality::canVectorizeMemory() {
04398 
04399   typedef SmallVector<Value*, 16> ValueVector;
04400   typedef SmallPtrSet<Value*, 16> ValueSet;
04401 
04402   // Holds the Load and Store *instructions*.
04403   ValueVector Loads;
04404   ValueVector Stores;
04405 
04406   // Holds all the different accesses in the loop.
04407   unsigned NumReads = 0;
04408   unsigned NumReadWrites = 0;
04409 
04410   PtrRtCheck.Pointers.clear();
04411   PtrRtCheck.Need = false;
04412 
04413   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
04414   MemoryDepChecker DepChecker(SE, DL, TheLoop);
04415 
04416   // For each block.
04417   for (Loop::block_iterator bb = TheLoop->block_begin(),
04418        be = TheLoop->block_end(); bb != be; ++bb) {
04419 
04420     // Scan the BB and collect legal loads and stores.
04421     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
04422          ++it) {
04423 
04424       // If this is a load, save it. If this instruction can read from memory
04425       // but is not a load, then we quit. Notice that we don't handle function
04426       // calls that read or write.
04427       if (it->mayReadFromMemory()) {
04428         // Many math library functions read the rounding mode. We will only
04429         // vectorize a loop if it contains known function calls that don't set
04430         // the flag. Therefore, it is safe to ignore this read from memory.
04431         CallInst *Call = dyn_cast<CallInst>(it);
04432         if (Call && getIntrinsicIDForCall(Call, TLI))
04433           continue;
04434 
04435         LoadInst *Ld = dyn_cast<LoadInst>(it);
04436         if (!Ld) return false;
04437         if (!Ld->isSimple() && !IsAnnotatedParallel) {
04438           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
04439           return false;
04440         }
04441         NumLoads++;
04442         Loads.push_back(Ld);
04443         DepChecker.addAccess(Ld);
04444         continue;
04445       }
04446 
04447       // Save 'store' instructions. Abort if other instructions write to memory.
04448       if (it->mayWriteToMemory()) {
04449         StoreInst *St = dyn_cast<StoreInst>(it);
04450         if (!St) return false;
04451         if (!St->isSimple() && !IsAnnotatedParallel) {
04452           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
04453           return false;
04454         }
04455         NumStores++;
04456         Stores.push_back(St);
04457         DepChecker.addAccess(St);
04458       }
04459     } // Next instr.
04460   } // Next block.
04461 
04462   // Now we have two lists that hold the loads and the stores.
04463   // Next, we find the pointers that they use.
04464 
04465   // Check if we see any stores. If there are no stores, then we don't
04466   // care if the pointers are *restrict*.
04467   if (!Stores.size()) {
04468     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
04469     return true;
04470   }
04471 
04472   AccessAnalysis::DepCandidates DependentAccesses;
04473   AccessAnalysis Accesses(DL, DependentAccesses);
04474 
04475   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
04476   // multiple times on the same object. If the ptr is accessed twice, once
04477   // for read and once for write, it will only appear once (on the write
04478   // list). This is okay, since we are going to check for conflicts between
04479   // writes and between reads and writes, but not between reads and reads.
04480   ValueSet Seen;
04481 
04482   ValueVector::iterator I, IE;
04483   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
04484     StoreInst *ST = cast<StoreInst>(*I);
04485     Value* Ptr = ST->getPointerOperand();
04486 
04487     if (isUniform(Ptr)) {
04488       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
04489       return false;
04490     }
04491 
04492     // If we did *not* see this pointer before, insert it to  the read-write
04493     // list. At this phase it is only a 'write' list.
04494     if (Seen.insert(Ptr)) {
04495       ++NumReadWrites;
04496       Accesses.addStore(Ptr);
04497     }
04498   }
04499 
04500   if (IsAnnotatedParallel) {
04501     DEBUG(dbgs()
04502           << "LV: A loop annotated parallel, ignore memory dependency "
04503           << "checks.\n");
04504     return true;
04505   }
04506 
04507   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
04508     LoadInst *LD = cast<LoadInst>(*I);
04509     Value* Ptr = LD->getPointerOperand();
04510     // If we did *not* see this pointer before, insert it to the
04511     // read list. If we *did* see it before, then it is already in
04512     // the read-write list. This allows us to vectorize expressions
04513     // such as A[i] += x;  Because the address of A[i] is a read-write
04514     // pointer. This only works if the index of A[i] is consecutive.
04515     // If the address of i is unknown (for example A[B[i]]) then we may
04516     // read a few words, modify, and write a few words, and some of the
04517     // words may be written to the same address.
04518     bool IsReadOnlyPtr = false;
04519     if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
04520       ++NumReads;
04521       IsReadOnlyPtr = true;
04522     }
04523     Accesses.addLoad(Ptr, IsReadOnlyPtr);
04524   }
04525 
04526   // If we write (or read-write) to a single destination and there are no
04527   // other reads in this loop then is it safe to vectorize.
04528   if (NumReadWrites == 1 && NumReads == 0) {
04529     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
04530     return true;
04531   }
04532 
04533   // Build dependence sets and check whether we need a runtime pointer bounds
04534   // check.
04535   Accesses.buildDependenceSets();
04536   bool NeedRTCheck = Accesses.isRTCheckNeeded();
04537 
04538   // Find pointers with computable bounds. We are going to use this information
04539   // to place a runtime bound check.
04540   unsigned NumComparisons = 0;
04541   bool CanDoRT = false;
04542   if (NeedRTCheck)
04543     CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
04544                                        Strides);
04545 
04546   DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
04547         " pointer comparisons.\n");
04548 
04549   // If we only have one set of dependences to check pointers among we don't
04550   // need a runtime check.
04551   if (NumComparisons == 0 && NeedRTCheck)
04552     NeedRTCheck = false;
04553 
04554   // Check that we did not collect too many pointers or found an unsizeable
04555   // pointer.
04556   if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
04557     PtrRtCheck.reset();
04558     CanDoRT = false;
04559   }
04560 
04561   if (CanDoRT) {
04562     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
04563   }
04564 
04565   if (NeedRTCheck && !CanDoRT) {
04566     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
04567           "the array bounds.\n");
04568     PtrRtCheck.reset();
04569     return false;
04570   }
04571 
04572   PtrRtCheck.Need = NeedRTCheck;
04573 
04574   bool CanVecMem = true;
04575   if (Accesses.isDependencyCheckNeeded()) {
04576     DEBUG(dbgs() << "LV: Checking memory dependencies\n");
04577     CanVecMem = DepChecker.areDepsSafe(
04578         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
04579     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
04580 
04581     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
04582       DEBUG(dbgs() << "LV: Retrying with memory checks\n");
04583       NeedRTCheck = true;
04584 
04585       // Clear the dependency checks. We assume they are not needed.
04586       Accesses.resetDepChecks();
04587 
04588       PtrRtCheck.reset();
04589       PtrRtCheck.Need = true;
04590 
04591       CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
04592                                          TheLoop, Strides, true);
04593       // Check that we did not collect too many pointers or found an unsizeable
04594       // pointer.
04595       if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
04596         DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
04597         PtrRtCheck.reset();
04598         return false;
04599       }
04600 
04601       CanVecMem = true;
04602     }
04603   }
04604 
04605   DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
04606         " need a runtime memory check.\n");
04607 
04608   return CanVecMem;
04609 }
04610 
04611 static bool hasMultipleUsesOf(Instruction *I,
04612                               SmallPtrSet<Instruction *, 8> &Insts) {
04613   unsigned NumUses = 0;
04614   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
04615     if (Insts.count(dyn_cast<Instruction>(*Use)))
04616       ++NumUses;
04617     if (NumUses > 1)
04618       return true;
04619   }
04620 
04621   return false;
04622 }
04623 
04624 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
04625   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
04626     if (!Set.count(dyn_cast<Instruction>(*Use)))
04627       return false;
04628   return true;
04629 }
04630 
04631 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
04632                                                 ReductionKind Kind) {
04633   if (Phi->getNumIncomingValues() != 2)
04634     return false;
04635 
04636   // Reduction variables are only found in the loop header block.
04637   if (Phi->getParent() != TheLoop->getHeader())
04638     return false;
04639 
04640   // Obtain the reduction start value from the value that comes from the loop
04641   // preheader.
04642   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
04643 
04644   // ExitInstruction is the single value which is used outside the loop.
04645   // We only allow for a single reduction value to be used outside the loop.
04646   // This includes users of the reduction, variables (which form a cycle
04647   // which ends in the phi node).
04648   Instruction *ExitInstruction = 0;
04649   // Indicates that we found a reduction operation in our scan.
04650   bool FoundReduxOp = false;
04651 
04652   // We start with the PHI node and scan for all of the users of this
04653   // instruction. All users must be instructions that can be used as reduction
04654   // variables (such as ADD). We must have a single out-of-block user. The cycle
04655   // must include the original PHI.
04656   bool FoundStartPHI = false;
04657 
04658   // To recognize min/max patterns formed by a icmp select sequence, we store
04659   // the number of instruction we saw from the recognized min/max pattern,
04660   //  to make sure we only see exactly the two instructions.
04661   unsigned NumCmpSelectPatternInst = 0;
04662   ReductionInstDesc ReduxDesc(false, 0);
04663 
04664   SmallPtrSet<Instruction *, 8> VisitedInsts;
04665   SmallVector<Instruction *, 8> Worklist;
04666   Worklist.push_back(Phi);
04667   VisitedInsts.insert(Phi);
04668 
04669   // A value in the reduction can be used:
04670   //  - By the reduction:
04671   //      - Reduction operation:
04672   //        - One use of reduction value (safe).
04673   //        - Multiple use of reduction value (not safe).
04674   //      - PHI:
04675   //        - All uses of the PHI must be the reduction (safe).
04676   //        - Otherwise, not safe.
04677   //  - By one instruction outside of the loop (safe).
04678   //  - By further instructions outside of the loop (not safe).
04679   //  - By an instruction that is not part of the reduction (not safe).
04680   //    This is either:
04681   //      * An instruction type other than PHI or the reduction operation.
04682   //      * A PHI in the header other than the initial PHI.
04683   while (!Worklist.empty()) {
04684     Instruction *Cur = Worklist.back();
04685     Worklist.pop_back();
04686 
04687     // No Users.
04688     // If the instruction has no users then this is a broken chain and can't be
04689     // a reduction variable.
04690     if (Cur->use_empty())
04691       return false;
04692 
04693     bool IsAPhi = isa<PHINode>(Cur);
04694 
04695     // A header PHI use other than the original PHI.
04696     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
04697       return false;
04698 
04699     // Reductions of instructions such as Div, and Sub is only possible if the
04700     // LHS is the reduction variable.
04701     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
04702         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
04703         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
04704       return false;
04705 
04706     // Any reduction instruction must be of one of the allowed kinds.
04707     ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
04708     if (!ReduxDesc.IsReduction)
04709       return false;
04710 
04711     // A reduction operation must only have one use of the reduction value.
04712     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
04713         hasMultipleUsesOf(Cur, VisitedInsts))
04714       return false;
04715 
04716     // All inputs to a PHI node must be a reduction value.
04717     if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
04718       return false;
04719 
04720     if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
04721                                      isa<SelectInst>(Cur)))
04722       ++NumCmpSelectPatternInst;
04723     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
04724                                    isa<SelectInst>(Cur)))
04725       ++NumCmpSelectPatternInst;
04726 
04727     // Check  whether we found a reduction operator.
04728     FoundReduxOp |= !IsAPhi;
04729 
04730     // Process users of current instruction. Push non-PHI nodes after PHI nodes
04731     // onto the stack. This way we are going to have seen all inputs to PHI
04732     // nodes once we get to them.
04733     SmallVector<Instruction *, 8> NonPHIs;
04734     SmallVector<Instruction *, 8> PHIs;
04735     for (User *U : Cur->users()) {
04736       Instruction *UI = cast<Instruction>(U);
04737 
04738       // Check if we found the exit user.
04739       BasicBlock *Parent = UI->getParent();
04740       if (!TheLoop->contains(Parent)) {
04741         // Exit if you find multiple outside users or if the header phi node is
04742         // being used. In this case the user uses the value of the previous
04743         // iteration, in which case we would loose "VF-1" iterations of the
04744         // reduction operation if we vectorize.
04745         if (ExitInstruction != 0 || Cur == Phi)
04746           return false;
04747 
04748         // The instruction used by an outside user must be the last instruction
04749         // before we feed back to the reduction phi. Otherwise, we loose VF-1
04750         // operations on the value.
04751         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
04752          return false;
04753 
04754         ExitInstruction = Cur;
04755         continue;
04756       }
04757 
04758       // Process instructions only once (termination). Each reduction cycle
04759       // value must only be used once, except by phi nodes and min/max
04760       // reductions which are represented as a cmp followed by a select.
04761       ReductionInstDesc IgnoredVal(false, 0);
04762       if (VisitedInsts.insert(UI)) {
04763         if (isa<PHINode>(UI))
04764           PHIs.push_back(UI);
04765         else
04766           NonPHIs.push_back(UI);
04767       } else if (!isa<PHINode>(UI) &&
04768                  ((!isa<FCmpInst>(UI) &&
04769                    !isa<ICmpInst>(UI) &&
04770                    !isa<SelectInst>(UI)) ||
04771                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
04772         return false;
04773 
04774       // Remember that we completed the cycle.
04775       if (UI == Phi)
04776         FoundStartPHI = true;
04777     }
04778     Worklist.append(PHIs.begin(), PHIs.end());
04779     Worklist.append(NonPHIs.begin(), NonPHIs.end());
04780   }
04781 
04782   // This means we have seen one but not the other instruction of the
04783   // pattern or more than just a select and cmp.
04784   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
04785       NumCmpSelectPatternInst != 2)
04786     return false;
04787 
04788   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
04789     return false;
04790 
04791   // We found a reduction var if we have reached the original phi node and we
04792   // only have a single instruction with out-of-loop users.
04793 
04794   // This instruction is allowed to have out-of-loop users.
04795   AllowedExit.insert(ExitInstruction);
04796 
04797   // Save the description of this reduction variable.
04798   ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
04799                          ReduxDesc.MinMaxKind);
04800   Reductions[Phi] = RD;
04801   // We've ended the cycle. This is a reduction variable if we have an
04802   // outside user and it has a binary op.
04803 
04804   return true;
04805 }
04806 
04807 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
04808 /// pattern corresponding to a min(X, Y) or max(X, Y).
04809 LoopVectorizationLegality::ReductionInstDesc
04810 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
04811                                                     ReductionInstDesc &Prev) {
04812 
04813   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
04814          "Expect a select instruction");
04815   Instruction *Cmp = 0;
04816   SelectInst *Select = 0;
04817 
04818   // We must handle the select(cmp()) as a single instruction. Advance to the
04819   // select.
04820   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
04821     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
04822       return ReductionInstDesc(false, I);
04823     return ReductionInstDesc(Select, Prev.MinMaxKind);
04824   }
04825 
04826   // Only handle single use cases for now.
04827   if (!(Select = dyn_cast<SelectInst>(I)))
04828     return ReductionInstDesc(false, I);
04829   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
04830       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
04831     return ReductionInstDesc(false, I);
04832   if (!Cmp->hasOneUse())
04833     return ReductionInstDesc(false, I);
04834 
04835   Value *CmpLeft;
04836   Value *CmpRight;
04837 
04838   // Look for a min/max pattern.
04839   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
04840     return ReductionInstDesc(Select, MRK_UIntMin);
04841   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
04842     return ReductionInstDesc(Select, MRK_UIntMax);
04843   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
04844     return ReductionInstDesc(Select, MRK_SIntMax);
04845   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
04846     return ReductionInstDesc(Select, MRK_SIntMin);
04847   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
04848     return ReductionInstDesc(Select, MRK_FloatMin);
04849   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
04850     return ReductionInstDesc(Select, MRK_FloatMax);
04851   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
04852     return ReductionInstDesc(Select, MRK_FloatMin);
04853   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
04854     return ReductionInstDesc(Select, MRK_FloatMax);
04855 
04856   return ReductionInstDesc(false, I);
04857 }
04858 
04859 LoopVectorizationLegality::ReductionInstDesc
04860 LoopVectorizationLegality::isReductionInstr(Instruction *I,
04861                                             ReductionKind Kind,
04862                                             ReductionInstDesc &Prev) {
04863   bool FP = I->getType()->isFloatingPointTy();
04864   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
04865   switch (I->getOpcode()) {
04866   default:
04867     return ReductionInstDesc(false, I);
04868   case Instruction::PHI:
04869       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
04870                  Kind != RK_FloatMinMax))
04871         return ReductionInstDesc(false, I);
04872     return ReductionInstDesc(I, Prev.MinMaxKind);
04873   case Instruction::Sub:
04874   case Instruction::Add:
04875     return ReductionInstDesc(Kind == RK_IntegerAdd, I);
04876   case Instruction::Mul:
04877     return ReductionInstDesc(Kind == RK_IntegerMult, I);
04878   case Instruction::And:
04879     return ReductionInstDesc(Kind == RK_IntegerAnd, I);
04880   case Instruction::Or:
04881     return ReductionInstDesc(Kind == RK_IntegerOr, I);
04882   case Instruction::Xor:
04883     return ReductionInstDesc(Kind == RK_IntegerXor, I);
04884   case Instruction::FMul:
04885     return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
04886   case Instruction::FAdd:
04887     return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
04888   case Instruction::FCmp:
04889   case Instruction::ICmp:
04890   case Instruction::Select:
04891     if (Kind != RK_IntegerMinMax &&
04892         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
04893       return ReductionInstDesc(false, I);
04894     return isMinMaxSelectCmpPattern(I, Prev);
04895   }
04896 }
04897 
04898 LoopVectorizationLegality::InductionKind
04899 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
04900   Type *PhiTy = Phi->getType();
04901   // We only handle integer and pointer inductions variables.
04902   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
04903     return IK_NoInduction;
04904 
04905   // Check that the PHI is consecutive.
04906   const SCEV *PhiScev = SE->getSCEV(Phi);
04907   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
04908   if (!AR) {
04909     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
04910     return IK_NoInduction;
04911   }
04912   const SCEV *Step = AR->getStepRecurrence(*SE);
04913 
04914   // Integer inductions need to have a stride of one.
04915   if (PhiTy->isIntegerTy()) {
04916     if (Step->isOne())
04917       return IK_IntInduction;
04918     if (Step->isAllOnesValue())
04919       return IK_ReverseIntInduction;
04920     return IK_NoInduction;
04921   }
04922 
04923   // Calculate the pointer stride and check if it is consecutive.
04924   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
04925   if (!C)
04926     return IK_NoInduction;
04927 
04928   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
04929   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
04930   if (C->getValue()->equalsInt(Size))
04931     return IK_PtrInduction;
04932   else if (C->getValue()->equalsInt(0 - Size))
04933     return IK_ReversePtrInduction;
04934 
04935   return IK_NoInduction;
04936 }
04937 
04938 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
04939   Value *In0 = const_cast<Value*>(V);
04940   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
04941   if (!PN)
04942     return false;
04943 
04944   return Inductions.count(PN);
04945 }
04946 
04947 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
04948   assert(TheLoop->contains(BB) && "Unknown block used");
04949 
04950   // Blocks that do not dominate the latch need predication.
04951   BasicBlock* Latch = TheLoop->getLoopLatch();
04952   return !DT->dominates(BB, Latch);
04953 }
04954 
04955 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
04956                                             SmallPtrSet<Value *, 8>& SafePtrs) {
04957   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
04958     // We might be able to hoist the load.
04959     if (it->mayReadFromMemory()) {
04960       LoadInst *LI = dyn_cast<LoadInst>(it);
04961       if (!LI || !SafePtrs.count(LI->getPointerOperand()))
04962         return false;
04963     }
04964 
04965     // We don't predicate stores at the moment.
04966     if (it->mayWriteToMemory()) {
04967       StoreInst *SI = dyn_cast<StoreInst>(it);
04968       // We only support predication of stores in basic blocks with one
04969       // predecessor.
04970       if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
04971           !SafePtrs.count(SI->getPointerOperand()) ||
04972           !SI->getParent()->getSinglePredecessor())
04973         return false;
04974     }
04975     if (it->mayThrow())
04976       return false;
04977 
04978     // Check that we don't have a constant expression that can trap as operand.
04979     for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
04980          OI != OE; ++OI) {
04981       if (Constant *C = dyn_cast<Constant>(*OI))
04982         if (C->canTrap())
04983           return false;
04984     }
04985 
04986     // The instructions below can trap.
04987     switch (it->getOpcode()) {
04988     default: continue;
04989     case Instruction::UDiv:
04990     case Instruction::SDiv:
04991     case Instruction::URem:
04992     case Instruction::SRem:
04993              return false;
04994     }
04995   }
04996 
04997   return true;
04998 }
04999 
05000 LoopVectorizationCostModel::VectorizationFactor
05001 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
05002                                                       unsigned UserVF) {
05003   // Width 1 means no vectorize
05004   VectorizationFactor Factor = { 1U, 0U };
05005   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
05006     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
05007     return Factor;
05008   }
05009 
05010   if (!EnableCondStoresVectorization && Legal->NumPredStores) {
05011     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
05012     return Factor;
05013   }
05014 
05015   // Find the trip count.
05016   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
05017   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
05018 
05019   unsigned WidestType = getWidestType();
05020   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
05021   unsigned MaxSafeDepDist = -1U;
05022   if (Legal->getMaxSafeDepDistBytes() != -1U)
05023     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
05024   WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
05025                     WidestRegister : MaxSafeDepDist);
05026   unsigned MaxVectorSize = WidestRegister / WidestType;
05027   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
05028   DEBUG(dbgs() << "LV: The Widest register is: "
05029           << WidestRegister << " bits.\n");
05030 
05031   if (MaxVectorSize == 0) {
05032     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
05033     MaxVectorSize = 1;
05034   }
05035 
05036   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
05037          " into one vector!");
05038 
05039   unsigned VF = MaxVectorSize;
05040 
05041   // If we optimize the program for size, avoid creating the tail loop.
05042   if (OptForSize) {
05043     // If we are unable to calculate the trip count then don't try to vectorize.
05044     if (TC < 2) {
05045       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
05046       return Factor;
05047     }
05048 
05049     // Find the maximum SIMD width that can fit within the trip count.
05050     VF = TC % MaxVectorSize;
05051 
05052     if (VF == 0)
05053       VF = MaxVectorSize;
05054 
05055     // If the trip count that we found modulo the vectorization factor is not
05056     // zero then we require a tail.
05057     if (VF < 2) {
05058       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
05059       return Factor;
05060     }
05061   }
05062 
05063   if (UserVF != 0) {
05064     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
05065     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
05066 
05067     Factor.Width = UserVF;
05068     return Factor;
05069   }
05070 
05071   float Cost = expectedCost(1);
05072   unsigned Width = 1;
05073   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n");
05074   for (unsigned i=2; i <= VF; i*=2) {
05075     // Notice that the vector loop needs to be executed less times, so
05076     // we need to divide the cost of the vector loops by the width of
05077     // the vector elements.
05078     float VectorCost = expectedCost(i) / (float)i;
05079     DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
05080           (int)VectorCost << ".\n");
05081     if (VectorCost < Cost) {
05082       Cost = VectorCost;
05083       Width = i;
05084     }
05085   }
05086 
05087   DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
05088   Factor.Width = Width;
05089   Factor.Cost = Width * Cost;
05090   return Factor;
05091 }
05092 
05093 unsigned LoopVectorizationCostModel::getWidestType() {
05094   unsigned MaxWidth = 8;
05095 
05096   // For each block.
05097   for (Loop::block_iterator bb = TheLoop->block_begin(),
05098        be = TheLoop->block_end(); bb != be; ++bb) {
05099     BasicBlock *BB = *bb;
05100 
05101     // For each instruction in the loop.
05102     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
05103       Type *T = it->getType();
05104 
05105       // Only examine Loads, Stores and PHINodes.
05106       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
05107         continue;
05108 
05109       // Examine PHI nodes that are reduction variables.
05110       if (PHINode *PN = dyn_cast<PHINode>(it))
05111         if (!Legal->getReductionVars()->count(PN))
05112           continue;
05113 
05114       // Examine the stored values.
05115       if (StoreInst *ST = dyn_cast<StoreInst>(it))
05116         T = ST->getValueOperand()->getType();
05117 
05118       // Ignore loaded pointer types and stored pointer types that are not
05119       // consecutive. However, we do want to take consecutive stores/loads of
05120       // pointer vectors into account.
05121       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
05122         continue;
05123 
05124       MaxWidth = std::max(MaxWidth,
05125                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
05126     }
05127   }
05128 
05129   return MaxWidth;
05130 }
05131 
05132 unsigned
05133 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
05134                                                unsigned UserUF,
05135                                                unsigned VF,
05136                                                unsigned LoopCost) {
05137 
05138   // -- The unroll heuristics --
05139   // We unroll the loop in order to expose ILP and reduce the loop overhead.
05140   // There are many micro-architectural considerations that we can't predict
05141   // at this level. For example frontend pressure (on decode or fetch) due to
05142   // code size, or the number and capabilities of the execution ports.
05143   //
05144   // We use the following heuristics to select the unroll factor:
05145   // 1. If the code has reductions the we unroll in order to break the cross
05146   // iteration dependency.
05147   // 2. If the loop is really small then we unroll in order to reduce the loop
05148   // overhead.
05149   // 3. We don't unroll if we think that we will spill registers to memory due
05150   // to the increased register pressure.
05151 
05152   // Use the user preference, unless 'auto' is selected.
05153   if (UserUF != 0)
05154     return UserUF;
05155 
05156   // When we optimize for size we don't unroll.
05157   if (OptForSize)
05158     return 1;
05159 
05160   // We used the distance for the unroll factor.
05161   if (Legal->getMaxSafeDepDistBytes() != -1U)
05162     return 1;
05163 
05164   // Do not unroll loops with a relatively small trip count.
05165   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
05166                                               TheLoop->getLoopLatch());
05167   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
05168     return 1;
05169 
05170   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
05171   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
05172         " registers\n");
05173 
05174   if (VF == 1) {
05175     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
05176       TargetNumRegisters = ForceTargetNumScalarRegs;
05177   } else {
05178     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
05179       TargetNumRegisters = ForceTargetNumVectorRegs;
05180   }
05181 
05182   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
05183   // We divide by these constants so assume that we have at least one
05184   // instruction that uses at least one register.
05185   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
05186   R.NumInstructions = std::max(R.NumInstructions, 1U);
05187 
05188   // We calculate the unroll factor using the following formula.
05189   // Subtract the number of loop invariants from the number of available
05190   // registers. These registers are used by all of the unrolled instances.
05191   // Next, divide the remaining registers by the number of registers that is
05192   // required by the loop, in order to estimate how many parallel instances
05193   // fit without causing spills. All of this is rounded down if necessary to be
05194   // a power of two. We want power of two unroll factors to simplify any
05195   // addressing operations or alignment considerations.
05196   unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
05197                               R.MaxLocalUsers);
05198 
05199   // Don't count the induction variable as unrolled.
05200   if (EnableIndVarRegisterHeur)
05201     UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
05202                        std::max(1U, (R.MaxLocalUsers - 1)));
05203 
05204   // Clamp the unroll factor ranges to reasonable factors.
05205   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
05206 
05207   // Check if the user has overridden the unroll max.
05208   if (VF == 1) {
05209     if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
05210       MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
05211   } else {
05212     if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
05213       MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
05214   }
05215 
05216   // If we did not calculate the cost for VF (because the user selected the VF)
05217   // then we calculate the cost of VF here.
05218   if (LoopCost == 0)
05219     LoopCost = expectedCost(VF);
05220 
05221   // Clamp the calculated UF to be between the 1 and the max unroll factor
05222   // that the target allows.
05223   if (UF > MaxUnrollSize)
05224     UF = MaxUnrollSize;
05225   else if (UF < 1)
05226     UF = 1;
05227 
05228   // Unroll if we vectorized this loop and there is a reduction that could
05229   // benefit from unrolling.
05230   if (VF > 1 && Legal->getReductionVars()->size()) {
05231     DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
05232     return UF;
05233   }
05234 
05235   // Note that if we've already vectorized the loop we will have done the
05236   // runtime check and so unrolling won't require further checks.
05237   bool UnrollingRequiresRuntimePointerCheck =
05238       (VF == 1 && Legal->getRuntimePointerCheck()->Need);
05239 
05240   // We want to unroll small loops in order to reduce the loop overhead and
05241   // potentially expose ILP opportunities.
05242   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
05243   if (!UnrollingRequiresRuntimePointerCheck &&
05244       LoopCost < SmallLoopCost) {
05245     // We assume that the cost overhead is 1 and we use the cost model
05246     // to estimate the cost of the loop and unroll until the cost of the
05247     // loop overhead is about 5% of the cost of the loop.
05248     unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
05249 
05250     // Unroll until store/load ports (estimated by max unroll factor) are
05251     // saturated.
05252     unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
05253     unsigned LoadsUF = UF /  (Legal->NumLoads ? Legal->NumLoads : 1);
05254 
05255     if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
05256       DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
05257       return std::max(StoresUF, LoadsUF);
05258     }
05259 
05260     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
05261     return SmallUF;
05262   }
05263 
05264   DEBUG(dbgs() << "LV: Not Unrolling.\n");
05265   return 1;
05266 }
05267 
05268 LoopVectorizationCostModel::RegisterUsage
05269 LoopVectorizationCostModel::calculateRegisterUsage() {
05270   // This function calculates the register usage by measuring the highest number
05271   // of values that are alive at a single location. Obviously, this is a very
05272   // rough estimation. We scan the loop in a topological order in order and
05273   // assign a number to each instruction. We use RPO to ensure that defs are
05274   // met before their users. We assume that each instruction that has in-loop
05275   // users starts an interval. We record every time that an in-loop value is
05276   // used, so we have a list of the first and last occurrences of each
05277   // instruction. Next, we transpose this data structure into a multi map that
05278   // holds the list of intervals that *end* at a specific location. This multi
05279   // map allows us to perform a linear search. We scan the instructions linearly
05280   // and record each time that a new interval starts, by placing it in a set.
05281   // If we find this value in the multi-map then we remove it from the set.
05282   // The max register usage is the maximum size of the set.
05283   // We also search for instructions that are defined outside the loop, but are
05284   // used inside the loop. We need this number separately from the max-interval
05285   // usage number because when we unroll, loop-invariant values do not take
05286   // more register.
05287   LoopBlocksDFS DFS(TheLoop);
05288   DFS.perform(LI);
05289 
05290   RegisterUsage R;
05291   R.NumInstructions = 0;
05292 
05293   // Each 'key' in the map opens a new interval. The values
05294   // of the map are the index of the 'last seen' usage of the
05295   // instruction that is the key.
05296   typedef DenseMap<Instruction*, unsigned> IntervalMap;
05297   // Maps instruction to its index.
05298   DenseMap<unsigned, Instruction*> IdxToInstr;
05299   // Marks the end of each interval.
05300   IntervalMap EndPoint;
05301   // Saves the list of instruction indices that are used in the loop.
05302   SmallSet<Instruction*, 8> Ends;
05303   // Saves the list of values that are used in the loop but are
05304   // defined outside the loop, such as arguments and constants.
05305   SmallPtrSet<Value*, 8> LoopInvariants;
05306 
05307   unsigned Index = 0;
05308   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
05309        be = DFS.endRPO(); bb != be; ++bb) {
05310     R.NumInstructions += (*bb)->size();
05311     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
05312          ++it) {
05313       Instruction *I = it;
05314       IdxToInstr[Index++] = I;
05315 
05316       // Save the end location of each USE.
05317       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
05318         Value *U = I->getOperand(i);
05319         Instruction *Instr = dyn_cast<Instruction>(U);
05320 
05321         // Ignore non-instruction values such as arguments, constants, etc.
05322         if (!Instr) continue;
05323 
05324         // If this instruction is outside the loop then record it and continue.
05325         if (!TheLoop->contains(Instr)) {
05326           LoopInvariants.insert(Instr);
05327           continue;
05328         }
05329 
05330         // Overwrite previous end points.
05331         EndPoint[Instr] = Index;
05332         Ends.insert(Instr);
05333       }
05334     }
05335   }
05336 
05337   // Saves the list of intervals that end with the index in 'key'.
05338   typedef SmallVector<Instruction*, 2> InstrList;
05339   DenseMap<unsigned, InstrList> TransposeEnds;
05340 
05341   // Transpose the EndPoints to a list of values that end at each index.
05342   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
05343        it != e; ++it)
05344     TransposeEnds[it->second].push_back(it->first);
05345 
05346   SmallSet<Instruction*, 8> OpenIntervals;
05347   unsigned MaxUsage = 0;
05348 
05349 
05350   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
05351   for (unsigned int i = 0; i < Index; ++i) {
05352     Instruction *I = IdxToInstr[i];
05353     // Ignore instructions that are never used within the loop.
05354     if (!Ends.count(I)) continue;
05355 
05356     // Remove all of the instructions that end at this location.
05357     InstrList &List = TransposeEnds[i];
05358     for (unsigned int j=0, e = List.size(); j < e; ++j)
05359       OpenIntervals.erase(List[j]);
05360 
05361     // Count the number of live interals.
05362     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
05363 
05364     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
05365           OpenIntervals.size() << '\n');
05366 
05367     // Add the current instruction to the list of open intervals.
05368     OpenIntervals.insert(I);
05369   }
05370 
05371   unsigned Invariant = LoopInvariants.size();
05372   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
05373   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
05374   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
05375 
05376   R.LoopInvariantRegs = Invariant;
05377   R.MaxLocalUsers = MaxUsage;
05378   return R;
05379 }
05380 
05381 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
05382   unsigned Cost = 0;
05383 
05384   // For each block.
05385   for (Loop::block_iterator bb = TheLoop->block_begin(),
05386        be = TheLoop->block_end(); bb != be; ++bb) {
05387     unsigned BlockCost = 0;
05388     BasicBlock *BB = *bb;
05389 
05390     // For each instruction in the old loop.
05391     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
05392       // Skip dbg intrinsics.
05393       if (isa<DbgInfoIntrinsic>(it))
05394         continue;
05395 
05396       unsigned C = getInstructionCost(it, VF);
05397 
05398       // Check if we should override the cost.
05399       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
05400         C = ForceTargetInstructionCost;
05401 
05402       BlockCost += C;
05403       DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
05404             VF << " For instruction: " << *it << '\n');
05405     }
05406 
05407     // We assume that if-converted blocks have a 50% chance of being executed.
05408     // When the code is scalar then some of the blocks are avoided due to CF.
05409     // When the code is vectorized we execute all code paths.
05410     if (VF == 1 && Legal->blockNeedsPredication(*bb))
05411       BlockCost /= 2;
05412 
05413     Cost += BlockCost;
05414   }
05415 
05416   return Cost;
05417 }
05418 
05419 /// \brief Check whether the address computation for a non-consecutive memory
05420 /// access looks like an unlikely candidate for being merged into the indexing
05421 /// mode.
05422 ///
05423 /// We look for a GEP which has one index that is an induction variable and all
05424 /// other indices are loop invariant. If the stride of this access is also
05425 /// within a small bound we decide that this address computation can likely be
05426 /// merged into the addressing mode.
05427 /// In all other cases, we identify the address computation as complex.
05428 static bool isLikelyComplexAddressComputation(Value *Ptr,
05429                                               LoopVectorizationLegality *Legal,
05430                                               ScalarEvolution *SE,
05431                                               const Loop *TheLoop) {
05432   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
05433   if (!Gep)
05434     return true;
05435 
05436   // We are looking for a gep with all loop invariant indices except for one
05437   // which should be an induction variable.
05438   unsigned NumOperands = Gep->getNumOperands();
05439   for (unsigned i = 1; i < NumOperands; ++i) {
05440     Value *Opd = Gep->getOperand(i);
05441     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
05442         !Legal->isInductionVariable(Opd))
05443       return true;
05444   }
05445 
05446   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
05447   // can likely be merged into the address computation.
05448   unsigned MaxMergeDistance = 64;
05449 
05450   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
05451   if (!AddRec)
05452     return true;
05453 
05454   // Check the step is constant.
05455   const SCEV *Step = AddRec->getStepRecurrence(*SE);
05456   // Calculate the pointer stride and check if it is consecutive.
05457   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
05458   if (!C)
05459     return true;
05460 
05461   const APInt &APStepVal = C->getValue()->getValue();
05462 
05463   // Huge step value - give up.
05464   if (APStepVal.getBitWidth() > 64)
05465     return true;
05466 
05467   int64_t StepVal = APStepVal.getSExtValue();
05468 
05469   return StepVal > MaxMergeDistance;
05470 }
05471 
05472 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
05473   if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
05474     return true;
05475   return false;
05476 }
05477 
05478 unsigned
05479 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
05480   // If we know that this instruction will remain uniform, check the cost of
05481   // the scalar version.
05482   if (Legal->isUniformAfterVectorization(I))
05483     VF = 1;
05484 
05485   Type *RetTy = I->getType();
05486   Type *VectorTy = ToVectorTy(RetTy, VF);
05487 
05488   // TODO: We need to estimate the cost of intrinsic calls.
05489   switch (I->getOpcode()) {
05490   case Instruction::GetElementPtr:
05491     // We mark this instruction as zero-cost because the cost of GEPs in
05492     // vectorized code depends on whether the corresponding memory instruction
05493     // is scalarized or not. Therefore, we handle GEPs with the memory
05494     // instruction cost.
05495     return 0;
05496   case Instruction::Br: {
05497     return TTI.getCFInstrCost(I->getOpcode());
05498   }
05499   case Instruction::PHI:
05500     //TODO: IF-converted IFs become selects.
05501     return 0;
05502   case Instruction::Add:
05503   case Instruction::FAdd:
05504   case Instruction::Sub:
05505   case Instruction::FSub:
05506   case Instruction::Mul:
05507   case Instruction::FMul:
05508   case Instruction::UDiv:
05509   case Instruction::SDiv:
05510   case Instruction::FDiv:
05511   case Instruction::URem:
05512   case Instruction::SRem:
05513   case Instruction::FRem:
05514   case Instruction::Shl:
05515   case Instruction::LShr:
05516   case Instruction::AShr:
05517   case Instruction::And:
05518   case Instruction::Or:
05519   case Instruction::Xor: {
05520     // Since we will replace the stride by 1 the multiplication should go away.
05521     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
05522       return 0;
05523     // Certain instructions can be cheaper to vectorize if they have a constant
05524     // second vector operand. One example of this are shifts on x86.
05525     TargetTransformInfo::OperandValueKind Op1VK =
05526       TargetTransformInfo::OK_AnyValue;
05527     TargetTransformInfo::OperandValueKind Op2VK =
05528       TargetTransformInfo::OK_AnyValue;
05529     Value *Op2 = I->getOperand(1);
05530 
05531     // Check for a splat of a constant or for a non uniform vector of constants.
05532     if (isa<ConstantInt>(Op2))
05533       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
05534     else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
05535       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
05536       if (cast<Constant>(Op2)->getSplatValue() != NULL)
05537         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
05538     }
05539 
05540     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
05541   }
05542   case Instruction::Select: {
05543     SelectInst *SI = cast<SelectInst>(I);
05544     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
05545     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
05546     Type *CondTy = SI->getCondition()->getType();
05547     if (!ScalarCond)
05548       CondTy = VectorType::get(CondTy, VF);
05549 
05550     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
05551   }
05552   case Instruction::ICmp:
05553   case Instruction::FCmp: {
05554     Type *ValTy = I->getOperand(0)->getType();
05555     VectorTy = ToVectorTy(ValTy, VF);
05556     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
05557   }
05558   case Instruction::Store:
05559   case Instruction::Load: {
05560     StoreInst *SI = dyn_cast<StoreInst>(I);
05561     LoadInst *LI = dyn_cast<LoadInst>(I);
05562     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
05563                    LI->getType());
05564     VectorTy = ToVectorTy(ValTy, VF);
05565 
05566     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
05567     unsigned AS = SI ? SI->getPointerAddressSpace() :
05568       LI->getPointerAddressSpace();
05569     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
05570     // We add the cost of address computation here instead of with the gep
05571     // instruction because only here we know whether the operation is
05572     // scalarized.
05573     if (VF == 1)
05574       return TTI.getAddressComputationCost(VectorTy) +
05575         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
05576 
05577     // Scalarized loads/stores.
05578     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
05579     bool Reverse = ConsecutiveStride < 0;
05580     unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
05581     unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
05582     if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
05583       bool IsComplexComputation =
05584         isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
05585       unsigned Cost = 0;
05586       // The cost of extracting from the value vector and pointer vector.
05587       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
05588       for (unsigned i = 0; i < VF; ++i) {
05589         //  The cost of extracting the pointer operand.
05590         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
05591         // In case of STORE, the cost of ExtractElement from the vector.
05592         // In case of LOAD, the cost of InsertElement into the returned
05593         // vector.
05594         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
05595                                             Instruction::InsertElement,
05596                                             VectorTy, i);
05597       }
05598 
05599       // The cost of the scalar loads/stores.
05600       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
05601       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
05602                                        Alignment, AS);
05603       return Cost;
05604     }
05605 
05606     // Wide load/stores.
05607     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
05608     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
05609 
05610     if (Reverse)
05611       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
05612                                   VectorTy, 0);
05613     return Cost;
05614   }
05615   case Instruction::ZExt:
05616   case Instruction::SExt:
05617   case Instruction::FPToUI:
05618   case Instruction::FPToSI:
05619   case Instruction::FPExt:
05620   case Instruction::PtrToInt:
05621   case Instruction::IntToPtr:
05622   case Instruction::SIToFP:
05623   case Instruction::UIToFP:
05624   case Instruction::Trunc:
05625   case Instruction::FPTrunc:
05626   case Instruction::BitCast: {
05627     // We optimize the truncation of induction variable.
05628     // The cost of these is the same as the scalar operation.
05629     if (I->getOpcode() == Instruction::Trunc &&
05630         Legal->isInductionVariable(I->getOperand(0)))
05631       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
05632                                   I->getOperand(0)->getType());
05633 
05634     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
05635     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
05636   }
05637   case Instruction::Call: {
05638     CallInst *CI = cast<CallInst>(I);
05639     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
05640     assert(ID && "Not an intrinsic call!");
05641     Type *RetTy = ToVectorTy(CI->getType(), VF);
05642     SmallVector<Type*, 4> Tys;
05643     for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
05644       Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
05645     return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
05646   }
05647   default: {
05648     // We are scalarizing the instruction. Return the cost of the scalar
05649     // instruction, plus the cost of insert and extract into vector
05650     // elements, times the vector width.
05651     unsigned Cost = 0;
05652 
05653     if (!RetTy->isVoidTy() && VF != 1) {
05654       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
05655                                                 VectorTy);
05656       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
05657                                                 VectorTy);
05658 
05659       // The cost of inserting the results plus extracting each one of the
05660       // operands.
05661       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
05662     }
05663 
05664     // The cost of executing VF copies of the scalar instruction. This opcode
05665     // is unknown. Assume that it is the same as 'mul'.
05666     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
05667     return Cost;
05668   }
05669   }// end of switch.
05670 }
05671 
05672 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
05673   if (Scalar->isVoidTy() || VF == 1)
05674     return Scalar;
05675   return VectorType::get(Scalar, VF);
05676 }
05677 
05678 char LoopVectorize::ID = 0;
05679 static const char lv_name[] = "Loop Vectorization";
05680 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
05681 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
05682 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
05683 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
05684 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
05685 INITIALIZE_PASS_DEPENDENCY(LCSSA)
05686 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
05687 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
05688 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
05689 
05690 namespace llvm {
05691   Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
05692     return new LoopVectorize(NoUnrolling, AlwaysVectorize);
05693   }
05694 }
05695 
05696 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
05697   // Check for a store.
05698   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
05699     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
05700 
05701   // Check for a load.
05702   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
05703     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
05704 
05705   return false;
05706 }
05707 
05708 
05709 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
05710                                              bool IfPredicateStore) {
05711   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
05712   // Holds vector parameters or scalars, in case of uniform vals.
05713   SmallVector<VectorParts, 4> Params;
05714 
05715   setDebugLocFromInst(Builder, Instr);
05716 
05717   // Find all of the vectorized parameters.
05718   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
05719     Value *SrcOp = Instr->getOperand(op);
05720 
05721     // If we are accessing the old induction variable, use the new one.
05722     if (SrcOp == OldInduction) {
05723       Params.push_back(getVectorValue(SrcOp));
05724       continue;
05725     }
05726 
05727     // Try using previously calculated values.
05728     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
05729 
05730     // If the src is an instruction that appeared earlier in the basic block
05731     // then it should already be vectorized.
05732     if (SrcInst && OrigLoop->contains(SrcInst)) {
05733       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
05734       // The parameter is a vector value from earlier.
05735       Params.push_back(WidenMap.get(SrcInst));
05736     } else {
05737       // The parameter is a scalar from outside the loop. Maybe even a constant.
05738       VectorParts Scalars;
05739       Scalars.append(UF, SrcOp);
05740       Params.push_back(Scalars);
05741     }
05742   }
05743 
05744   assert(Params.size() == Instr->getNumOperands() &&
05745          "Invalid number of operands");
05746 
05747   // Does this instruction return a value ?
05748   bool IsVoidRetTy = Instr->getType()->isVoidTy();
05749 
05750   Value *UndefVec = IsVoidRetTy ? 0 :
05751   UndefValue::get(Instr->getType());
05752   // Create a new entry in the WidenMap and initialize it to Undef or Null.
05753   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
05754 
05755   Instruction *InsertPt = Builder.GetInsertPoint();
05756   BasicBlock *IfBlock = Builder.GetInsertBlock();
05757   BasicBlock *CondBlock = 0;
05758 
05759   VectorParts Cond;
05760   Loop *VectorLp = 0;
05761   if (IfPredicateStore) {
05762     assert(Instr->getParent()->getSinglePredecessor() &&
05763            "Only support single predecessor blocks");
05764     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
05765                           Instr->getParent());
05766     VectorLp = LI->getLoopFor(IfBlock);
05767     assert(VectorLp && "Must have a loop for this block");
05768   }
05769 
05770   // For each vector unroll 'part':
05771   for (unsigned Part = 0; Part < UF; ++Part) {
05772     // For each scalar that we create:
05773 
05774     // Start an "if (pred) a[i] = ..." block.
05775     Value *Cmp = 0;
05776     if (IfPredicateStore) {
05777       if (Cond[Part]->getType()->isVectorTy())
05778         Cond[Part] =
05779             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
05780       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
05781                                ConstantInt::get(Cond[Part]->getType(), 1));
05782       CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
05783       LoopVectorBody.push_back(CondBlock);
05784       VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
05785       // Update Builder with newly created basic block.
05786       Builder.SetInsertPoint(InsertPt);
05787     }
05788 
05789     Instruction *Cloned = Instr->clone();
05790       if (!IsVoidRetTy)
05791         Cloned->setName(Instr->getName() + ".cloned");
05792       // Replace the operands of the cloned instructions with extracted scalars.
05793       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
05794         Value *Op = Params[op][Part];
05795         Cloned->setOperand(op, Op);
05796       }
05797 
05798       // Place the cloned scalar in the new loop.
05799       Builder.Insert(Cloned);
05800 
05801       // If the original scalar returns a value we need to place it in a vector
05802       // so that future users will be able to use it.
05803       if (!IsVoidRetTy)
05804         VecResults[Part] = Cloned;
05805 
05806     // End if-block.
05807       if (IfPredicateStore) {
05808         BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
05809         LoopVectorBody.push_back(NewIfBlock);
05810         VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
05811         Builder.SetInsertPoint(InsertPt);
05812         Instruction *OldBr = IfBlock->getTerminator();
05813         BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
05814         OldBr->eraseFromParent();
05815         IfBlock = NewIfBlock;
05816       }
05817   }
05818 }
05819 
05820 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
05821   StoreInst *SI = dyn_cast<StoreInst>(Instr);
05822   bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
05823 
05824   return scalarizeInstruction(Instr, IfPredicateStore);
05825 }
05826 
05827 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
05828   return Vec;
05829 }
05830 
05831 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
05832   return V;
05833 }
05834 
05835 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
05836                                                bool Negate) {
05837   // When unrolling and the VF is 1, we only need to add a simple scalar.
05838   Type *ITy = Val->getType();
05839   assert(!ITy->isVectorTy() && "Val must be a scalar");
05840   Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
05841   return Builder.CreateAdd(Val, C, "induction");
05842 }
05843