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