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