LLVM API Documentation

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