Home | History | Annotate | Download | only in Vectorize
      1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
     11 // and generates target-independent LLVM-IR.
     12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
     13 // of instructions in order to estimate the profitability of vectorization.
     14 //
     15 // The loop vectorizer combines consecutive loop iterations into a single
     16 // 'wide' iteration. After this transformation the index is incremented
     17 // by the SIMD vector width, and not by one.
     18 //
     19 // This pass has three parts:
     20 // 1. The main loop pass that drives the different parts.
     21 // 2. LoopVectorizationLegality - A unit that checks for the legality
     22 //    of the vectorization.
     23 // 3. InnerLoopVectorizer - A unit that performs the actual
     24 //    widening of instructions.
     25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
     26 //    of vectorization. It decides on the optimal vector width, which
     27 //    can be one, if vectorization is not profitable.
     28 //
     29 //===----------------------------------------------------------------------===//
     30 //
     31 // The reduction-variable vectorization is based on the paper:
     32 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
     33 //
     34 // Variable uniformity checks are inspired by:
     35 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
     36 //
     37 // The interleaved access vectorization is based on the paper:
     38 //  Dorit Nuzman, Ira Rosen and Ayal Zaks.  Auto-Vectorization of Interleaved
     39 //  Data for SIMD
     40 //
     41 // Other ideas/concepts are from:
     42 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
     43 //
     44 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
     45 //  Vectorizing Compilers.
     46 //
     47 //===----------------------------------------------------------------------===//
     48 
     49 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
     50 #include "llvm/ADT/DenseMap.h"
     51 #include "llvm/ADT/Hashing.h"
     52 #include "llvm/ADT/MapVector.h"
     53 #include "llvm/ADT/SetVector.h"
     54 #include "llvm/ADT/SmallPtrSet.h"
     55 #include "llvm/ADT/SmallSet.h"
     56 #include "llvm/ADT/SmallVector.h"
     57 #include "llvm/ADT/Statistic.h"
     58 #include "llvm/ADT/StringExtras.h"
     59 #include "llvm/Analysis/CodeMetrics.h"
     60 #include "llvm/Analysis/GlobalsModRef.h"
     61 #include "llvm/Analysis/LoopInfo.h"
     62 #include "llvm/Analysis/LoopIterator.h"
     63 #include "llvm/Analysis/LoopPass.h"
     64 #include "llvm/Analysis/ScalarEvolutionExpander.h"
     65 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
     66 #include "llvm/Analysis/ValueTracking.h"
     67 #include "llvm/Analysis/VectorUtils.h"
     68 #include "llvm/IR/Constants.h"
     69 #include "llvm/IR/DataLayout.h"
     70 #include "llvm/IR/DebugInfo.h"
     71 #include "llvm/IR/DerivedTypes.h"
     72 #include "llvm/IR/DiagnosticInfo.h"
     73 #include "llvm/IR/Dominators.h"
     74 #include "llvm/IR/Function.h"
     75 #include "llvm/IR/IRBuilder.h"
     76 #include "llvm/IR/Instructions.h"
     77 #include "llvm/IR/IntrinsicInst.h"
     78 #include "llvm/IR/LLVMContext.h"
     79 #include "llvm/IR/Module.h"
     80 #include "llvm/IR/PatternMatch.h"
     81 #include "llvm/IR/Type.h"
     82 #include "llvm/IR/Value.h"
     83 #include "llvm/IR/ValueHandle.h"
     84 #include "llvm/IR/Verifier.h"
     85 #include "llvm/Pass.h"
     86 #include "llvm/Support/BranchProbability.h"
     87 #include "llvm/Support/CommandLine.h"
     88 #include "llvm/Support/Debug.h"
     89 #include "llvm/Support/raw_ostream.h"
     90 #include "llvm/Transforms/Scalar.h"
     91 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     92 #include "llvm/Transforms/Utils/Local.h"
     93 #include "llvm/Transforms/Utils/LoopUtils.h"
     94 #include "llvm/Transforms/Utils/LoopVersioning.h"
     95 #include "llvm/Transforms/Vectorize.h"
     96 #include <algorithm>
     97 #include <map>
     98 #include <tuple>
     99 
    100 using namespace llvm;
    101 using namespace llvm::PatternMatch;
    102 
    103 #define LV_NAME "loop-vectorize"
    104 #define DEBUG_TYPE LV_NAME
    105 
    106 STATISTIC(LoopsVectorized, "Number of loops vectorized");
    107 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
    108 
    109 static cl::opt<bool>
    110     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
    111                        cl::desc("Enable if-conversion during vectorization."));
    112 
    113 /// We don't vectorize loops with a known constant trip count below this number.
    114 static cl::opt<unsigned> TinyTripCountVectorThreshold(
    115     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
    116     cl::desc("Don't vectorize loops with a constant "
    117              "trip count that is smaller than this "
    118              "value."));
    119 
    120 static cl::opt<bool> MaximizeBandwidth(
    121     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
    122     cl::desc("Maximize bandwidth when selecting vectorization factor which "
    123              "will be determined by the smallest type in loop."));
    124 
    125 static cl::opt<bool> EnableInterleavedMemAccesses(
    126     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
    127     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
    128 
    129 /// Maximum factor for an interleaved memory access.
    130 static cl::opt<unsigned> MaxInterleaveGroupFactor(
    131     "max-interleave-group-factor", cl::Hidden,
    132     cl::desc("Maximum factor for an interleaved access group (default = 8)"),
    133     cl::init(8));
    134 
    135 /// We don't interleave loops with a known constant trip count below this
    136 /// number.
    137 static const unsigned TinyTripCountInterleaveThreshold = 128;
    138 
    139 static cl::opt<unsigned> ForceTargetNumScalarRegs(
    140     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
    141     cl::desc("A flag that overrides the target's number of scalar registers."));
    142 
    143 static cl::opt<unsigned> ForceTargetNumVectorRegs(
    144     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
    145     cl::desc("A flag that overrides the target's number of vector registers."));
    146 
    147 /// Maximum vectorization interleave count.
    148 static const unsigned MaxInterleaveFactor = 16;
    149 
    150 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
    151     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
    152     cl::desc("A flag that overrides the target's max interleave factor for "
    153              "scalar loops."));
    154 
    155 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
    156     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
    157     cl::desc("A flag that overrides the target's max interleave factor for "
    158              "vectorized loops."));
    159 
    160 static cl::opt<unsigned> ForceTargetInstructionCost(
    161     "force-target-instruction-cost", cl::init(0), cl::Hidden,
    162     cl::desc("A flag that overrides the target's expected cost for "
    163              "an instruction to a single constant value. Mostly "
    164              "useful for getting consistent testing."));
    165 
    166 static cl::opt<unsigned> SmallLoopCost(
    167     "small-loop-cost", cl::init(20), cl::Hidden,
    168     cl::desc(
    169         "The cost of a loop that is considered 'small' by the interleaver."));
    170 
    171 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
    172     "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
    173     cl::desc("Enable the use of the block frequency analysis to access PGO "
    174              "heuristics minimizing code growth in cold regions and being more "
    175              "aggressive in hot regions."));
    176 
    177 // Runtime interleave loops for load/store throughput.
    178 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
    179     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
    180     cl::desc(
    181         "Enable runtime interleaving until load/store ports are saturated"));
    182 
    183 /// The number of stores in a loop that are allowed to need predication.
    184 static cl::opt<unsigned> NumberOfStoresToPredicate(
    185     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
    186     cl::desc("Max number of stores to be predicated behind an if."));
    187 
    188 static cl::opt<bool> EnableIndVarRegisterHeur(
    189     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
    190     cl::desc("Count the induction variable only once when interleaving"));
    191 
    192 static cl::opt<bool> EnableCondStoresVectorization(
    193     "enable-cond-stores-vec", cl::init(false), cl::Hidden,
    194     cl::desc("Enable if predication of stores during vectorization."));
    195 
    196 static cl::opt<unsigned> MaxNestedScalarReductionIC(
    197     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
    198     cl::desc("The maximum interleave count to use when interleaving a scalar "
    199              "reduction in a nested loop."));
    200 
    201 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
    202     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
    203     cl::desc("The maximum allowed number of runtime memory checks with a "
    204              "vectorize(enable) pragma."));
    205 
    206 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
    207     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
    208     cl::desc("The maximum number of SCEV checks allowed."));
    209 
    210 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
    211     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
    212     cl::desc("The maximum number of SCEV checks allowed with a "
    213              "vectorize(enable) pragma"));
    214 
    215 namespace {
    216 
    217 // Forward declarations.
    218 class LoopVectorizeHints;
    219 class LoopVectorizationLegality;
    220 class LoopVectorizationCostModel;
    221 class LoopVectorizationRequirements;
    222 
    223 /// \brief This modifies LoopAccessReport to initialize message with
    224 /// loop-vectorizer-specific part.
    225 class VectorizationReport : public LoopAccessReport {
    226 public:
    227   VectorizationReport(Instruction *I = nullptr)
    228       : LoopAccessReport("loop not vectorized: ", I) {}
    229 
    230   /// \brief This allows promotion of the loop-access analysis report into the
    231   /// loop-vectorizer report.  It modifies the message to add the
    232   /// loop-vectorizer-specific part of the message.
    233   explicit VectorizationReport(const LoopAccessReport &R)
    234       : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
    235                          R.getInstr()) {}
    236 };
    237 
    238 /// A helper function for converting Scalar types to vector types.
    239 /// If the incoming type is void, we return void. If the VF is 1, we return
    240 /// the scalar type.
    241 static Type *ToVectorTy(Type *Scalar, unsigned VF) {
    242   if (Scalar->isVoidTy() || VF == 1)
    243     return Scalar;
    244   return VectorType::get(Scalar, VF);
    245 }
    246 
    247 /// A helper function that returns GEP instruction and knows to skip a
    248 /// 'bitcast'. The 'bitcast' may be skipped if the source and the destination
    249 /// pointee types of the 'bitcast' have the same size.
    250 /// For example:
    251 ///   bitcast double** %var to i64* - can be skipped
    252 ///   bitcast double** %var to i8*  - can not
    253 static GetElementPtrInst *getGEPInstruction(Value *Ptr) {
    254 
    255   if (isa<GetElementPtrInst>(Ptr))
    256     return cast<GetElementPtrInst>(Ptr);
    257 
    258   if (isa<BitCastInst>(Ptr) &&
    259       isa<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0))) {
    260     Type *BitcastTy = Ptr->getType();
    261     Type *GEPTy = cast<BitCastInst>(Ptr)->getSrcTy();
    262     if (!isa<PointerType>(BitcastTy) || !isa<PointerType>(GEPTy))
    263       return nullptr;
    264     Type *Pointee1Ty = cast<PointerType>(BitcastTy)->getPointerElementType();
    265     Type *Pointee2Ty = cast<PointerType>(GEPTy)->getPointerElementType();
    266     const DataLayout &DL = cast<BitCastInst>(Ptr)->getModule()->getDataLayout();
    267     if (DL.getTypeSizeInBits(Pointee1Ty) == DL.getTypeSizeInBits(Pointee2Ty))
    268       return cast<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0));
    269   }
    270   return nullptr;
    271 }
    272 
    273 /// InnerLoopVectorizer vectorizes loops which contain only one basic
    274 /// block to a specified vectorization factor (VF).
    275 /// This class performs the widening of scalars into vectors, or multiple
    276 /// scalars. This class also implements the following features:
    277 /// * It inserts an epilogue loop for handling loops that don't have iteration
    278 ///   counts that are known to be a multiple of the vectorization factor.
    279 /// * It handles the code generation for reduction variables.
    280 /// * Scalarization (implementation using scalars) of un-vectorizable
    281 ///   instructions.
    282 /// InnerLoopVectorizer does not perform any vectorization-legality
    283 /// checks, and relies on the caller to check for the different legality
    284 /// aspects. The InnerLoopVectorizer relies on the
    285 /// LoopVectorizationLegality class to provide information about the induction
    286 /// and reduction variables that were found to a given vectorization factor.
    287 class InnerLoopVectorizer {
    288 public:
    289   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
    290                       LoopInfo *LI, DominatorTree *DT,
    291                       const TargetLibraryInfo *TLI,
    292                       const TargetTransformInfo *TTI, AssumptionCache *AC,
    293                       unsigned VecWidth, unsigned UnrollFactor)
    294       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
    295         AC(AC), VF(VecWidth), UF(UnrollFactor),
    296         Builder(PSE.getSE()->getContext()), Induction(nullptr),
    297         OldInduction(nullptr), WidenMap(UnrollFactor), TripCount(nullptr),
    298         VectorTripCount(nullptr), Legal(nullptr), AddedSafetyChecks(false) {}
    299 
    300   // Perform the actual loop widening (vectorization).
    301   // MinimumBitWidths maps scalar integer values to the smallest bitwidth they
    302   // can be validly truncated to. The cost model has assumed this truncation
    303   // will happen when vectorizing. VecValuesToIgnore contains scalar values
    304   // that the cost model has chosen to ignore because they will not be
    305   // vectorized.
    306   void vectorize(LoopVectorizationLegality *L,
    307                  const MapVector<Instruction *, uint64_t> &MinimumBitWidths,
    308                  SmallPtrSetImpl<const Value *> &VecValuesToIgnore) {
    309     MinBWs = &MinimumBitWidths;
    310     ValuesNotWidened = &VecValuesToIgnore;
    311     Legal = L;
    312     // Create a new empty loop. Unlink the old loop and connect the new one.
    313     createEmptyLoop();
    314     // Widen each instruction in the old loop to a new one in the new loop.
    315     // Use the Legality module to find the induction and reduction variables.
    316     vectorizeLoop();
    317   }
    318 
    319   // Return true if any runtime check is added.
    320   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
    321 
    322   virtual ~InnerLoopVectorizer() {}
    323 
    324 protected:
    325   /// A small list of PHINodes.
    326   typedef SmallVector<PHINode *, 4> PhiVector;
    327   /// When we unroll loops we have multiple vector values for each scalar.
    328   /// This data structure holds the unrolled and vectorized values that
    329   /// originated from one scalar instruction.
    330   typedef SmallVector<Value *, 2> VectorParts;
    331 
    332   // When we if-convert we need to create edge masks. We have to cache values
    333   // so that we don't end up with exponential recursion/IR.
    334   typedef DenseMap<std::pair<BasicBlock *, BasicBlock *>, VectorParts>
    335       EdgeMaskCache;
    336 
    337   /// Create an empty loop, based on the loop ranges of the old loop.
    338   void createEmptyLoop();
    339 
    340   /// Set up the values of the IVs correctly when exiting the vector loop.
    341   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
    342                     Value *CountRoundDown, Value *EndValue,
    343                     BasicBlock *MiddleBlock);
    344 
    345   /// Create a new induction variable inside L.
    346   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
    347                                    Value *Step, Instruction *DL);
    348   /// Copy and widen the instructions from the old loop.
    349   virtual void vectorizeLoop();
    350 
    351   /// Fix a first-order recurrence. This is the second phase of vectorizing
    352   /// this phi node.
    353   void fixFirstOrderRecurrence(PHINode *Phi);
    354 
    355   /// \brief The Loop exit block may have single value PHI nodes where the
    356   /// incoming value is 'Undef'. While vectorizing we only handled real values
    357   /// that were defined inside the loop. Here we fix the 'undef case'.
    358   /// See PR14725.
    359   void fixLCSSAPHIs();
    360 
    361   /// Shrinks vector element sizes based on information in "MinBWs".
    362   void truncateToMinimalBitwidths();
    363 
    364   /// A helper function that computes the predicate of the block BB, assuming
    365   /// that the header block of the loop is set to True. It returns the *entry*
    366   /// mask for the block BB.
    367   VectorParts createBlockInMask(BasicBlock *BB);
    368   /// A helper function that computes the predicate of the edge between SRC
    369   /// and DST.
    370   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
    371 
    372   /// A helper function to vectorize a single BB within the innermost loop.
    373   void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
    374 
    375   /// Vectorize a single PHINode in a block. This method handles the induction
    376   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
    377   /// arbitrary length vectors.
    378   void widenPHIInstruction(Instruction *PN, VectorParts &Entry, unsigned UF,
    379                            unsigned VF, PhiVector *PV);
    380 
    381   /// Insert the new loop to the loop hierarchy and pass manager
    382   /// and update the analysis passes.
    383   void updateAnalysis();
    384 
    385   /// This instruction is un-vectorizable. Implement it as a sequence
    386   /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
    387   /// scalarized instruction behind an if block predicated on the control
    388   /// dependence of the instruction.
    389   virtual void scalarizeInstruction(Instruction *Instr,
    390                                     bool IfPredicateStore = false);
    391 
    392   /// Vectorize Load and Store instructions,
    393   virtual void vectorizeMemoryInstruction(Instruction *Instr);
    394 
    395   /// Create a broadcast instruction. This method generates a broadcast
    396   /// instruction (shuffle) for loop invariant values and for the induction
    397   /// value. If this is the induction variable then we extend it to N, N+1, ...
    398   /// this is needed because each iteration in the loop corresponds to a SIMD
    399   /// element.
    400   virtual Value *getBroadcastInstrs(Value *V);
    401 
    402   /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
    403   /// to each vector element of Val. The sequence starts at StartIndex.
    404   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
    405 
    406   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
    407   /// variable on which to base the steps, \p Step is the size of the step, and
    408   /// \p EntryVal is the value from the original loop that maps to the steps.
    409   /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it
    410   /// can be a truncate instruction).
    411   void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal);
    412 
    413   /// Create a vector induction phi node based on an existing scalar one. This
    414   /// currently only works for integer induction variables with a constant
    415   /// step. If \p TruncType is non-null, instead of widening the original IV,
    416   /// we widen a version of the IV truncated to \p TruncType.
    417   void createVectorIntInductionPHI(const InductionDescriptor &II,
    418                                    VectorParts &Entry, IntegerType *TruncType);
    419 
    420   /// Widen an integer induction variable \p IV. If \p Trunc is provided, the
    421   /// induction variable will first be truncated to the corresponding type. The
    422   /// widened values are placed in \p Entry.
    423   void widenIntInduction(PHINode *IV, VectorParts &Entry,
    424                          TruncInst *Trunc = nullptr);
    425 
    426   /// When we go over instructions in the basic block we rely on previous
    427   /// values within the current basic block or on loop invariant values.
    428   /// When we widen (vectorize) values we place them in the map. If the values
    429   /// are not within the map, they have to be loop invariant, so we simply
    430   /// broadcast them into a vector.
    431   VectorParts &getVectorValue(Value *V);
    432 
    433   /// Try to vectorize the interleaved access group that \p Instr belongs to.
    434   void vectorizeInterleaveGroup(Instruction *Instr);
    435 
    436   /// Generate a shuffle sequence that will reverse the vector Vec.
    437   virtual Value *reverseVector(Value *Vec);
    438 
    439   /// Returns (and creates if needed) the original loop trip count.
    440   Value *getOrCreateTripCount(Loop *NewLoop);
    441 
    442   /// Returns (and creates if needed) the trip count of the widened loop.
    443   Value *getOrCreateVectorTripCount(Loop *NewLoop);
    444 
    445   /// Emit a bypass check to see if the trip count would overflow, or we
    446   /// wouldn't have enough iterations to execute one vector loop.
    447   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
    448   /// Emit a bypass check to see if the vector trip count is nonzero.
    449   void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
    450   /// Emit a bypass check to see if all of the SCEV assumptions we've
    451   /// had to make are correct.
    452   void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
    453   /// Emit bypass checks to check any memory assumptions we may have made.
    454   void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
    455 
    456   /// Add additional metadata to \p To that was not present on \p Orig.
    457   ///
    458   /// Currently this is used to add the noalias annotations based on the
    459   /// inserted memchecks.  Use this for instructions that are *cloned* into the
    460   /// vector loop.
    461   void addNewMetadata(Instruction *To, const Instruction *Orig);
    462 
    463   /// Add metadata from one instruction to another.
    464   ///
    465   /// This includes both the original MDs from \p From and additional ones (\see
    466   /// addNewMetadata).  Use this for *newly created* instructions in the vector
    467   /// loop.
    468   void addMetadata(Instruction *To, Instruction *From);
    469 
    470   /// \brief Similar to the previous function but it adds the metadata to a
    471   /// vector of instructions.
    472   void addMetadata(ArrayRef<Value *> To, Instruction *From);
    473 
    474   /// This is a helper class that holds the vectorizer state. It maps scalar
    475   /// instructions to vector instructions. When the code is 'unrolled' then
    476   /// then a single scalar value is mapped to multiple vector parts. The parts
    477   /// are stored in the VectorPart type.
    478   struct ValueMap {
    479     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
    480     /// are mapped.
    481     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
    482 
    483     /// \return True if 'Key' is saved in the Value Map.
    484     bool has(Value *Key) const { return MapStorage.count(Key); }
    485 
    486     /// Initializes a new entry in the map. Sets all of the vector parts to the
    487     /// save value in 'Val'.
    488     /// \return A reference to a vector with splat values.
    489     VectorParts &splat(Value *Key, Value *Val) {
    490       VectorParts &Entry = MapStorage[Key];
    491       Entry.assign(UF, Val);
    492       return Entry;
    493     }
    494 
    495     ///\return A reference to the value that is stored at 'Key'.
    496     VectorParts &get(Value *Key) {
    497       VectorParts &Entry = MapStorage[Key];
    498       if (Entry.empty())
    499         Entry.resize(UF);
    500       assert(Entry.size() == UF);
    501       return Entry;
    502     }
    503 
    504   private:
    505     /// The unroll factor. Each entry in the map stores this number of vector
    506     /// elements.
    507     unsigned UF;
    508 
    509     /// Map storage. We use std::map and not DenseMap because insertions to a
    510     /// dense map invalidates its iterators.
    511     std::map<Value *, VectorParts> MapStorage;
    512   };
    513 
    514   /// The original loop.
    515   Loop *OrigLoop;
    516   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
    517   /// dynamic knowledge to simplify SCEV expressions and converts them to a
    518   /// more usable form.
    519   PredicatedScalarEvolution &PSE;
    520   /// Loop Info.
    521   LoopInfo *LI;
    522   /// Dominator Tree.
    523   DominatorTree *DT;
    524   /// Alias Analysis.
    525   AliasAnalysis *AA;
    526   /// Target Library Info.
    527   const TargetLibraryInfo *TLI;
    528   /// Target Transform Info.
    529   const TargetTransformInfo *TTI;
    530   /// Assumption Cache.
    531   AssumptionCache *AC;
    532 
    533   /// \brief LoopVersioning.  It's only set up (non-null) if memchecks were
    534   /// used.
    535   ///
    536   /// This is currently only used to add no-alias metadata based on the
    537   /// memchecks.  The actually versioning is performed manually.
    538   std::unique_ptr<LoopVersioning> LVer;
    539 
    540   /// The vectorization SIMD factor to use. Each vector will have this many
    541   /// vector elements.
    542   unsigned VF;
    543 
    544 protected:
    545   /// The vectorization unroll factor to use. Each scalar is vectorized to this
    546   /// many different vector instructions.
    547   unsigned UF;
    548 
    549   /// The builder that we use
    550   IRBuilder<> Builder;
    551 
    552   // --- Vectorization state ---
    553 
    554   /// The vector-loop preheader.
    555   BasicBlock *LoopVectorPreHeader;
    556   /// The scalar-loop preheader.
    557   BasicBlock *LoopScalarPreHeader;
    558   /// Middle Block between the vector and the scalar.
    559   BasicBlock *LoopMiddleBlock;
    560   /// The ExitBlock of the scalar loop.
    561   BasicBlock *LoopExitBlock;
    562   /// The vector loop body.
    563   BasicBlock *LoopVectorBody;
    564   /// The scalar loop body.
    565   BasicBlock *LoopScalarBody;
    566   /// A list of all bypass blocks. The first block is the entry of the loop.
    567   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
    568 
    569   /// The new Induction variable which was added to the new block.
    570   PHINode *Induction;
    571   /// The induction variable of the old basic block.
    572   PHINode *OldInduction;
    573   /// Maps scalars to widened vectors.
    574   ValueMap WidenMap;
    575 
    576   /// A map of induction variables from the original loop to their
    577   /// corresponding VF * UF scalarized values in the vectorized loop. The
    578   /// purpose of ScalarIVMap is similar to that of WidenMap. Whereas WidenMap
    579   /// maps original loop values to their vector versions in the new loop,
    580   /// ScalarIVMap maps induction variables from the original loop that are not
    581   /// vectorized to their scalar equivalents in the vector loop. Maintaining a
    582   /// separate map for scalarized induction variables allows us to avoid
    583   /// unnecessary scalar-to-vector-to-scalar conversions.
    584   DenseMap<Value *, SmallVector<Value *, 8>> ScalarIVMap;
    585 
    586   /// Store instructions that should be predicated, as a pair
    587   ///   <StoreInst, Predicate>
    588   SmallVector<std::pair<StoreInst *, Value *>, 4> PredicatedStores;
    589   EdgeMaskCache MaskCache;
    590   /// Trip count of the original loop.
    591   Value *TripCount;
    592   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
    593   Value *VectorTripCount;
    594 
    595   /// Map of scalar integer values to the smallest bitwidth they can be legally
    596   /// represented as. The vector equivalents of these values should be truncated
    597   /// to this type.
    598   const MapVector<Instruction *, uint64_t> *MinBWs;
    599 
    600   /// A set of values that should not be widened. This is taken from
    601   /// VecValuesToIgnore in the cost model.
    602   SmallPtrSetImpl<const Value *> *ValuesNotWidened;
    603 
    604   LoopVectorizationLegality *Legal;
    605 
    606   // Record whether runtime checks are added.
    607   bool AddedSafetyChecks;
    608 };
    609 
    610 class InnerLoopUnroller : public InnerLoopVectorizer {
    611 public:
    612   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
    613                     LoopInfo *LI, DominatorTree *DT,
    614                     const TargetLibraryInfo *TLI,
    615                     const TargetTransformInfo *TTI, AssumptionCache *AC,
    616                     unsigned UnrollFactor)
    617       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, 1,
    618                             UnrollFactor) {}
    619 
    620 private:
    621   void scalarizeInstruction(Instruction *Instr,
    622                             bool IfPredicateStore = false) override;
    623   void vectorizeMemoryInstruction(Instruction *Instr) override;
    624   Value *getBroadcastInstrs(Value *V) override;
    625   Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
    626   Value *reverseVector(Value *Vec) override;
    627 };
    628 
    629 /// \brief Look for a meaningful debug location on the instruction or it's
    630 /// operands.
    631 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
    632   if (!I)
    633     return I;
    634 
    635   DebugLoc Empty;
    636   if (I->getDebugLoc() != Empty)
    637     return I;
    638 
    639   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
    640     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
    641       if (OpInst->getDebugLoc() != Empty)
    642         return OpInst;
    643   }
    644 
    645   return I;
    646 }
    647 
    648 /// \brief Set the debug location in the builder using the debug location in the
    649 /// instruction.
    650 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
    651   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
    652     B.SetCurrentDebugLocation(Inst->getDebugLoc());
    653   else
    654     B.SetCurrentDebugLocation(DebugLoc());
    655 }
    656 
    657 #ifndef NDEBUG
    658 /// \return string containing a file name and a line # for the given loop.
    659 static std::string getDebugLocString(const Loop *L) {
    660   std::string Result;
    661   if (L) {
    662     raw_string_ostream OS(Result);
    663     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
    664       LoopDbgLoc.print(OS);
    665     else
    666       // Just print the module name.
    667       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
    668     OS.flush();
    669   }
    670   return Result;
    671 }
    672 #endif
    673 
    674 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
    675                                          const Instruction *Orig) {
    676   // If the loop was versioned with memchecks, add the corresponding no-alias
    677   // metadata.
    678   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
    679     LVer->annotateInstWithNoAlias(To, Orig);
    680 }
    681 
    682 void InnerLoopVectorizer::addMetadata(Instruction *To,
    683                                       Instruction *From) {
    684   propagateMetadata(To, From);
    685   addNewMetadata(To, From);
    686 }
    687 
    688 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
    689                                       Instruction *From) {
    690   for (Value *V : To) {
    691     if (Instruction *I = dyn_cast<Instruction>(V))
    692       addMetadata(I, From);
    693   }
    694 }
    695 
    696 /// \brief The group of interleaved loads/stores sharing the same stride and
    697 /// close to each other.
    698 ///
    699 /// Each member in this group has an index starting from 0, and the largest
    700 /// index should be less than interleaved factor, which is equal to the absolute
    701 /// value of the access's stride.
    702 ///
    703 /// E.g. An interleaved load group of factor 4:
    704 ///        for (unsigned i = 0; i < 1024; i+=4) {
    705 ///          a = A[i];                           // Member of index 0
    706 ///          b = A[i+1];                         // Member of index 1
    707 ///          d = A[i+3];                         // Member of index 3
    708 ///          ...
    709 ///        }
    710 ///
    711 ///      An interleaved store group of factor 4:
    712 ///        for (unsigned i = 0; i < 1024; i+=4) {
    713 ///          ...
    714 ///          A[i]   = a;                         // Member of index 0
    715 ///          A[i+1] = b;                         // Member of index 1
    716 ///          A[i+2] = c;                         // Member of index 2
    717 ///          A[i+3] = d;                         // Member of index 3
    718 ///        }
    719 ///
    720 /// Note: the interleaved load group could have gaps (missing members), but
    721 /// the interleaved store group doesn't allow gaps.
    722 class InterleaveGroup {
    723 public:
    724   InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
    725       : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
    726     assert(Align && "The alignment should be non-zero");
    727 
    728     Factor = std::abs(Stride);
    729     assert(Factor > 1 && "Invalid interleave factor");
    730 
    731     Reverse = Stride < 0;
    732     Members[0] = Instr;
    733   }
    734 
    735   bool isReverse() const { return Reverse; }
    736   unsigned getFactor() const { return Factor; }
    737   unsigned getAlignment() const { return Align; }
    738   unsigned getNumMembers() const { return Members.size(); }
    739 
    740   /// \brief Try to insert a new member \p Instr with index \p Index and
    741   /// alignment \p NewAlign. The index is related to the leader and it could be
    742   /// negative if it is the new leader.
    743   ///
    744   /// \returns false if the instruction doesn't belong to the group.
    745   bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
    746     assert(NewAlign && "The new member's alignment should be non-zero");
    747 
    748     int Key = Index + SmallestKey;
    749 
    750     // Skip if there is already a member with the same index.
    751     if (Members.count(Key))
    752       return false;
    753 
    754     if (Key > LargestKey) {
    755       // The largest index is always less than the interleave factor.
    756       if (Index >= static_cast<int>(Factor))
    757         return false;
    758 
    759       LargestKey = Key;
    760     } else if (Key < SmallestKey) {
    761       // The largest index is always less than the interleave factor.
    762       if (LargestKey - Key >= static_cast<int>(Factor))
    763         return false;
    764 
    765       SmallestKey = Key;
    766     }
    767 
    768     // It's always safe to select the minimum alignment.
    769     Align = std::min(Align, NewAlign);
    770     Members[Key] = Instr;
    771     return true;
    772   }
    773 
    774   /// \brief Get the member with the given index \p Index
    775   ///
    776   /// \returns nullptr if contains no such member.
    777   Instruction *getMember(unsigned Index) const {
    778     int Key = SmallestKey + Index;
    779     if (!Members.count(Key))
    780       return nullptr;
    781 
    782     return Members.find(Key)->second;
    783   }
    784 
    785   /// \brief Get the index for the given member. Unlike the key in the member
    786   /// map, the index starts from 0.
    787   unsigned getIndex(Instruction *Instr) const {
    788     for (auto I : Members)
    789       if (I.second == Instr)
    790         return I.first - SmallestKey;
    791 
    792     llvm_unreachable("InterleaveGroup contains no such member");
    793   }
    794 
    795   Instruction *getInsertPos() const { return InsertPos; }
    796   void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
    797 
    798 private:
    799   unsigned Factor; // Interleave Factor.
    800   bool Reverse;
    801   unsigned Align;
    802   DenseMap<int, Instruction *> Members;
    803   int SmallestKey;
    804   int LargestKey;
    805 
    806   // To avoid breaking dependences, vectorized instructions of an interleave
    807   // group should be inserted at either the first load or the last store in
    808   // program order.
    809   //
    810   // E.g. %even = load i32             // Insert Position
    811   //      %add = add i32 %even         // Use of %even
    812   //      %odd = load i32
    813   //
    814   //      store i32 %even
    815   //      %odd = add i32               // Def of %odd
    816   //      store i32 %odd               // Insert Position
    817   Instruction *InsertPos;
    818 };
    819 
    820 /// \brief Drive the analysis of interleaved memory accesses in the loop.
    821 ///
    822 /// Use this class to analyze interleaved accesses only when we can vectorize
    823 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
    824 /// on interleaved accesses is unsafe.
    825 ///
    826 /// The analysis collects interleave groups and records the relationships
    827 /// between the member and the group in a map.
    828 class InterleavedAccessInfo {
    829 public:
    830   InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
    831                         DominatorTree *DT, LoopInfo *LI)
    832       : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(nullptr),
    833         RequiresScalarEpilogue(false) {}
    834 
    835   ~InterleavedAccessInfo() {
    836     SmallSet<InterleaveGroup *, 4> DelSet;
    837     // Avoid releasing a pointer twice.
    838     for (auto &I : InterleaveGroupMap)
    839       DelSet.insert(I.second);
    840     for (auto *Ptr : DelSet)
    841       delete Ptr;
    842   }
    843 
    844   /// \brief Analyze the interleaved accesses and collect them in interleave
    845   /// groups. Substitute symbolic strides using \p Strides.
    846   void analyzeInterleaving(const ValueToValueMap &Strides);
    847 
    848   /// \brief Check if \p Instr belongs to any interleave group.
    849   bool isInterleaved(Instruction *Instr) const {
    850     return InterleaveGroupMap.count(Instr);
    851   }
    852 
    853   /// \brief Return the maximum interleave factor of all interleaved groups.
    854   unsigned getMaxInterleaveFactor() const {
    855     unsigned MaxFactor = 1;
    856     for (auto &Entry : InterleaveGroupMap)
    857       MaxFactor = std::max(MaxFactor, Entry.second->getFactor());
    858     return MaxFactor;
    859   }
    860 
    861   /// \brief Get the interleave group that \p Instr belongs to.
    862   ///
    863   /// \returns nullptr if doesn't have such group.
    864   InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
    865     if (InterleaveGroupMap.count(Instr))
    866       return InterleaveGroupMap.find(Instr)->second;
    867     return nullptr;
    868   }
    869 
    870   /// \brief Returns true if an interleaved group that may access memory
    871   /// out-of-bounds requires a scalar epilogue iteration for correctness.
    872   bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
    873 
    874   /// \brief Initialize the LoopAccessInfo used for dependence checking.
    875   void setLAI(const LoopAccessInfo *Info) { LAI = Info; }
    876 
    877 private:
    878   /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
    879   /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
    880   /// The interleaved access analysis can also add new predicates (for example
    881   /// by versioning strides of pointers).
    882   PredicatedScalarEvolution &PSE;
    883   Loop *TheLoop;
    884   DominatorTree *DT;
    885   LoopInfo *LI;
    886   const LoopAccessInfo *LAI;
    887 
    888   /// True if the loop may contain non-reversed interleaved groups with
    889   /// out-of-bounds accesses. We ensure we don't speculatively access memory
    890   /// out-of-bounds by executing at least one scalar epilogue iteration.
    891   bool RequiresScalarEpilogue;
    892 
    893   /// Holds the relationships between the members and the interleave group.
    894   DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
    895 
    896   /// Holds dependences among the memory accesses in the loop. It maps a source
    897   /// access to a set of dependent sink accesses.
    898   DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
    899 
    900   /// \brief The descriptor for a strided memory access.
    901   struct StrideDescriptor {
    902     StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
    903                      unsigned Align)
    904         : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
    905 
    906     StrideDescriptor() = default;
    907 
    908     // The access's stride. It is negative for a reverse access.
    909     int64_t Stride = 0;
    910     const SCEV *Scev = nullptr; // The scalar expression of this access
    911     uint64_t Size = 0;          // The size of the memory object.
    912     unsigned Align = 0;         // The alignment of this access.
    913   };
    914 
    915   /// \brief A type for holding instructions and their stride descriptors.
    916   typedef std::pair<Instruction *, StrideDescriptor> StrideEntry;
    917 
    918   /// \brief Create a new interleave group with the given instruction \p Instr,
    919   /// stride \p Stride and alignment \p Align.
    920   ///
    921   /// \returns the newly created interleave group.
    922   InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
    923                                          unsigned Align) {
    924     assert(!InterleaveGroupMap.count(Instr) &&
    925            "Already in an interleaved access group");
    926     InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
    927     return InterleaveGroupMap[Instr];
    928   }
    929 
    930   /// \brief Release the group and remove all the relationships.
    931   void releaseGroup(InterleaveGroup *Group) {
    932     for (unsigned i = 0; i < Group->getFactor(); i++)
    933       if (Instruction *Member = Group->getMember(i))
    934         InterleaveGroupMap.erase(Member);
    935 
    936     delete Group;
    937   }
    938 
    939   /// \brief Collect all the accesses with a constant stride in program order.
    940   void collectConstStrideAccesses(
    941       MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
    942       const ValueToValueMap &Strides);
    943 
    944   /// \brief Returns true if \p Stride is allowed in an interleaved group.
    945   static bool isStrided(int Stride) {
    946     unsigned Factor = std::abs(Stride);
    947     return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
    948   }
    949 
    950   /// \brief Returns true if \p BB is a predicated block.
    951   bool isPredicated(BasicBlock *BB) const {
    952     return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
    953   }
    954 
    955   /// \brief Returns true if LoopAccessInfo can be used for dependence queries.
    956   bool areDependencesValid() const {
    957     return LAI && LAI->getDepChecker().getDependences();
    958   }
    959 
    960   /// \brief Returns true if memory accesses \p B and \p A can be reordered, if
    961   /// necessary, when constructing interleaved groups.
    962   ///
    963   /// \p B must precede \p A in program order. We return false if reordering is
    964   /// not necessary or is prevented because \p B and \p A may be dependent.
    965   bool canReorderMemAccessesForInterleavedGroups(StrideEntry *B,
    966                                                  StrideEntry *A) const {
    967 
    968     // Code motion for interleaved accesses can potentially hoist strided loads
    969     // and sink strided stores. The code below checks the legality of the
    970     // following two conditions:
    971     //
    972     // 1. Potentially moving a strided load (A) before any store (B) that
    973     //    precedes A, or
    974     //
    975     // 2. Potentially moving a strided store (B) after any load or store (A)
    976     //    that B precedes.
    977     //
    978     // It's legal to reorder B and A if we know there isn't a dependence from B
    979     // to A. Note that this determination is conservative since some
    980     // dependences could potentially be reordered safely.
    981 
    982     // B is potentially the source of a dependence.
    983     auto *Src = B->first;
    984     auto SrcDes = B->second;
    985 
    986     // A is potentially the sink of a dependence.
    987     auto *Sink = A->first;
    988     auto SinkDes = A->second;
    989 
    990     // Code motion for interleaved accesses can't violate WAR dependences.
    991     // Thus, reordering is legal if the source isn't a write.
    992     if (!Src->mayWriteToMemory())
    993       return true;
    994 
    995     // At least one of the accesses must be strided.
    996     if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
    997       return true;
    998 
    999     // If dependence information is not available from LoopAccessInfo,
   1000     // conservatively assume the instructions can't be reordered.
   1001     if (!areDependencesValid())
   1002       return false;
   1003 
   1004     // If we know there is a dependence from source to sink, assume the
   1005     // instructions can't be reordered. Otherwise, reordering is legal.
   1006     return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink);
   1007   }
   1008 
   1009   /// \brief Collect the dependences from LoopAccessInfo.
   1010   ///
   1011   /// We process the dependences once during the interleaved access analysis to
   1012   /// enable constant-time dependence queries.
   1013   void collectDependences() {
   1014     if (!areDependencesValid())
   1015       return;
   1016     auto *Deps = LAI->getDepChecker().getDependences();
   1017     for (auto Dep : *Deps)
   1018       Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
   1019   }
   1020 };
   1021 
   1022 /// Utility class for getting and setting loop vectorizer hints in the form
   1023 /// of loop metadata.
   1024 /// This class keeps a number of loop annotations locally (as member variables)
   1025 /// and can, upon request, write them back as metadata on the loop. It will
   1026 /// initially scan the loop for existing metadata, and will update the local
   1027 /// values based on information in the loop.
   1028 /// We cannot write all values to metadata, as the mere presence of some info,
   1029 /// for example 'force', means a decision has been made. So, we need to be
   1030 /// careful NOT to add them if the user hasn't specifically asked so.
   1031 class LoopVectorizeHints {
   1032   enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE };
   1033 
   1034   /// Hint - associates name and validation with the hint value.
   1035   struct Hint {
   1036     const char *Name;
   1037     unsigned Value; // This may have to change for non-numeric values.
   1038     HintKind Kind;
   1039 
   1040     Hint(const char *Name, unsigned Value, HintKind Kind)
   1041         : Name(Name), Value(Value), Kind(Kind) {}
   1042 
   1043     bool validate(unsigned Val) {
   1044       switch (Kind) {
   1045       case HK_WIDTH:
   1046         return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
   1047       case HK_UNROLL:
   1048         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
   1049       case HK_FORCE:
   1050         return (Val <= 1);
   1051       }
   1052       return false;
   1053     }
   1054   };
   1055 
   1056   /// Vectorization width.
   1057   Hint Width;
   1058   /// Vectorization interleave factor.
   1059   Hint Interleave;
   1060   /// Vectorization forced
   1061   Hint Force;
   1062 
   1063   /// Return the loop metadata prefix.
   1064   static StringRef Prefix() { return "llvm.loop."; }
   1065 
   1066   /// True if there is any unsafe math in the loop.
   1067   bool PotentiallyUnsafe;
   1068 
   1069 public:
   1070   enum ForceKind {
   1071     FK_Undefined = -1, ///< Not selected.
   1072     FK_Disabled = 0,   ///< Forcing disabled.
   1073     FK_Enabled = 1,    ///< Forcing enabled.
   1074   };
   1075 
   1076   LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
   1077       : Width("vectorize.width", VectorizerParams::VectorizationFactor,
   1078               HK_WIDTH),
   1079         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
   1080         Force("vectorize.enable", FK_Undefined, HK_FORCE),
   1081         PotentiallyUnsafe(false), TheLoop(L) {
   1082     // Populate values with existing loop metadata.
   1083     getHintsFromMetadata();
   1084 
   1085     // force-vector-interleave overrides DisableInterleaving.
   1086     if (VectorizerParams::isInterleaveForced())
   1087       Interleave.Value = VectorizerParams::VectorizationInterleave;
   1088 
   1089     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
   1090           << "LV: Interleaving disabled by the pass manager\n");
   1091   }
   1092 
   1093   /// Mark the loop L as already vectorized by setting the width to 1.
   1094   void setAlreadyVectorized() {
   1095     Width.Value = Interleave.Value = 1;
   1096     Hint Hints[] = {Width, Interleave};
   1097     writeHintsToMetadata(Hints);
   1098   }
   1099 
   1100   bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
   1101     if (getForce() == LoopVectorizeHints::FK_Disabled) {
   1102       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
   1103       emitOptimizationRemarkAnalysis(F->getContext(),
   1104                                      vectorizeAnalysisPassName(), *F,
   1105                                      L->getStartLoc(), emitRemark());
   1106       return false;
   1107     }
   1108 
   1109     if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
   1110       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
   1111       emitOptimizationRemarkAnalysis(F->getContext(),
   1112                                      vectorizeAnalysisPassName(), *F,
   1113                                      L->getStartLoc(), emitRemark());
   1114       return false;
   1115     }
   1116 
   1117     if (getWidth() == 1 && getInterleave() == 1) {
   1118       // FIXME: Add a separate metadata to indicate when the loop has already
   1119       // been vectorized instead of setting width and count to 1.
   1120       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
   1121       // FIXME: Add interleave.disable metadata. This will allow
   1122       // vectorize.disable to be used without disabling the pass and errors
   1123       // to differentiate between disabled vectorization and a width of 1.
   1124       emitOptimizationRemarkAnalysis(
   1125           F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
   1126           "loop not vectorized: vectorization and interleaving are explicitly "
   1127           "disabled, or vectorize width and interleave count are both set to "
   1128           "1");
   1129       return false;
   1130     }
   1131 
   1132     return true;
   1133   }
   1134 
   1135   /// Dumps all the hint information.
   1136   std::string emitRemark() const {
   1137     VectorizationReport R;
   1138     if (Force.Value == LoopVectorizeHints::FK_Disabled)
   1139       R << "vectorization is explicitly disabled";
   1140     else {
   1141       R << "use -Rpass-analysis=loop-vectorize for more info";
   1142       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
   1143         R << " (Force=true";
   1144         if (Width.Value != 0)
   1145           R << ", Vector Width=" << Width.Value;
   1146         if (Interleave.Value != 0)
   1147           R << ", Interleave Count=" << Interleave.Value;
   1148         R << ")";
   1149       }
   1150     }
   1151 
   1152     return R.str();
   1153   }
   1154 
   1155   unsigned getWidth() const { return Width.Value; }
   1156   unsigned getInterleave() const { return Interleave.Value; }
   1157   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
   1158 
   1159   /// \brief If hints are provided that force vectorization, use the AlwaysPrint
   1160   /// pass name to force the frontend to print the diagnostic.
   1161   const char *vectorizeAnalysisPassName() const {
   1162     if (getWidth() == 1)
   1163       return LV_NAME;
   1164     if (getForce() == LoopVectorizeHints::FK_Disabled)
   1165       return LV_NAME;
   1166     if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
   1167       return LV_NAME;
   1168     return DiagnosticInfoOptimizationRemarkAnalysis::AlwaysPrint;
   1169   }
   1170 
   1171   bool allowReordering() const {
   1172     // When enabling loop hints are provided we allow the vectorizer to change
   1173     // the order of operations that is given by the scalar loop. This is not
   1174     // enabled by default because can be unsafe or inefficient. For example,
   1175     // reordering floating-point operations will change the way round-off
   1176     // error accumulates in the loop.
   1177     return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
   1178   }
   1179 
   1180   bool isPotentiallyUnsafe() const {
   1181     // Avoid FP vectorization if the target is unsure about proper support.
   1182     // This may be related to the SIMD unit in the target not handling
   1183     // IEEE 754 FP ops properly, or bad single-to-double promotions.
   1184     // Otherwise, a sequence of vectorized loops, even without reduction,
   1185     // could lead to different end results on the destination vectors.
   1186     return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
   1187   }
   1188 
   1189   void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
   1190 
   1191 private:
   1192   /// Find hints specified in the loop metadata and update local values.
   1193   void getHintsFromMetadata() {
   1194     MDNode *LoopID = TheLoop->getLoopID();
   1195     if (!LoopID)
   1196       return;
   1197 
   1198     // First operand should refer to the loop id itself.
   1199     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
   1200     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
   1201 
   1202     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
   1203       const MDString *S = nullptr;
   1204       SmallVector<Metadata *, 4> Args;
   1205 
   1206       // The expected hint is either a MDString or a MDNode with the first
   1207       // operand a MDString.
   1208       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
   1209         if (!MD || MD->getNumOperands() == 0)
   1210           continue;
   1211         S = dyn_cast<MDString>(MD->getOperand(0));
   1212         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
   1213           Args.push_back(MD->getOperand(i));
   1214       } else {
   1215         S = dyn_cast<MDString>(LoopID->getOperand(i));
   1216         assert(Args.size() == 0 && "too many arguments for MDString");
   1217       }
   1218 
   1219       if (!S)
   1220         continue;
   1221 
   1222       // Check if the hint starts with the loop metadata prefix.
   1223       StringRef Name = S->getString();
   1224       if (Args.size() == 1)
   1225         setHint(Name, Args[0]);
   1226     }
   1227   }
   1228 
   1229   /// Checks string hint with one operand and set value if valid.
   1230   void setHint(StringRef Name, Metadata *Arg) {
   1231     if (!Name.startswith(Prefix()))
   1232       return;
   1233     Name = Name.substr(Prefix().size(), StringRef::npos);
   1234 
   1235     const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
   1236     if (!C)
   1237       return;
   1238     unsigned Val = C->getZExtValue();
   1239 
   1240     Hint *Hints[] = {&Width, &Interleave, &Force};
   1241     for (auto H : Hints) {
   1242       if (Name == H->Name) {
   1243         if (H->validate(Val))
   1244           H->Value = Val;
   1245         else
   1246           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
   1247         break;
   1248       }
   1249     }
   1250   }
   1251 
   1252   /// Create a new hint from name / value pair.
   1253   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
   1254     LLVMContext &Context = TheLoop->getHeader()->getContext();
   1255     Metadata *MDs[] = {MDString::get(Context, Name),
   1256                        ConstantAsMetadata::get(
   1257                            ConstantInt::get(Type::getInt32Ty(Context), V))};
   1258     return MDNode::get(Context, MDs);
   1259   }
   1260 
   1261   /// Matches metadata with hint name.
   1262   bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
   1263     MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
   1264     if (!Name)
   1265       return false;
   1266 
   1267     for (auto H : HintTypes)
   1268       if (Name->getString().endswith(H.Name))
   1269         return true;
   1270     return false;
   1271   }
   1272 
   1273   /// Sets current hints into loop metadata, keeping other values intact.
   1274   void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
   1275     if (HintTypes.size() == 0)
   1276       return;
   1277 
   1278     // Reserve the first element to LoopID (see below).
   1279     SmallVector<Metadata *, 4> MDs(1);
   1280     // If the loop already has metadata, then ignore the existing operands.
   1281     MDNode *LoopID = TheLoop->getLoopID();
   1282     if (LoopID) {
   1283       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
   1284         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
   1285         // If node in update list, ignore old value.
   1286         if (!matchesHintMetadataName(Node, HintTypes))
   1287           MDs.push_back(Node);
   1288       }
   1289     }
   1290 
   1291     // Now, add the missing hints.
   1292     for (auto H : HintTypes)
   1293       MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
   1294 
   1295     // Replace current metadata node with new one.
   1296     LLVMContext &Context = TheLoop->getHeader()->getContext();
   1297     MDNode *NewLoopID = MDNode::get(Context, MDs);
   1298     // Set operand 0 to refer to the loop id itself.
   1299     NewLoopID->replaceOperandWith(0, NewLoopID);
   1300 
   1301     TheLoop->setLoopID(NewLoopID);
   1302   }
   1303 
   1304   /// The loop these hints belong to.
   1305   const Loop *TheLoop;
   1306 };
   1307 
   1308 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
   1309                              const LoopVectorizeHints &Hints,
   1310                              const LoopAccessReport &Message) {
   1311   const char *Name = Hints.vectorizeAnalysisPassName();
   1312   LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
   1313 }
   1314 
   1315 static void emitMissedWarning(Function *F, Loop *L,
   1316                               const LoopVectorizeHints &LH) {
   1317   emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
   1318                                LH.emitRemark());
   1319 
   1320   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
   1321     if (LH.getWidth() != 1)
   1322       emitLoopVectorizeWarning(
   1323           F->getContext(), *F, L->getStartLoc(),
   1324           "failed explicitly specified loop vectorization");
   1325     else if (LH.getInterleave() != 1)
   1326       emitLoopInterleaveWarning(
   1327           F->getContext(), *F, L->getStartLoc(),
   1328           "failed explicitly specified loop interleaving");
   1329   }
   1330 }
   1331 
   1332 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
   1333 /// to what vectorization factor.
   1334 /// This class does not look at the profitability of vectorization, only the
   1335 /// legality. This class has two main kinds of checks:
   1336 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
   1337 ///   will change the order of memory accesses in a way that will change the
   1338 ///   correctness of the program.
   1339 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
   1340 /// checks for a number of different conditions, such as the availability of a
   1341 /// single induction variable, that all types are supported and vectorize-able,
   1342 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
   1343 /// This class is also used by InnerLoopVectorizer for identifying
   1344 /// induction variable and the different reduction variables.
   1345 class LoopVectorizationLegality {
   1346 public:
   1347   LoopVectorizationLegality(
   1348       Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT,
   1349       TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F,
   1350       const TargetTransformInfo *TTI,
   1351       std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI,
   1352       LoopVectorizationRequirements *R, LoopVectorizeHints *H)
   1353       : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TheFunction(F),
   1354         TTI(TTI), DT(DT), GetLAA(GetLAA), LAI(nullptr),
   1355         InterleaveInfo(PSE, L, DT, LI), Induction(nullptr),
   1356         WidestIndTy(nullptr), HasFunNoNaNAttr(false), Requirements(R),
   1357         Hints(H) {}
   1358 
   1359   /// ReductionList contains the reduction descriptors for all
   1360   /// of the reductions that were found in the loop.
   1361   typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
   1362 
   1363   /// InductionList saves induction variables and maps them to the
   1364   /// induction descriptor.
   1365   typedef MapVector<PHINode *, InductionDescriptor> InductionList;
   1366 
   1367   /// RecurrenceSet contains the phi nodes that are recurrences other than
   1368   /// inductions and reductions.
   1369   typedef SmallPtrSet<const PHINode *, 8> RecurrenceSet;
   1370 
   1371   /// Returns true if it is legal to vectorize this loop.
   1372   /// This does not mean that it is profitable to vectorize this
   1373   /// loop, only that it is legal to do so.
   1374   bool canVectorize();
   1375 
   1376   /// Returns the Induction variable.
   1377   PHINode *getInduction() { return Induction; }
   1378 
   1379   /// Returns the reduction variables found in the loop.
   1380   ReductionList *getReductionVars() { return &Reductions; }
   1381 
   1382   /// Returns the induction variables found in the loop.
   1383   InductionList *getInductionVars() { return &Inductions; }
   1384 
   1385   /// Return the first-order recurrences found in the loop.
   1386   RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
   1387 
   1388   /// Returns the widest induction type.
   1389   Type *getWidestInductionType() { return WidestIndTy; }
   1390 
   1391   /// Returns True if V is an induction variable in this loop.
   1392   bool isInductionVariable(const Value *V);
   1393 
   1394   /// Returns True if PN is a reduction variable in this loop.
   1395   bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
   1396 
   1397   /// Returns True if Phi is a first-order recurrence in this loop.
   1398   bool isFirstOrderRecurrence(const PHINode *Phi);
   1399 
   1400   /// Return true if the block BB needs to be predicated in order for the loop
   1401   /// to be vectorized.
   1402   bool blockNeedsPredication(BasicBlock *BB);
   1403 
   1404   /// Check if this pointer is consecutive when vectorizing. This happens
   1405   /// when the last index of the GEP is the induction variable, or that the
   1406   /// pointer itself is an induction variable.
   1407   /// This check allows us to vectorize A[idx] into a wide load/store.
   1408   /// Returns:
   1409   /// 0 - Stride is unknown or non-consecutive.
   1410   /// 1 - Address is consecutive.
   1411   /// -1 - Address is consecutive, and decreasing.
   1412   int isConsecutivePtr(Value *Ptr);
   1413 
   1414   /// Returns true if the value V is uniform within the loop.
   1415   bool isUniform(Value *V);
   1416 
   1417   /// Returns true if this instruction will remain scalar after vectorization.
   1418   bool isUniformAfterVectorization(Instruction *I) { return Uniforms.count(I); }
   1419 
   1420   /// Returns the information that we collected about runtime memory check.
   1421   const RuntimePointerChecking *getRuntimePointerChecking() const {
   1422     return LAI->getRuntimePointerChecking();
   1423   }
   1424 
   1425   const LoopAccessInfo *getLAI() const { return LAI; }
   1426 
   1427   /// \brief Check if \p Instr belongs to any interleaved access group.
   1428   bool isAccessInterleaved(Instruction *Instr) {
   1429     return InterleaveInfo.isInterleaved(Instr);
   1430   }
   1431 
   1432   /// \brief Return the maximum interleave factor of all interleaved groups.
   1433   unsigned getMaxInterleaveFactor() const {
   1434     return InterleaveInfo.getMaxInterleaveFactor();
   1435   }
   1436 
   1437   /// \brief Get the interleaved access group that \p Instr belongs to.
   1438   const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
   1439     return InterleaveInfo.getInterleaveGroup(Instr);
   1440   }
   1441 
   1442   /// \brief Returns true if an interleaved group requires a scalar iteration
   1443   /// to handle accesses with gaps.
   1444   bool requiresScalarEpilogue() const {
   1445     return InterleaveInfo.requiresScalarEpilogue();
   1446   }
   1447 
   1448   unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
   1449 
   1450   bool hasStride(Value *V) { return LAI->hasStride(V); }
   1451 
   1452   /// Returns true if the target machine supports masked store operation
   1453   /// for the given \p DataType and kind of access to \p Ptr.
   1454   bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
   1455     return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
   1456   }
   1457   /// Returns true if the target machine supports masked load operation
   1458   /// for the given \p DataType and kind of access to \p Ptr.
   1459   bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
   1460     return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
   1461   }
   1462   /// Returns true if the target machine supports masked scatter operation
   1463   /// for the given \p DataType.
   1464   bool isLegalMaskedScatter(Type *DataType) {
   1465     return TTI->isLegalMaskedScatter(DataType);
   1466   }
   1467   /// Returns true if the target machine supports masked gather operation
   1468   /// for the given \p DataType.
   1469   bool isLegalMaskedGather(Type *DataType) {
   1470     return TTI->isLegalMaskedGather(DataType);
   1471   }
   1472 
   1473   /// Returns true if vector representation of the instruction \p I
   1474   /// requires mask.
   1475   bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
   1476   unsigned getNumStores() const { return LAI->getNumStores(); }
   1477   unsigned getNumLoads() const { return LAI->getNumLoads(); }
   1478   unsigned getNumPredStores() const { return NumPredStores; }
   1479 
   1480 private:
   1481   /// Check if a single basic block loop is vectorizable.
   1482   /// At this point we know that this is a loop with a constant trip count
   1483   /// and we only need to check individual instructions.
   1484   bool canVectorizeInstrs();
   1485 
   1486   /// When we vectorize loops we may change the order in which
   1487   /// we read and write from memory. This method checks if it is
   1488   /// legal to vectorize the code, considering only memory constrains.
   1489   /// Returns true if the loop is vectorizable
   1490   bool canVectorizeMemory();
   1491 
   1492   /// Return true if we can vectorize this loop using the IF-conversion
   1493   /// transformation.
   1494   bool canVectorizeWithIfConvert();
   1495 
   1496   /// Collect the variables that need to stay uniform after vectorization.
   1497   void collectLoopUniforms();
   1498 
   1499   /// Return true if all of the instructions in the block can be speculatively
   1500   /// executed. \p SafePtrs is a list of addresses that are known to be legal
   1501   /// and we know that we can read from them without segfault.
   1502   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
   1503 
   1504   /// Updates the vectorization state by adding \p Phi to the inductions list.
   1505   /// This can set \p Phi as the main induction of the loop if \p Phi is a
   1506   /// better choice for the main induction than the existing one.
   1507   void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID,
   1508                        SmallPtrSetImpl<Value *> &AllowedExit);
   1509 
   1510   /// Report an analysis message to assist the user in diagnosing loops that are
   1511   /// not vectorized.  These are handled as LoopAccessReport rather than
   1512   /// VectorizationReport because the << operator of VectorizationReport returns
   1513   /// LoopAccessReport.
   1514   void emitAnalysis(const LoopAccessReport &Message) const {
   1515     emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
   1516   }
   1517 
   1518   /// \brief If an access has a symbolic strides, this maps the pointer value to
   1519   /// the stride symbol.
   1520   const ValueToValueMap *getSymbolicStrides() {
   1521     // FIXME: Currently, the set of symbolic strides is sometimes queried before
   1522     // it's collected.  This happens from canVectorizeWithIfConvert, when the
   1523     // pointer is checked to reference consecutive elements suitable for a
   1524     // masked access.
   1525     return LAI ? &LAI->getSymbolicStrides() : nullptr;
   1526   }
   1527 
   1528   unsigned NumPredStores;
   1529 
   1530   /// The loop that we evaluate.
   1531   Loop *TheLoop;
   1532   /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
   1533   /// Applies dynamic knowledge to simplify SCEV expressions in the context
   1534   /// of existing SCEV assumptions. The analysis will also add a minimal set
   1535   /// of new predicates if this is required to enable vectorization and
   1536   /// unrolling.
   1537   PredicatedScalarEvolution &PSE;
   1538   /// Target Library Info.
   1539   TargetLibraryInfo *TLI;
   1540   /// Parent function
   1541   Function *TheFunction;
   1542   /// Target Transform Info
   1543   const TargetTransformInfo *TTI;
   1544   /// Dominator Tree.
   1545   DominatorTree *DT;
   1546   // LoopAccess analysis.
   1547   std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
   1548   // And the loop-accesses info corresponding to this loop.  This pointer is
   1549   // null until canVectorizeMemory sets it up.
   1550   const LoopAccessInfo *LAI;
   1551 
   1552   /// The interleave access information contains groups of interleaved accesses
   1553   /// with the same stride and close to each other.
   1554   InterleavedAccessInfo InterleaveInfo;
   1555 
   1556   //  ---  vectorization state --- //
   1557 
   1558   /// Holds the integer induction variable. This is the counter of the
   1559   /// loop.
   1560   PHINode *Induction;
   1561   /// Holds the reduction variables.
   1562   ReductionList Reductions;
   1563   /// Holds all of the induction variables that we found in the loop.
   1564   /// Notice that inductions don't need to start at zero and that induction
   1565   /// variables can be pointers.
   1566   InductionList Inductions;
   1567   /// Holds the phi nodes that are first-order recurrences.
   1568   RecurrenceSet FirstOrderRecurrences;
   1569   /// Holds the widest induction type encountered.
   1570   Type *WidestIndTy;
   1571 
   1572   /// Allowed outside users. This holds the induction and reduction
   1573   /// vars which can be accessed from outside the loop.
   1574   SmallPtrSet<Value *, 4> AllowedExit;
   1575   /// This set holds the variables which are known to be uniform after
   1576   /// vectorization.
   1577   SmallPtrSet<Instruction *, 4> Uniforms;
   1578 
   1579   /// Can we assume the absence of NaNs.
   1580   bool HasFunNoNaNAttr;
   1581 
   1582   /// Vectorization requirements that will go through late-evaluation.
   1583   LoopVectorizationRequirements *Requirements;
   1584 
   1585   /// Used to emit an analysis of any legality issues.
   1586   LoopVectorizeHints *Hints;
   1587 
   1588   /// While vectorizing these instructions we have to generate a
   1589   /// call to the appropriate masked intrinsic
   1590   SmallPtrSet<const Instruction *, 8> MaskedOp;
   1591 };
   1592 
   1593 /// LoopVectorizationCostModel - estimates the expected speedups due to
   1594 /// vectorization.
   1595 /// In many cases vectorization is not profitable. This can happen because of
   1596 /// a number of reasons. In this class we mainly attempt to predict the
   1597 /// expected speedup/slowdowns due to the supported instruction set. We use the
   1598 /// TargetTransformInfo to query the different backends for the cost of
   1599 /// different operations.
   1600 class LoopVectorizationCostModel {
   1601 public:
   1602   LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
   1603                              LoopInfo *LI, LoopVectorizationLegality *Legal,
   1604                              const TargetTransformInfo &TTI,
   1605                              const TargetLibraryInfo *TLI, DemandedBits *DB,
   1606                              AssumptionCache *AC, const Function *F,
   1607                              const LoopVectorizeHints *Hints)
   1608       : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
   1609         AC(AC), TheFunction(F), Hints(Hints) {}
   1610 
   1611   /// Information about vectorization costs
   1612   struct VectorizationFactor {
   1613     unsigned Width; // Vector width with best cost
   1614     unsigned Cost;  // Cost of the loop with that width
   1615   };
   1616   /// \return The most profitable vectorization factor and the cost of that VF.
   1617   /// This method checks every power of two up to VF. If UserVF is not ZERO
   1618   /// then this vectorization factor will be selected if vectorization is
   1619   /// possible.
   1620   VectorizationFactor selectVectorizationFactor(bool OptForSize);
   1621 
   1622   /// \return The size (in bits) of the smallest and widest types in the code
   1623   /// that needs to be vectorized. We ignore values that remain scalar such as
   1624   /// 64 bit loop indices.
   1625   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
   1626 
   1627   /// \return The desired interleave count.
   1628   /// If interleave count has been specified by metadata it will be returned.
   1629   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
   1630   /// are the selected vectorization factor and the cost of the selected VF.
   1631   unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
   1632                                  unsigned LoopCost);
   1633 
   1634   /// \return The most profitable unroll factor.
   1635   /// This method finds the best unroll-factor based on register pressure and
   1636   /// other parameters. VF and LoopCost are the selected vectorization factor
   1637   /// and the cost of the selected VF.
   1638   unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
   1639                                   unsigned LoopCost);
   1640 
   1641   /// \brief A struct that represents some properties of the register usage
   1642   /// of a loop.
   1643   struct RegisterUsage {
   1644     /// Holds the number of loop invariant values that are used in the loop.
   1645     unsigned LoopInvariantRegs;
   1646     /// Holds the maximum number of concurrent live intervals in the loop.
   1647     unsigned MaxLocalUsers;
   1648     /// Holds the number of instructions in the loop.
   1649     unsigned NumInstructions;
   1650   };
   1651 
   1652   /// \return Returns information about the register usages of the loop for the
   1653   /// given vectorization factors.
   1654   SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
   1655 
   1656   /// Collect values we want to ignore in the cost model.
   1657   void collectValuesToIgnore();
   1658 
   1659 private:
   1660   /// The vectorization cost is a combination of the cost itself and a boolean
   1661   /// indicating whether any of the contributing operations will actually
   1662   /// operate on
   1663   /// vector values after type legalization in the backend. If this latter value
   1664   /// is
   1665   /// false, then all operations will be scalarized (i.e. no vectorization has
   1666   /// actually taken place).
   1667   typedef std::pair<unsigned, bool> VectorizationCostTy;
   1668 
   1669   /// Returns the expected execution cost. The unit of the cost does
   1670   /// not matter because we use the 'cost' units to compare different
   1671   /// vector widths. The cost that is returned is *not* normalized by
   1672   /// the factor width.
   1673   VectorizationCostTy expectedCost(unsigned VF);
   1674 
   1675   /// Returns the execution time cost of an instruction for a given vector
   1676   /// width. Vector width of one means scalar.
   1677   VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
   1678 
   1679   /// The cost-computation logic from getInstructionCost which provides
   1680   /// the vector type as an output parameter.
   1681   unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
   1682 
   1683   /// Returns whether the instruction is a load or store and will be a emitted
   1684   /// as a vector operation.
   1685   bool isConsecutiveLoadOrStore(Instruction *I);
   1686 
   1687   /// Report an analysis message to assist the user in diagnosing loops that are
   1688   /// not vectorized.  These are handled as LoopAccessReport rather than
   1689   /// VectorizationReport because the << operator of VectorizationReport returns
   1690   /// LoopAccessReport.
   1691   void emitAnalysis(const LoopAccessReport &Message) const {
   1692     emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
   1693   }
   1694 
   1695 public:
   1696   /// Map of scalar integer values to the smallest bitwidth they can be legally
   1697   /// represented as. The vector equivalents of these values should be truncated
   1698   /// to this type.
   1699   MapVector<Instruction *, uint64_t> MinBWs;
   1700 
   1701   /// The loop that we evaluate.
   1702   Loop *TheLoop;
   1703   /// Predicated scalar evolution analysis.
   1704   PredicatedScalarEvolution &PSE;
   1705   /// Loop Info analysis.
   1706   LoopInfo *LI;
   1707   /// Vectorization legality.
   1708   LoopVectorizationLegality *Legal;
   1709   /// Vector target information.
   1710   const TargetTransformInfo &TTI;
   1711   /// Target Library Info.
   1712   const TargetLibraryInfo *TLI;
   1713   /// Demanded bits analysis.
   1714   DemandedBits *DB;
   1715   /// Assumption cache.
   1716   AssumptionCache *AC;
   1717   const Function *TheFunction;
   1718   /// Loop Vectorize Hint.
   1719   const LoopVectorizeHints *Hints;
   1720   /// Values to ignore in the cost model.
   1721   SmallPtrSet<const Value *, 16> ValuesToIgnore;
   1722   /// Values to ignore in the cost model when VF > 1.
   1723   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
   1724 };
   1725 
   1726 /// \brief This holds vectorization requirements that must be verified late in
   1727 /// the process. The requirements are set by legalize and costmodel. Once
   1728 /// vectorization has been determined to be possible and profitable the
   1729 /// requirements can be verified by looking for metadata or compiler options.
   1730 /// For example, some loops require FP commutativity which is only allowed if
   1731 /// vectorization is explicitly specified or if the fast-math compiler option
   1732 /// has been provided.
   1733 /// Late evaluation of these requirements allows helpful diagnostics to be
   1734 /// composed that tells the user what need to be done to vectorize the loop. For
   1735 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
   1736 /// evaluation should be used only when diagnostics can generated that can be
   1737 /// followed by a non-expert user.
   1738 class LoopVectorizationRequirements {
   1739 public:
   1740   LoopVectorizationRequirements()
   1741       : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
   1742 
   1743   void addUnsafeAlgebraInst(Instruction *I) {
   1744     // First unsafe algebra instruction.
   1745     if (!UnsafeAlgebraInst)
   1746       UnsafeAlgebraInst = I;
   1747   }
   1748 
   1749   void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
   1750 
   1751   bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
   1752     const char *Name = Hints.vectorizeAnalysisPassName();
   1753     bool Failed = false;
   1754     if (UnsafeAlgebraInst && !Hints.allowReordering()) {
   1755       emitOptimizationRemarkAnalysisFPCommute(
   1756           F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
   1757           VectorizationReport() << "cannot prove it is safe to reorder "
   1758                                    "floating-point operations");
   1759       Failed = true;
   1760     }
   1761 
   1762     // Test if runtime memcheck thresholds are exceeded.
   1763     bool PragmaThresholdReached =
   1764         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
   1765     bool ThresholdReached =
   1766         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
   1767     if ((ThresholdReached && !Hints.allowReordering()) ||
   1768         PragmaThresholdReached) {
   1769       emitOptimizationRemarkAnalysisAliasing(
   1770           F->getContext(), Name, *F, L->getStartLoc(),
   1771           VectorizationReport()
   1772               << "cannot prove it is safe to reorder memory operations");
   1773       DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
   1774       Failed = true;
   1775     }
   1776 
   1777     return Failed;
   1778   }
   1779 
   1780 private:
   1781   unsigned NumRuntimePointerChecks;
   1782   Instruction *UnsafeAlgebraInst;
   1783 };
   1784 
   1785 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
   1786   if (L.empty())
   1787     return V.push_back(&L);
   1788 
   1789   for (Loop *InnerL : L)
   1790     addInnerLoop(*InnerL, V);
   1791 }
   1792 
   1793 /// The LoopVectorize Pass.
   1794 struct LoopVectorize : public FunctionPass {
   1795   /// Pass identification, replacement for typeid
   1796   static char ID;
   1797 
   1798   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
   1799       : FunctionPass(ID) {
   1800     Impl.DisableUnrolling = NoUnrolling;
   1801     Impl.AlwaysVectorize = AlwaysVectorize;
   1802     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
   1803   }
   1804 
   1805   LoopVectorizePass Impl;
   1806 
   1807   bool runOnFunction(Function &F) override {
   1808     if (skipFunction(F))
   1809       return false;
   1810 
   1811     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
   1812     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
   1813     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
   1814     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
   1815     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
   1816     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
   1817     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
   1818     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
   1819     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
   1820     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
   1821     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
   1822 
   1823     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
   1824         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
   1825 
   1826     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
   1827                         GetLAA);
   1828   }
   1829 
   1830   void getAnalysisUsage(AnalysisUsage &AU) const override {
   1831     AU.addRequired<AssumptionCacheTracker>();
   1832     AU.addRequiredID(LoopSimplifyID);
   1833     AU.addRequiredID(LCSSAID);
   1834     AU.addRequired<BlockFrequencyInfoWrapperPass>();
   1835     AU.addRequired<DominatorTreeWrapperPass>();
   1836     AU.addRequired<LoopInfoWrapperPass>();
   1837     AU.addRequired<ScalarEvolutionWrapperPass>();
   1838     AU.addRequired<TargetTransformInfoWrapperPass>();
   1839     AU.addRequired<AAResultsWrapperPass>();
   1840     AU.addRequired<LoopAccessLegacyAnalysis>();
   1841     AU.addRequired<DemandedBitsWrapperPass>();
   1842     AU.addPreserved<LoopInfoWrapperPass>();
   1843     AU.addPreserved<DominatorTreeWrapperPass>();
   1844     AU.addPreserved<BasicAAWrapperPass>();
   1845     AU.addPreserved<GlobalsAAWrapperPass>();
   1846   }
   1847 };
   1848 
   1849 } // end anonymous namespace
   1850 
   1851 //===----------------------------------------------------------------------===//
   1852 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
   1853 // LoopVectorizationCostModel.
   1854 //===----------------------------------------------------------------------===//
   1855 
   1856 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
   1857   // We need to place the broadcast of invariant variables outside the loop.
   1858   Instruction *Instr = dyn_cast<Instruction>(V);
   1859   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
   1860   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
   1861 
   1862   // Place the code for broadcasting invariant variables in the new preheader.
   1863   IRBuilder<>::InsertPointGuard Guard(Builder);
   1864   if (Invariant)
   1865     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
   1866 
   1867   // Broadcast the scalar into all locations in the vector.
   1868   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
   1869 
   1870   return Shuf;
   1871 }
   1872 
   1873 void InnerLoopVectorizer::createVectorIntInductionPHI(
   1874     const InductionDescriptor &II, VectorParts &Entry, IntegerType *TruncType) {
   1875   Value *Start = II.getStartValue();
   1876   ConstantInt *Step = II.getConstIntStepValue();
   1877   assert(Step && "Can not widen an IV with a non-constant step");
   1878 
   1879   // Construct the initial value of the vector IV in the vector loop preheader
   1880   auto CurrIP = Builder.saveIP();
   1881   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
   1882   if (TruncType) {
   1883     Step = ConstantInt::getSigned(TruncType, Step->getSExtValue());
   1884     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
   1885   }
   1886   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
   1887   Value *SteppedStart = getStepVector(SplatStart, 0, Step);
   1888   Builder.restoreIP(CurrIP);
   1889 
   1890   Value *SplatVF =
   1891       ConstantVector::getSplat(VF, ConstantInt::getSigned(Start->getType(),
   1892                                VF * Step->getSExtValue()));
   1893   // We may need to add the step a number of times, depending on the unroll
   1894   // factor. The last of those goes into the PHI.
   1895   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
   1896                                     &*LoopVectorBody->getFirstInsertionPt());
   1897   Value *LastInduction = VecInd;
   1898   for (unsigned Part = 0; Part < UF; ++Part) {
   1899     Entry[Part] = LastInduction;
   1900     LastInduction = Builder.CreateAdd(LastInduction, SplatVF, "step.add");
   1901   }
   1902 
   1903   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
   1904   VecInd->addIncoming(LastInduction, LoopVectorBody);
   1905 }
   1906 
   1907 void InnerLoopVectorizer::widenIntInduction(PHINode *IV, VectorParts &Entry,
   1908                                             TruncInst *Trunc) {
   1909 
   1910   auto II = Legal->getInductionVars()->find(IV);
   1911   assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
   1912 
   1913   auto ID = II->second;
   1914   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
   1915 
   1916   // If a truncate instruction was provided, get the smaller type.
   1917   auto *TruncType = Trunc ? cast<IntegerType>(Trunc->getType()) : nullptr;
   1918 
   1919   // The step of the induction.
   1920   Value *Step = nullptr;
   1921 
   1922   // If the induction variable has a constant integer step value, go ahead and
   1923   // get it now.
   1924   if (ID.getConstIntStepValue())
   1925     Step = ID.getConstIntStepValue();
   1926 
   1927   // Try to create a new independent vector induction variable. If we can't
   1928   // create the phi node, we will splat the scalar induction variable in each
   1929   // loop iteration.
   1930   if (VF > 1 && IV->getType() == Induction->getType() && Step &&
   1931       !ValuesNotWidened->count(IV))
   1932     return createVectorIntInductionPHI(ID, Entry, TruncType);
   1933 
   1934   // The scalar value to broadcast. This will be derived from the canonical
   1935   // induction variable.
   1936   Value *ScalarIV = nullptr;
   1937 
   1938   // Define the scalar induction variable and step values. If we were given a
   1939   // truncation type, truncate the canonical induction variable and constant
   1940   // step. Otherwise, derive these values from the induction descriptor.
   1941   if (TruncType) {
   1942     assert(Step && "Truncation requires constant integer step");
   1943     auto StepInt = cast<ConstantInt>(Step)->getSExtValue();
   1944     ScalarIV = Builder.CreateCast(Instruction::Trunc, Induction, TruncType);
   1945     Step = ConstantInt::getSigned(TruncType, StepInt);
   1946   } else {
   1947     ScalarIV = Induction;
   1948     auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
   1949     if (IV != OldInduction) {
   1950       ScalarIV = Builder.CreateSExtOrTrunc(ScalarIV, IV->getType());
   1951       ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
   1952       ScalarIV->setName("offset.idx");
   1953     }
   1954     if (!Step) {
   1955       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
   1956       Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
   1957                                &*Builder.GetInsertPoint());
   1958     }
   1959   }
   1960 
   1961   // Splat the scalar induction variable, and build the necessary step vectors.
   1962   Value *Broadcasted = getBroadcastInstrs(ScalarIV);
   1963   for (unsigned Part = 0; Part < UF; ++Part)
   1964     Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
   1965 
   1966   // If an induction variable is only used for counting loop iterations or
   1967   // calculating addresses, it doesn't need to be widened. Create scalar steps
   1968   // that can be used by instructions we will later scalarize. Note that the
   1969   // addition of the scalar steps will not increase the number of instructions
   1970   // in the loop in the common case prior to InstCombine. We will be trading
   1971   // one vector extract for each scalar step.
   1972   if (VF > 1 && ValuesNotWidened->count(IV)) {
   1973     auto *EntryVal = Trunc ? cast<Value>(Trunc) : IV;
   1974     buildScalarSteps(ScalarIV, Step, EntryVal);
   1975   }
   1976 }
   1977 
   1978 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
   1979                                           Value *Step) {
   1980   assert(Val->getType()->isVectorTy() && "Must be a vector");
   1981   assert(Val->getType()->getScalarType()->isIntegerTy() &&
   1982          "Elem must be an integer");
   1983   assert(Step->getType() == Val->getType()->getScalarType() &&
   1984          "Step has wrong type");
   1985   // Create the types.
   1986   Type *ITy = Val->getType()->getScalarType();
   1987   VectorType *Ty = cast<VectorType>(Val->getType());
   1988   int VLen = Ty->getNumElements();
   1989   SmallVector<Constant *, 8> Indices;
   1990 
   1991   // Create a vector of consecutive numbers from zero to VF.
   1992   for (int i = 0; i < VLen; ++i)
   1993     Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
   1994 
   1995   // Add the consecutive indices to the vector value.
   1996   Constant *Cv = ConstantVector::get(Indices);
   1997   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
   1998   Step = Builder.CreateVectorSplat(VLen, Step);
   1999   assert(Step->getType() == Val->getType() && "Invalid step vec");
   2000   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
   2001   // which can be found from the original scalar operations.
   2002   Step = Builder.CreateMul(Cv, Step);
   2003   return Builder.CreateAdd(Val, Step, "induction");
   2004 }
   2005 
   2006 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
   2007                                            Value *EntryVal) {
   2008 
   2009   // We shouldn't have to build scalar steps if we aren't vectorizing.
   2010   assert(VF > 1 && "VF should be greater than one");
   2011 
   2012   // Get the value type and ensure it and the step have the same integer type.
   2013   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
   2014   assert(ScalarIVTy->isIntegerTy() && ScalarIVTy == Step->getType() &&
   2015          "Val and Step should have the same integer type");
   2016 
   2017   // Compute the scalar steps and save the results in ScalarIVMap.
   2018   for (unsigned Part = 0; Part < UF; ++Part)
   2019     for (unsigned I = 0; I < VF; ++I) {
   2020       auto *StartIdx = ConstantInt::get(ScalarIVTy, VF * Part + I);
   2021       auto *Mul = Builder.CreateMul(StartIdx, Step);
   2022       auto *Add = Builder.CreateAdd(ScalarIV, Mul);
   2023       ScalarIVMap[EntryVal].push_back(Add);
   2024     }
   2025 }
   2026 
   2027 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
   2028   assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
   2029   auto *SE = PSE.getSE();
   2030   // Make sure that the pointer does not point to structs.
   2031   if (Ptr->getType()->getPointerElementType()->isAggregateType())
   2032     return 0;
   2033 
   2034   // If this value is a pointer induction variable, we know it is consecutive.
   2035   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
   2036   if (Phi && Inductions.count(Phi)) {
   2037     InductionDescriptor II = Inductions[Phi];
   2038     return II.getConsecutiveDirection();
   2039   }
   2040 
   2041   GetElementPtrInst *Gep = getGEPInstruction(Ptr);
   2042   if (!Gep)
   2043     return 0;
   2044 
   2045   unsigned NumOperands = Gep->getNumOperands();
   2046   Value *GpPtr = Gep->getPointerOperand();
   2047   // If this GEP value is a consecutive pointer induction variable and all of
   2048   // the indices are constant, then we know it is consecutive.
   2049   Phi = dyn_cast<PHINode>(GpPtr);
   2050   if (Phi && Inductions.count(Phi)) {
   2051 
   2052     // Make sure that the pointer does not point to structs.
   2053     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
   2054     if (GepPtrType->getElementType()->isAggregateType())
   2055       return 0;
   2056 
   2057     // Make sure that all of the index operands are loop invariant.
   2058     for (unsigned i = 1; i < NumOperands; ++i)
   2059       if (!SE->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), TheLoop))
   2060         return 0;
   2061 
   2062     InductionDescriptor II = Inductions[Phi];
   2063     return II.getConsecutiveDirection();
   2064   }
   2065 
   2066   unsigned InductionOperand = getGEPInductionOperand(Gep);
   2067 
   2068   // Check that all of the gep indices are uniform except for our induction
   2069   // operand.
   2070   for (unsigned i = 0; i != NumOperands; ++i)
   2071     if (i != InductionOperand &&
   2072         !SE->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), TheLoop))
   2073       return 0;
   2074 
   2075   // We can emit wide load/stores only if the last non-zero index is the
   2076   // induction variable.
   2077   const SCEV *Last = nullptr;
   2078   if (!getSymbolicStrides() || !getSymbolicStrides()->count(Gep))
   2079     Last = PSE.getSCEV(Gep->getOperand(InductionOperand));
   2080   else {
   2081     // Because of the multiplication by a stride we can have a s/zext cast.
   2082     // We are going to replace this stride by 1 so the cast is safe to ignore.
   2083     //
   2084     //  %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
   2085     //  %0 = trunc i64 %indvars.iv to i32
   2086     //  %mul = mul i32 %0, %Stride1
   2087     //  %idxprom = zext i32 %mul to i64  << Safe cast.
   2088     //  %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
   2089     //
   2090     Last = replaceSymbolicStrideSCEV(PSE, *getSymbolicStrides(),
   2091                                      Gep->getOperand(InductionOperand), Gep);
   2092     if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
   2093       Last =
   2094           (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
   2095               ? C->getOperand()
   2096               : Last;
   2097   }
   2098   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
   2099     const SCEV *Step = AR->getStepRecurrence(*SE);
   2100 
   2101     // The memory is consecutive because the last index is consecutive
   2102     // and all other indices are loop invariant.
   2103     if (Step->isOne())
   2104       return 1;
   2105     if (Step->isAllOnesValue())
   2106       return -1;
   2107   }
   2108 
   2109   return 0;
   2110 }
   2111 
   2112 bool LoopVectorizationLegality::isUniform(Value *V) {
   2113   return LAI->isUniform(V);
   2114 }
   2115 
   2116 InnerLoopVectorizer::VectorParts &
   2117 InnerLoopVectorizer::getVectorValue(Value *V) {
   2118   assert(V != Induction && "The new induction variable should not be used.");
   2119   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
   2120 
   2121   // If we have a stride that is replaced by one, do it here.
   2122   if (Legal->hasStride(V))
   2123     V = ConstantInt::get(V->getType(), 1);
   2124 
   2125   // If we have this scalar in the map, return it.
   2126   if (WidenMap.has(V))
   2127     return WidenMap.get(V);
   2128 
   2129   // If this scalar is unknown, assume that it is a constant or that it is
   2130   // loop invariant. Broadcast V and save the value for future uses.
   2131   Value *B = getBroadcastInstrs(V);
   2132   return WidenMap.splat(V, B);
   2133 }
   2134 
   2135 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
   2136   assert(Vec->getType()->isVectorTy() && "Invalid type");
   2137   SmallVector<Constant *, 8> ShuffleMask;
   2138   for (unsigned i = 0; i < VF; ++i)
   2139     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
   2140 
   2141   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
   2142                                      ConstantVector::get(ShuffleMask),
   2143                                      "reverse");
   2144 }
   2145 
   2146 // Get a mask to interleave \p NumVec vectors into a wide vector.
   2147 // I.e.  <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
   2148 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
   2149 //      <0, 4, 1, 5, 2, 6, 3, 7>
   2150 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
   2151                                     unsigned NumVec) {
   2152   SmallVector<Constant *, 16> Mask;
   2153   for (unsigned i = 0; i < VF; i++)
   2154     for (unsigned j = 0; j < NumVec; j++)
   2155       Mask.push_back(Builder.getInt32(j * VF + i));
   2156 
   2157   return ConstantVector::get(Mask);
   2158 }
   2159 
   2160 // Get the strided mask starting from index \p Start.
   2161 // I.e.  <Start, Start + Stride, ..., Start + Stride*(VF-1)>
   2162 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
   2163                                 unsigned Stride, unsigned VF) {
   2164   SmallVector<Constant *, 16> Mask;
   2165   for (unsigned i = 0; i < VF; i++)
   2166     Mask.push_back(Builder.getInt32(Start + i * Stride));
   2167 
   2168   return ConstantVector::get(Mask);
   2169 }
   2170 
   2171 // Get a mask of two parts: The first part consists of sequential integers
   2172 // starting from 0, The second part consists of UNDEFs.
   2173 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
   2174 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
   2175                                    unsigned NumUndef) {
   2176   SmallVector<Constant *, 16> Mask;
   2177   for (unsigned i = 0; i < NumInt; i++)
   2178     Mask.push_back(Builder.getInt32(i));
   2179 
   2180   Constant *Undef = UndefValue::get(Builder.getInt32Ty());
   2181   for (unsigned i = 0; i < NumUndef; i++)
   2182     Mask.push_back(Undef);
   2183 
   2184   return ConstantVector::get(Mask);
   2185 }
   2186 
   2187 // Concatenate two vectors with the same element type. The 2nd vector should
   2188 // not have more elements than the 1st vector. If the 2nd vector has less
   2189 // elements, extend it with UNDEFs.
   2190 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
   2191                                     Value *V2) {
   2192   VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
   2193   VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
   2194   assert(VecTy1 && VecTy2 &&
   2195          VecTy1->getScalarType() == VecTy2->getScalarType() &&
   2196          "Expect two vectors with the same element type");
   2197 
   2198   unsigned NumElts1 = VecTy1->getNumElements();
   2199   unsigned NumElts2 = VecTy2->getNumElements();
   2200   assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
   2201 
   2202   if (NumElts1 > NumElts2) {
   2203     // Extend with UNDEFs.
   2204     Constant *ExtMask =
   2205         getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
   2206     V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
   2207   }
   2208 
   2209   Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
   2210   return Builder.CreateShuffleVector(V1, V2, Mask);
   2211 }
   2212 
   2213 // Concatenate vectors in the given list. All vectors have the same type.
   2214 static Value *ConcatenateVectors(IRBuilder<> &Builder,
   2215                                  ArrayRef<Value *> InputList) {
   2216   unsigned NumVec = InputList.size();
   2217   assert(NumVec > 1 && "Should be at least two vectors");
   2218 
   2219   SmallVector<Value *, 8> ResList;
   2220   ResList.append(InputList.begin(), InputList.end());
   2221   do {
   2222     SmallVector<Value *, 8> TmpList;
   2223     for (unsigned i = 0; i < NumVec - 1; i += 2) {
   2224       Value *V0 = ResList[i], *V1 = ResList[i + 1];
   2225       assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
   2226              "Only the last vector may have a different type");
   2227 
   2228       TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
   2229     }
   2230 
   2231     // Push the last vector if the total number of vectors is odd.
   2232     if (NumVec % 2 != 0)
   2233       TmpList.push_back(ResList[NumVec - 1]);
   2234 
   2235     ResList = TmpList;
   2236     NumVec = ResList.size();
   2237   } while (NumVec > 1);
   2238 
   2239   return ResList[0];
   2240 }
   2241 
   2242 // Try to vectorize the interleave group that \p Instr belongs to.
   2243 //
   2244 // E.g. Translate following interleaved load group (factor = 3):
   2245 //   for (i = 0; i < N; i+=3) {
   2246 //     R = Pic[i];             // Member of index 0
   2247 //     G = Pic[i+1];           // Member of index 1
   2248 //     B = Pic[i+2];           // Member of index 2
   2249 //     ... // do something to R, G, B
   2250 //   }
   2251 // To:
   2252 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
   2253 //   %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9>   ; R elements
   2254 //   %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10>  ; G elements
   2255 //   %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11>  ; B elements
   2256 //
   2257 // Or translate following interleaved store group (factor = 3):
   2258 //   for (i = 0; i < N; i+=3) {
   2259 //     ... do something to R, G, B
   2260 //     Pic[i]   = R;           // Member of index 0
   2261 //     Pic[i+1] = G;           // Member of index 1
   2262 //     Pic[i+2] = B;           // Member of index 2
   2263 //   }
   2264 // To:
   2265 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
   2266 //   %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
   2267 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
   2268 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
   2269 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
   2270 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
   2271   const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
   2272   assert(Group && "Fail to get an interleaved access group.");
   2273 
   2274   // Skip if current instruction is not the insert position.
   2275   if (Instr != Group->getInsertPos())
   2276     return;
   2277 
   2278   LoadInst *LI = dyn_cast<LoadInst>(Instr);
   2279   StoreInst *SI = dyn_cast<StoreInst>(Instr);
   2280   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
   2281 
   2282   // Prepare for the vector type of the interleaved load/store.
   2283   Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
   2284   unsigned InterleaveFactor = Group->getFactor();
   2285   Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
   2286   Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
   2287 
   2288   // Prepare for the new pointers.
   2289   setDebugLocFromInst(Builder, Ptr);
   2290   VectorParts &PtrParts = getVectorValue(Ptr);
   2291   SmallVector<Value *, 2> NewPtrs;
   2292   unsigned Index = Group->getIndex(Instr);
   2293   for (unsigned Part = 0; Part < UF; Part++) {
   2294     // Extract the pointer for current instruction from the pointer vector. A
   2295     // reverse access uses the pointer in the last lane.
   2296     Value *NewPtr = Builder.CreateExtractElement(
   2297         PtrParts[Part],
   2298         Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
   2299 
   2300     // Notice current instruction could be any index. Need to adjust the address
   2301     // to the member of index 0.
   2302     //
   2303     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
   2304     //       b = A[i];       // Member of index 0
   2305     // Current pointer is pointed to A[i+1], adjust it to A[i].
   2306     //
   2307     // E.g.  A[i+1] = a;     // Member of index 1
   2308     //       A[i]   = b;     // Member of index 0
   2309     //       A[i+2] = c;     // Member of index 2 (Current instruction)
   2310     // Current pointer is pointed to A[i+2], adjust it to A[i].
   2311     NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
   2312 
   2313     // Cast to the vector pointer type.
   2314     NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
   2315   }
   2316 
   2317   setDebugLocFromInst(Builder, Instr);
   2318   Value *UndefVec = UndefValue::get(VecTy);
   2319 
   2320   // Vectorize the interleaved load group.
   2321   if (LI) {
   2322     for (unsigned Part = 0; Part < UF; Part++) {
   2323       Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
   2324           NewPtrs[Part], Group->getAlignment(), "wide.vec");
   2325 
   2326       for (unsigned i = 0; i < InterleaveFactor; i++) {
   2327         Instruction *Member = Group->getMember(i);
   2328 
   2329         // Skip the gaps in the group.
   2330         if (!Member)
   2331           continue;
   2332 
   2333         Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
   2334         Value *StridedVec = Builder.CreateShuffleVector(
   2335             NewLoadInstr, UndefVec, StrideMask, "strided.vec");
   2336 
   2337         // If this member has different type, cast the result type.
   2338         if (Member->getType() != ScalarTy) {
   2339           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
   2340           StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
   2341         }
   2342 
   2343         VectorParts &Entry = WidenMap.get(Member);
   2344         Entry[Part] =
   2345             Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
   2346       }
   2347 
   2348       addMetadata(NewLoadInstr, Instr);
   2349     }
   2350     return;
   2351   }
   2352 
   2353   // The sub vector type for current instruction.
   2354   VectorType *SubVT = VectorType::get(ScalarTy, VF);
   2355 
   2356   // Vectorize the interleaved store group.
   2357   for (unsigned Part = 0; Part < UF; Part++) {
   2358     // Collect the stored vector from each member.
   2359     SmallVector<Value *, 4> StoredVecs;
   2360     for (unsigned i = 0; i < InterleaveFactor; i++) {
   2361       // Interleaved store group doesn't allow a gap, so each index has a member
   2362       Instruction *Member = Group->getMember(i);
   2363       assert(Member && "Fail to get a member from an interleaved store group");
   2364 
   2365       Value *StoredVec =
   2366           getVectorValue(cast<StoreInst>(Member)->getValueOperand())[Part];
   2367       if (Group->isReverse())
   2368         StoredVec = reverseVector(StoredVec);
   2369 
   2370       // If this member has different type, cast it to an unified type.
   2371       if (StoredVec->getType() != SubVT)
   2372         StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
   2373 
   2374       StoredVecs.push_back(StoredVec);
   2375     }
   2376 
   2377     // Concatenate all vectors into a wide vector.
   2378     Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
   2379 
   2380     // Interleave the elements in the wide vector.
   2381     Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
   2382     Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
   2383                                               "interleaved.vec");
   2384 
   2385     Instruction *NewStoreInstr =
   2386         Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
   2387     addMetadata(NewStoreInstr, Instr);
   2388   }
   2389 }
   2390 
   2391 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
   2392   // Attempt to issue a wide load.
   2393   LoadInst *LI = dyn_cast<LoadInst>(Instr);
   2394   StoreInst *SI = dyn_cast<StoreInst>(Instr);
   2395 
   2396   assert((LI || SI) && "Invalid Load/Store instruction");
   2397 
   2398   // Try to vectorize the interleave group if this access is interleaved.
   2399   if (Legal->isAccessInterleaved(Instr))
   2400     return vectorizeInterleaveGroup(Instr);
   2401 
   2402   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
   2403   Type *DataTy = VectorType::get(ScalarDataTy, VF);
   2404   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
   2405   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
   2406   // An alignment of 0 means target abi alignment. We need to use the scalar's
   2407   // target abi alignment in such a case.
   2408   const DataLayout &DL = Instr->getModule()->getDataLayout();
   2409   if (!Alignment)
   2410     Alignment = DL.getABITypeAlignment(ScalarDataTy);
   2411   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
   2412   uint64_t ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
   2413   uint64_t VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
   2414 
   2415   if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
   2416       !Legal->isMaskRequired(SI))
   2417     return scalarizeInstruction(Instr, true);
   2418 
   2419   if (ScalarAllocatedSize != VectorElementSize)
   2420     return scalarizeInstruction(Instr);
   2421 
   2422   // If the pointer is loop invariant scalarize the load.
   2423   if (LI && Legal->isUniform(Ptr))
   2424     return scalarizeInstruction(Instr);
   2425 
   2426   // If the pointer is non-consecutive and gather/scatter is not supported
   2427   // scalarize the instruction.
   2428   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
   2429   bool Reverse = ConsecutiveStride < 0;
   2430   bool CreateGatherScatter =
   2431       !ConsecutiveStride && ((LI && Legal->isLegalMaskedGather(ScalarDataTy)) ||
   2432                              (SI && Legal->isLegalMaskedScatter(ScalarDataTy)));
   2433 
   2434   if (!ConsecutiveStride && !CreateGatherScatter)
   2435     return scalarizeInstruction(Instr);
   2436 
   2437   Constant *Zero = Builder.getInt32(0);
   2438   VectorParts &Entry = WidenMap.get(Instr);
   2439   VectorParts VectorGep;
   2440 
   2441   // Handle consecutive loads/stores.
   2442   GetElementPtrInst *Gep = getGEPInstruction(Ptr);
   2443   if (ConsecutiveStride) {
   2444     if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
   2445       setDebugLocFromInst(Builder, Gep);
   2446       Value *PtrOperand = Gep->getPointerOperand();
   2447       Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
   2448       FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
   2449 
   2450       // Create the new GEP with the new induction variable.
   2451       GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
   2452       Gep2->setOperand(0, FirstBasePtr);
   2453       Gep2->setName("gep.indvar.base");
   2454       Ptr = Builder.Insert(Gep2);
   2455     } else if (Gep) {
   2456       setDebugLocFromInst(Builder, Gep);
   2457       assert(PSE.getSE()->isLoopInvariant(PSE.getSCEV(Gep->getPointerOperand()),
   2458                                           OrigLoop) &&
   2459              "Base ptr must be invariant");
   2460       // The last index does not have to be the induction. It can be
   2461       // consecutive and be a function of the index. For example A[I+1];
   2462       unsigned NumOperands = Gep->getNumOperands();
   2463       unsigned InductionOperand = getGEPInductionOperand(Gep);
   2464       // Create the new GEP with the new induction variable.
   2465       GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
   2466 
   2467       for (unsigned i = 0; i < NumOperands; ++i) {
   2468         Value *GepOperand = Gep->getOperand(i);
   2469         Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
   2470 
   2471         // Update last index or loop invariant instruction anchored in loop.
   2472         if (i == InductionOperand ||
   2473             (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
   2474           assert((i == InductionOperand ||
   2475                   PSE.getSE()->isLoopInvariant(PSE.getSCEV(GepOperandInst),
   2476                                                OrigLoop)) &&
   2477                  "Must be last index or loop invariant");
   2478 
   2479           VectorParts &GEPParts = getVectorValue(GepOperand);
   2480 
   2481           // If GepOperand is an induction variable, and there's a scalarized
   2482           // version of it available, use it. Otherwise, we will need to create
   2483           // an extractelement instruction.
   2484           Value *Index = ScalarIVMap.count(GepOperand)
   2485                              ? ScalarIVMap[GepOperand][0]
   2486                              : Builder.CreateExtractElement(GEPParts[0], Zero);
   2487 
   2488           Gep2->setOperand(i, Index);
   2489           Gep2->setName("gep.indvar.idx");
   2490         }
   2491       }
   2492       Ptr = Builder.Insert(Gep2);
   2493     } else { // No GEP
   2494       // Use the induction element ptr.
   2495       assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
   2496       setDebugLocFromInst(Builder, Ptr);
   2497       VectorParts &PtrVal = getVectorValue(Ptr);
   2498       Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
   2499     }
   2500   } else {
   2501     // At this point we should vector version of GEP for Gather or Scatter
   2502     assert(CreateGatherScatter && "The instruction should be scalarized");
   2503     if (Gep) {
   2504       // Vectorizing GEP, across UF parts. We want to get a vector value for base
   2505       // and each index that's defined inside the loop, even if it is
   2506       // loop-invariant but wasn't hoisted out. Otherwise we want to keep them
   2507       // scalar.
   2508       SmallVector<VectorParts, 4> OpsV;
   2509       for (Value *Op : Gep->operands()) {
   2510         Instruction *SrcInst = dyn_cast<Instruction>(Op);
   2511         if (SrcInst && OrigLoop->contains(SrcInst))
   2512           OpsV.push_back(getVectorValue(Op));
   2513         else
   2514           OpsV.push_back(VectorParts(UF, Op));
   2515       }
   2516       for (unsigned Part = 0; Part < UF; ++Part) {
   2517         SmallVector<Value *, 4> Ops;
   2518         Value *GEPBasePtr = OpsV[0][Part];
   2519         for (unsigned i = 1; i < Gep->getNumOperands(); i++)
   2520           Ops.push_back(OpsV[i][Part]);
   2521         Value *NewGep =  Builder.CreateGEP(GEPBasePtr, Ops, "VectorGep");
   2522         cast<GetElementPtrInst>(NewGep)->setIsInBounds(Gep->isInBounds());
   2523         assert(NewGep->getType()->isVectorTy() && "Expected vector GEP");
   2524 
   2525         NewGep =
   2526             Builder.CreateBitCast(NewGep, VectorType::get(Ptr->getType(), VF));
   2527         VectorGep.push_back(NewGep);
   2528       }
   2529     } else
   2530       VectorGep = getVectorValue(Ptr);
   2531   }
   2532 
   2533   VectorParts Mask = createBlockInMask(Instr->getParent());
   2534   // Handle Stores:
   2535   if (SI) {
   2536     assert(!Legal->isUniform(SI->getPointerOperand()) &&
   2537            "We do not allow storing to uniform addresses");
   2538     setDebugLocFromInst(Builder, SI);
   2539     // We don't want to update the value in the map as it might be used in
   2540     // another expression. So don't use a reference type for "StoredVal".
   2541     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
   2542 
   2543     for (unsigned Part = 0; Part < UF; ++Part) {
   2544       Instruction *NewSI = nullptr;
   2545       if (CreateGatherScatter) {
   2546         Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr;
   2547         NewSI = Builder.CreateMaskedScatter(StoredVal[Part], VectorGep[Part],
   2548                                             Alignment, MaskPart);
   2549       } else {
   2550         // Calculate the pointer for the specific unroll-part.
   2551         Value *PartPtr =
   2552             Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
   2553 
   2554         if (Reverse) {
   2555           // If we store to reverse consecutive memory locations, then we need
   2556           // to reverse the order of elements in the stored value.
   2557           StoredVal[Part] = reverseVector(StoredVal[Part]);
   2558           // If the address is consecutive but reversed, then the
   2559           // wide store needs to start at the last vector element.
   2560           PartPtr =
   2561               Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
   2562           PartPtr =
   2563               Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
   2564           Mask[Part] = reverseVector(Mask[Part]);
   2565         }
   2566 
   2567         Value *VecPtr =
   2568             Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
   2569 
   2570         if (Legal->isMaskRequired(SI))
   2571           NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
   2572                                             Mask[Part]);
   2573         else
   2574           NewSI =
   2575               Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
   2576       }
   2577       addMetadata(NewSI, SI);
   2578     }
   2579     return;
   2580   }
   2581 
   2582   // Handle loads.
   2583   assert(LI && "Must have a load instruction");
   2584   setDebugLocFromInst(Builder, LI);
   2585   for (unsigned Part = 0; Part < UF; ++Part) {
   2586     Instruction *NewLI;
   2587     if (CreateGatherScatter) {
   2588       Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr;
   2589       NewLI = Builder.CreateMaskedGather(VectorGep[Part], Alignment, MaskPart,
   2590                                          0, "wide.masked.gather");
   2591       Entry[Part] = NewLI;
   2592     } else {
   2593       // Calculate the pointer for the specific unroll-part.
   2594       Value *PartPtr =
   2595           Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
   2596 
   2597       if (Reverse) {
   2598         // If the address is consecutive but reversed, then the
   2599         // wide load needs to start at the last vector element.
   2600         PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
   2601         PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
   2602         Mask[Part] = reverseVector(Mask[Part]);
   2603       }
   2604 
   2605       Value *VecPtr =
   2606           Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
   2607       if (Legal->isMaskRequired(LI))
   2608         NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
   2609                                          UndefValue::get(DataTy),
   2610                                          "wide.masked.load");
   2611       else
   2612         NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
   2613       Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
   2614     }
   2615     addMetadata(NewLI, LI);
   2616   }
   2617 }
   2618 
   2619 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
   2620                                                bool IfPredicateStore) {
   2621   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
   2622   // Holds vector parameters or scalars, in case of uniform vals.
   2623   SmallVector<VectorParts, 4> Params;
   2624 
   2625   setDebugLocFromInst(Builder, Instr);
   2626 
   2627   // Find all of the vectorized parameters.
   2628   for (Value *SrcOp : Instr->operands()) {
   2629     // If we are accessing the old induction variable, use the new one.
   2630     if (SrcOp == OldInduction) {
   2631       Params.push_back(getVectorValue(SrcOp));
   2632       continue;
   2633     }
   2634 
   2635     // Try using previously calculated values.
   2636     auto *SrcInst = dyn_cast<Instruction>(SrcOp);
   2637 
   2638     // If the src is an instruction that appeared earlier in the basic block,
   2639     // then it should already be vectorized.
   2640     if (SrcInst && OrigLoop->contains(SrcInst)) {
   2641       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
   2642       // The parameter is a vector value from earlier.
   2643       Params.push_back(WidenMap.get(SrcInst));
   2644     } else {
   2645       // The parameter is a scalar from outside the loop. Maybe even a constant.
   2646       VectorParts Scalars;
   2647       Scalars.append(UF, SrcOp);
   2648       Params.push_back(Scalars);
   2649     }
   2650   }
   2651 
   2652   assert(Params.size() == Instr->getNumOperands() &&
   2653          "Invalid number of operands");
   2654 
   2655   // Does this instruction return a value ?
   2656   bool IsVoidRetTy = Instr->getType()->isVoidTy();
   2657 
   2658   Value *UndefVec =
   2659       IsVoidRetTy ? nullptr
   2660                   : UndefValue::get(VectorType::get(Instr->getType(), VF));
   2661   // Create a new entry in the WidenMap and initialize it to Undef or Null.
   2662   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
   2663 
   2664   VectorParts Cond;
   2665   if (IfPredicateStore) {
   2666     assert(Instr->getParent()->getSinglePredecessor() &&
   2667            "Only support single predecessor blocks");
   2668     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
   2669                           Instr->getParent());
   2670   }
   2671 
   2672   // For each vector unroll 'part':
   2673   for (unsigned Part = 0; Part < UF; ++Part) {
   2674     // For each scalar that we create:
   2675     for (unsigned Width = 0; Width < VF; ++Width) {
   2676 
   2677       // Start if-block.
   2678       Value *Cmp = nullptr;
   2679       if (IfPredicateStore) {
   2680         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
   2681         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp,
   2682                                  ConstantInt::get(Cmp->getType(), 1));
   2683       }
   2684 
   2685       Instruction *Cloned = Instr->clone();
   2686       if (!IsVoidRetTy)
   2687         Cloned->setName(Instr->getName() + ".cloned");
   2688       // Replace the operands of the cloned instructions with extracted scalars.
   2689       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
   2690 
   2691         // If the operand is an induction variable, and there's a scalarized
   2692         // version of it available, use it. Otherwise, we will need to create
   2693         // an extractelement instruction if vectorizing.
   2694         auto *NewOp = Params[op][Part];
   2695         auto *ScalarOp = Instr->getOperand(op);
   2696         if (ScalarIVMap.count(ScalarOp))
   2697           NewOp = ScalarIVMap[ScalarOp][VF * Part + Width];
   2698         else if (NewOp->getType()->isVectorTy())
   2699           NewOp = Builder.CreateExtractElement(NewOp, Builder.getInt32(Width));
   2700         Cloned->setOperand(op, NewOp);
   2701       }
   2702       addNewMetadata(Cloned, Instr);
   2703 
   2704       // Place the cloned scalar in the new loop.
   2705       Builder.Insert(Cloned);
   2706 
   2707       // If we just cloned a new assumption, add it the assumption cache.
   2708       if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
   2709         if (II->getIntrinsicID() == Intrinsic::assume)
   2710           AC->registerAssumption(II);
   2711 
   2712       // If the original scalar returns a value we need to place it in a vector
   2713       // so that future users will be able to use it.
   2714       if (!IsVoidRetTy)
   2715         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
   2716                                                        Builder.getInt32(Width));
   2717       // End if-block.
   2718       if (IfPredicateStore)
   2719         PredicatedStores.push_back(
   2720             std::make_pair(cast<StoreInst>(Cloned), Cmp));
   2721     }
   2722   }
   2723 }
   2724 
   2725 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
   2726                                                       Value *End, Value *Step,
   2727                                                       Instruction *DL) {
   2728   BasicBlock *Header = L->getHeader();
   2729   BasicBlock *Latch = L->getLoopLatch();
   2730   // As we're just creating this loop, it's possible no latch exists
   2731   // yet. If so, use the header as this will be a single block loop.
   2732   if (!Latch)
   2733     Latch = Header;
   2734 
   2735   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
   2736   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
   2737   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
   2738 
   2739   Builder.SetInsertPoint(Latch->getTerminator());
   2740 
   2741   // Create i+1 and fill the PHINode.
   2742   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
   2743   Induction->addIncoming(Start, L->getLoopPreheader());
   2744   Induction->addIncoming(Next, Latch);
   2745   // Create the compare.
   2746   Value *ICmp = Builder.CreateICmpEQ(Next, End);
   2747   Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
   2748 
   2749   // Now we have two terminators. Remove the old one from the block.
   2750   Latch->getTerminator()->eraseFromParent();
   2751 
   2752   return Induction;
   2753 }
   2754 
   2755 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
   2756   if (TripCount)
   2757     return TripCount;
   2758 
   2759   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
   2760   // Find the loop boundaries.
   2761   ScalarEvolution *SE = PSE.getSE();
   2762   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
   2763   assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
   2764          "Invalid loop count");
   2765 
   2766   Type *IdxTy = Legal->getWidestInductionType();
   2767 
   2768   // The exit count might have the type of i64 while the phi is i32. This can
   2769   // happen if we have an induction variable that is sign extended before the
   2770   // compare. The only way that we get a backedge taken count is that the
   2771   // induction variable was signed and as such will not overflow. In such a case
   2772   // truncation is legal.
   2773   if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
   2774       IdxTy->getPrimitiveSizeInBits())
   2775     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
   2776   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
   2777 
   2778   // Get the total trip count from the count by adding 1.
   2779   const SCEV *ExitCount = SE->getAddExpr(
   2780       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
   2781 
   2782   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
   2783 
   2784   // Expand the trip count and place the new instructions in the preheader.
   2785   // Notice that the pre-header does not change, only the loop body.
   2786   SCEVExpander Exp(*SE, DL, "induction");
   2787 
   2788   // Count holds the overall loop count (N).
   2789   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
   2790                                 L->getLoopPreheader()->getTerminator());
   2791 
   2792   if (TripCount->getType()->isPointerTy())
   2793     TripCount =
   2794         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
   2795                                     L->getLoopPreheader()->getTerminator());
   2796 
   2797   return TripCount;
   2798 }
   2799 
   2800 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
   2801   if (VectorTripCount)
   2802     return VectorTripCount;
   2803 
   2804   Value *TC = getOrCreateTripCount(L);
   2805   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
   2806 
   2807   // Now we need to generate the expression for the part of the loop that the
   2808   // vectorized body will execute. This is equal to N - (N % Step) if scalar
   2809   // iterations are not required for correctness, or N - Step, otherwise. Step
   2810   // is equal to the vectorization factor (number of SIMD elements) times the
   2811   // unroll factor (number of SIMD instructions).
   2812   Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
   2813   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
   2814 
   2815   // If there is a non-reversed interleaved group that may speculatively access
   2816   // memory out-of-bounds, we need to ensure that there will be at least one
   2817   // iteration of the scalar epilogue loop. Thus, if the step evenly divides
   2818   // the trip count, we set the remainder to be equal to the step. If the step
   2819   // does not evenly divide the trip count, no adjustment is necessary since
   2820   // there will already be scalar iterations. Note that the minimum iterations
   2821   // check ensures that N >= Step.
   2822   if (VF > 1 && Legal->requiresScalarEpilogue()) {
   2823     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
   2824     R = Builder.CreateSelect(IsZero, Step, R);
   2825   }
   2826 
   2827   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
   2828 
   2829   return VectorTripCount;
   2830 }
   2831 
   2832 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
   2833                                                          BasicBlock *Bypass) {
   2834   Value *Count = getOrCreateTripCount(L);
   2835   BasicBlock *BB = L->getLoopPreheader();
   2836   IRBuilder<> Builder(BB->getTerminator());
   2837 
   2838   // Generate code to check that the loop's trip count that we computed by
   2839   // adding one to the backedge-taken count will not overflow.
   2840   Value *CheckMinIters = Builder.CreateICmpULT(
   2841       Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
   2842 
   2843   BasicBlock *NewBB =
   2844       BB->splitBasicBlock(BB->getTerminator(), "min.iters.checked");
   2845   // Update dominator tree immediately if the generated block is a
   2846   // LoopBypassBlock because SCEV expansions to generate loop bypass
   2847   // checks may query it before the current function is finished.
   2848   DT->addNewBlock(NewBB, BB);
   2849   if (L->getParentLoop())
   2850     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
   2851   ReplaceInstWithInst(BB->getTerminator(),
   2852                       BranchInst::Create(Bypass, NewBB, CheckMinIters));
   2853   LoopBypassBlocks.push_back(BB);
   2854 }
   2855 
   2856 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
   2857                                                      BasicBlock *Bypass) {
   2858   Value *TC = getOrCreateVectorTripCount(L);
   2859   BasicBlock *BB = L->getLoopPreheader();
   2860   IRBuilder<> Builder(BB->getTerminator());
   2861 
   2862   // Now, compare the new count to zero. If it is zero skip the vector loop and
   2863   // jump to the scalar loop.
   2864   Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
   2865                                     "cmp.zero");
   2866 
   2867   // Generate code to check that the loop's trip count that we computed by
   2868   // adding one to the backedge-taken count will not overflow.
   2869   BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
   2870   // Update dominator tree immediately if the generated block is a
   2871   // LoopBypassBlock because SCEV expansions to generate loop bypass
   2872   // checks may query it before the current function is finished.
   2873   DT->addNewBlock(NewBB, BB);
   2874   if (L->getParentLoop())
   2875     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
   2876   ReplaceInstWithInst(BB->getTerminator(),
   2877                       BranchInst::Create(Bypass, NewBB, Cmp));
   2878   LoopBypassBlocks.push_back(BB);
   2879 }
   2880 
   2881 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
   2882   BasicBlock *BB = L->getLoopPreheader();
   2883 
   2884   // Generate the code to check that the SCEV assumptions that we made.
   2885   // We want the new basic block to start at the first instruction in a
   2886   // sequence of instructions that form a check.
   2887   SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
   2888                    "scev.check");
   2889   Value *SCEVCheck =
   2890       Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
   2891 
   2892   if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
   2893     if (C->isZero())
   2894       return;
   2895 
   2896   // Create a new block containing the stride check.
   2897   BB->setName("vector.scevcheck");
   2898   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
   2899   // Update dominator tree immediately if the generated block is a
   2900   // LoopBypassBlock because SCEV expansions to generate loop bypass
   2901   // checks may query it before the current function is finished.
   2902   DT->addNewBlock(NewBB, BB);
   2903   if (L->getParentLoop())
   2904     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
   2905   ReplaceInstWithInst(BB->getTerminator(),
   2906                       BranchInst::Create(Bypass, NewBB, SCEVCheck));
   2907   LoopBypassBlocks.push_back(BB);
   2908   AddedSafetyChecks = true;
   2909 }
   2910 
   2911 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
   2912   BasicBlock *BB = L->getLoopPreheader();
   2913 
   2914   // Generate the code that checks in runtime if arrays overlap. We put the
   2915   // checks into a separate block to make the more common case of few elements
   2916   // faster.
   2917   Instruction *FirstCheckInst;
   2918   Instruction *MemRuntimeCheck;
   2919   std::tie(FirstCheckInst, MemRuntimeCheck) =
   2920       Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
   2921   if (!MemRuntimeCheck)
   2922     return;
   2923 
   2924   // Create a new block containing the memory check.
   2925   BB->setName("vector.memcheck");
   2926   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
   2927   // Update dominator tree immediately if the generated block is a
   2928   // LoopBypassBlock because SCEV expansions to generate loop bypass
   2929   // checks may query it before the current function is finished.
   2930   DT->addNewBlock(NewBB, BB);
   2931   if (L->getParentLoop())
   2932     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
   2933   ReplaceInstWithInst(BB->getTerminator(),
   2934                       BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
   2935   LoopBypassBlocks.push_back(BB);
   2936   AddedSafetyChecks = true;
   2937 
   2938   // We currently don't use LoopVersioning for the actual loop cloning but we
   2939   // still use it to add the noalias metadata.
   2940   LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
   2941                                            PSE.getSE());
   2942   LVer->prepareNoAliasMetadata();
   2943 }
   2944 
   2945 void InnerLoopVectorizer::createEmptyLoop() {
   2946   /*
   2947    In this function we generate a new loop. The new loop will contain
   2948    the vectorized instructions while the old loop will continue to run the
   2949    scalar remainder.
   2950 
   2951        [ ] <-- loop iteration number check.
   2952     /   |
   2953    /    v
   2954   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
   2955   |  /  |
   2956   | /   v
   2957   ||   [ ]     <-- vector pre header.
   2958   |/    |
   2959   |     v
   2960   |    [  ] \
   2961   |    [  ]_|   <-- vector loop.
   2962   |     |
   2963   |     v
   2964   |   -[ ]   <--- middle-block.
   2965   |  /  |
   2966   | /   v
   2967   -|- >[ ]     <--- new preheader.
   2968    |    |
   2969    |    v
   2970    |   [ ] \
   2971    |   [ ]_|   <-- old scalar loop to handle remainder.
   2972     \   |
   2973      \  v
   2974       >[ ]     <-- exit block.
   2975    ...
   2976    */
   2977 
   2978   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
   2979   BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
   2980   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
   2981   assert(VectorPH && "Invalid loop structure");
   2982   assert(ExitBlock && "Must have an exit block");
   2983 
   2984   // Some loops have a single integer induction variable, while other loops
   2985   // don't. One example is c++ iterators that often have multiple pointer
   2986   // induction variables. In the code below we also support a case where we
   2987   // don't have a single induction variable.
   2988   //
   2989   // We try to obtain an induction variable from the original loop as hard
   2990   // as possible. However if we don't find one that:
   2991   //   - is an integer
   2992   //   - counts from zero, stepping by one
   2993   //   - is the size of the widest induction variable type
   2994   // then we create a new one.
   2995   OldInduction = Legal->getInduction();
   2996   Type *IdxTy = Legal->getWidestInductionType();
   2997 
   2998   // Split the single block loop into the two loop structure described above.
   2999   BasicBlock *VecBody =
   3000       VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
   3001   BasicBlock *MiddleBlock =
   3002       VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
   3003   BasicBlock *ScalarPH =
   3004       MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
   3005 
   3006   // Create and register the new vector loop.
   3007   Loop *Lp = new Loop();
   3008   Loop *ParentLoop = OrigLoop->getParentLoop();
   3009 
   3010   // Insert the new loop into the loop nest and register the new basic blocks
   3011   // before calling any utilities such as SCEV that require valid LoopInfo.
   3012   if (ParentLoop) {
   3013     ParentLoop->addChildLoop(Lp);
   3014     ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
   3015     ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
   3016   } else {
   3017     LI->addTopLevelLoop(Lp);
   3018   }
   3019   Lp->addBasicBlockToLoop(VecBody, *LI);
   3020 
   3021   // Find the loop boundaries.
   3022   Value *Count = getOrCreateTripCount(Lp);
   3023 
   3024   Value *StartIdx = ConstantInt::get(IdxTy, 0);
   3025 
   3026   // We need to test whether the backedge-taken count is uint##_max. Adding one
   3027   // to it will cause overflow and an incorrect loop trip count in the vector
   3028   // body. In case of overflow we want to directly jump to the scalar remainder
   3029   // loop.
   3030   emitMinimumIterationCountCheck(Lp, ScalarPH);
   3031   // Now, compare the new count to zero. If it is zero skip the vector loop and
   3032   // jump to the scalar loop.
   3033   emitVectorLoopEnteredCheck(Lp, ScalarPH);
   3034   // Generate the code to check any assumptions that we've made for SCEV
   3035   // expressions.
   3036   emitSCEVChecks(Lp, ScalarPH);
   3037 
   3038   // Generate the code that checks in runtime if arrays overlap. We put the
   3039   // checks into a separate block to make the more common case of few elements
   3040   // faster.
   3041   emitMemRuntimeChecks(Lp, ScalarPH);
   3042 
   3043   // Generate the induction variable.
   3044   // The loop step is equal to the vectorization factor (num of SIMD elements)
   3045   // times the unroll factor (num of SIMD instructions).
   3046   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
   3047   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
   3048   Induction =
   3049       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
   3050                               getDebugLocFromInstOrOperands(OldInduction));
   3051 
   3052   // We are going to resume the execution of the scalar loop.
   3053   // Go over all of the induction variables that we found and fix the
   3054   // PHIs that are left in the scalar version of the loop.
   3055   // The starting values of PHI nodes depend on the counter of the last
   3056   // iteration in the vectorized loop.
   3057   // If we come from a bypass edge then we need to start from the original
   3058   // start value.
   3059 
   3060   // This variable saves the new starting index for the scalar loop. It is used
   3061   // to test if there are any tail iterations left once the vector loop has
   3062   // completed.
   3063   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
   3064   for (auto &InductionEntry : *List) {
   3065     PHINode *OrigPhi = InductionEntry.first;
   3066     InductionDescriptor II = InductionEntry.second;
   3067 
   3068     // Create phi nodes to merge from the  backedge-taken check block.
   3069     PHINode *BCResumeVal = PHINode::Create(
   3070         OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
   3071     Value *EndValue;
   3072     if (OrigPhi == OldInduction) {
   3073       // We know what the end value is.
   3074       EndValue = CountRoundDown;
   3075     } else {
   3076       IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
   3077       Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
   3078                                        II.getStep()->getType(), "cast.crd");
   3079       const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
   3080       EndValue = II.transform(B, CRD, PSE.getSE(), DL);
   3081       EndValue->setName("ind.end");
   3082     }
   3083 
   3084     // The new PHI merges the original incoming value, in case of a bypass,
   3085     // or the value at the end of the vectorized loop.
   3086     BCResumeVal->addIncoming(EndValue, MiddleBlock);
   3087 
   3088     // Fix up external users of the induction variable.
   3089     fixupIVUsers(OrigPhi, II, CountRoundDown, EndValue, MiddleBlock);
   3090 
   3091     // Fix the scalar body counter (PHI node).
   3092     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
   3093 
   3094     // The old induction's phi node in the scalar body needs the truncated
   3095     // value.
   3096     for (BasicBlock *BB : LoopBypassBlocks)
   3097       BCResumeVal->addIncoming(II.getStartValue(), BB);
   3098     OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
   3099   }
   3100 
   3101   // Add a check in the middle block to see if we have completed
   3102   // all of the iterations in the first vector loop.
   3103   // If (N - N%VF) == N, then we *don't* need to run the remainder.
   3104   Value *CmpN =
   3105       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
   3106                       CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
   3107   ReplaceInstWithInst(MiddleBlock->getTerminator(),
   3108                       BranchInst::Create(ExitBlock, ScalarPH, CmpN));
   3109 
   3110   // Get ready to start creating new instructions into the vectorized body.
   3111   Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
   3112 
   3113   // Save the state.
   3114   LoopVectorPreHeader = Lp->getLoopPreheader();
   3115   LoopScalarPreHeader = ScalarPH;
   3116   LoopMiddleBlock = MiddleBlock;
   3117   LoopExitBlock = ExitBlock;
   3118   LoopVectorBody = VecBody;
   3119   LoopScalarBody = OldBasicBlock;
   3120 
   3121   // Keep all loop hints from the original loop on the vector loop (we'll
   3122   // replace the vectorizer-specific hints below).
   3123   if (MDNode *LID = OrigLoop->getLoopID())
   3124     Lp->setLoopID(LID);
   3125 
   3126   LoopVectorizeHints Hints(Lp, true);
   3127   Hints.setAlreadyVectorized();
   3128 }
   3129 
   3130 // Fix up external users of the induction variable. At this point, we are
   3131 // in LCSSA form, with all external PHIs that use the IV having one input value,
   3132 // coming from the remainder loop. We need those PHIs to also have a correct
   3133 // value for the IV when arriving directly from the middle block.
   3134 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
   3135                                        const InductionDescriptor &II,
   3136                                        Value *CountRoundDown, Value *EndValue,
   3137                                        BasicBlock *MiddleBlock) {
   3138   // There are two kinds of external IV usages - those that use the value
   3139   // computed in the last iteration (the PHI) and those that use the penultimate
   3140   // value (the value that feeds into the phi from the loop latch).
   3141   // We allow both, but they, obviously, have different values.
   3142 
   3143   assert(OrigLoop->getExitBlock() && "Expected a single exit block");
   3144 
   3145   DenseMap<Value *, Value *> MissingVals;
   3146 
   3147   // An external user of the last iteration's value should see the value that
   3148   // the remainder loop uses to initialize its own IV.
   3149   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
   3150   for (User *U : PostInc->users()) {
   3151     Instruction *UI = cast<Instruction>(U);
   3152     if (!OrigLoop->contains(UI)) {
   3153       assert(isa<PHINode>(UI) && "Expected LCSSA form");
   3154       MissingVals[UI] = EndValue;
   3155     }
   3156   }
   3157 
   3158   // An external user of the penultimate value need to see EndValue - Step.
   3159   // The simplest way to get this is to recompute it from the constituent SCEVs,
   3160   // that is Start + (Step * (CRD - 1)).
   3161   for (User *U : OrigPhi->users()) {
   3162     auto *UI = cast<Instruction>(U);
   3163     if (!OrigLoop->contains(UI)) {
   3164       const DataLayout &DL =
   3165           OrigLoop->getHeader()->getModule()->getDataLayout();
   3166       assert(isa<PHINode>(UI) && "Expected LCSSA form");
   3167 
   3168       IRBuilder<> B(MiddleBlock->getTerminator());
   3169       Value *CountMinusOne = B.CreateSub(
   3170           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
   3171       Value *CMO = B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType(),
   3172                                        "cast.cmo");
   3173       Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
   3174       Escape->setName("ind.escape");
   3175       MissingVals[UI] = Escape;
   3176     }
   3177   }
   3178 
   3179   for (auto &I : MissingVals) {
   3180     PHINode *PHI = cast<PHINode>(I.first);
   3181     // One corner case we have to handle is two IVs "chasing" each-other,
   3182     // that is %IV2 = phi [...], [ %IV1, %latch ]
   3183     // In this case, if IV1 has an external use, we need to avoid adding both
   3184     // "last value of IV1" and "penultimate value of IV2". So, verify that we
   3185     // don't already have an incoming value for the middle block.
   3186     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
   3187       PHI->addIncoming(I.second, MiddleBlock);
   3188   }
   3189 }
   3190 
   3191 namespace {
   3192 struct CSEDenseMapInfo {
   3193   static bool canHandle(Instruction *I) {
   3194     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
   3195            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
   3196   }
   3197   static inline Instruction *getEmptyKey() {
   3198     return DenseMapInfo<Instruction *>::getEmptyKey();
   3199   }
   3200   static inline Instruction *getTombstoneKey() {
   3201     return DenseMapInfo<Instruction *>::getTombstoneKey();
   3202   }
   3203   static unsigned getHashValue(Instruction *I) {
   3204     assert(canHandle(I) && "Unknown instruction!");
   3205     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
   3206                                                            I->value_op_end()));
   3207   }
   3208   static bool isEqual(Instruction *LHS, Instruction *RHS) {
   3209     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
   3210         LHS == getTombstoneKey() || RHS == getTombstoneKey())
   3211       return LHS == RHS;
   3212     return LHS->isIdenticalTo(RHS);
   3213   }
   3214 };
   3215 }
   3216 
   3217 ///\brief Perform cse of induction variable instructions.
   3218 static void cse(BasicBlock *BB) {
   3219   // Perform simple cse.
   3220   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
   3221   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
   3222     Instruction *In = &*I++;
   3223 
   3224     if (!CSEDenseMapInfo::canHandle(In))
   3225       continue;
   3226 
   3227     // Check if we can replace this instruction with any of the
   3228     // visited instructions.
   3229     if (Instruction *V = CSEMap.lookup(In)) {
   3230       In->replaceAllUsesWith(V);
   3231       In->eraseFromParent();
   3232       continue;
   3233     }
   3234 
   3235     CSEMap[In] = In;
   3236   }
   3237 }
   3238 
   3239 /// \brief Adds a 'fast' flag to floating point operations.
   3240 static Value *addFastMathFlag(Value *V) {
   3241   if (isa<FPMathOperator>(V)) {
   3242     FastMathFlags Flags;
   3243     Flags.setUnsafeAlgebra();
   3244     cast<Instruction>(V)->setFastMathFlags(Flags);
   3245   }
   3246   return V;
   3247 }
   3248 
   3249 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
   3250 /// the result needs to be inserted and/or extracted from vectors.
   3251 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
   3252                                          const TargetTransformInfo &TTI) {
   3253   if (Ty->isVoidTy())
   3254     return 0;
   3255 
   3256   assert(Ty->isVectorTy() && "Can only scalarize vectors");
   3257   unsigned Cost = 0;
   3258 
   3259   for (unsigned I = 0, E = Ty->getVectorNumElements(); I < E; ++I) {
   3260     if (Insert)
   3261       Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, I);
   3262     if (Extract)
   3263       Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, I);
   3264   }
   3265 
   3266   return Cost;
   3267 }
   3268 
   3269 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
   3270 // Return the cost of the instruction, including scalarization overhead if it's
   3271 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
   3272 // i.e. either vector version isn't available, or is too expensive.
   3273 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
   3274                                   const TargetTransformInfo &TTI,
   3275                                   const TargetLibraryInfo *TLI,
   3276                                   bool &NeedToScalarize) {
   3277   Function *F = CI->getCalledFunction();
   3278   StringRef FnName = CI->getCalledFunction()->getName();
   3279   Type *ScalarRetTy = CI->getType();
   3280   SmallVector<Type *, 4> Tys, ScalarTys;
   3281   for (auto &ArgOp : CI->arg_operands())
   3282     ScalarTys.push_back(ArgOp->getType());
   3283 
   3284   // Estimate cost of scalarized vector call. The source operands are assumed
   3285   // to be vectors, so we need to extract individual elements from there,
   3286   // execute VF scalar calls, and then gather the result into the vector return
   3287   // value.
   3288   unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
   3289   if (VF == 1)
   3290     return ScalarCallCost;
   3291 
   3292   // Compute corresponding vector type for return value and arguments.
   3293   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
   3294   for (Type *ScalarTy : ScalarTys)
   3295     Tys.push_back(ToVectorTy(ScalarTy, VF));
   3296 
   3297   // Compute costs of unpacking argument values for the scalar calls and
   3298   // packing the return values to a vector.
   3299   unsigned ScalarizationCost =
   3300       getScalarizationOverhead(RetTy, true, false, TTI);
   3301   for (Type *Ty : Tys)
   3302     ScalarizationCost += getScalarizationOverhead(Ty, false, true, TTI);
   3303 
   3304   unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
   3305 
   3306   // If we can't emit a vector call for this function, then the currently found
   3307   // cost is the cost we need to return.
   3308   NeedToScalarize = true;
   3309   if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
   3310     return Cost;
   3311 
   3312   // If the corresponding vector cost is cheaper, return its cost.
   3313   unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
   3314   if (VectorCallCost < Cost) {
   3315     NeedToScalarize = false;
   3316     return VectorCallCost;
   3317   }
   3318   return Cost;
   3319 }
   3320 
   3321 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
   3322 // factor VF.  Return the cost of the instruction, including scalarization
   3323 // overhead if it's needed.
   3324 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
   3325                                        const TargetTransformInfo &TTI,
   3326                                        const TargetLibraryInfo *TLI) {
   3327   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
   3328   assert(ID && "Expected intrinsic call!");
   3329 
   3330   Type *RetTy = ToVectorTy(CI->getType(), VF);
   3331   SmallVector<Type *, 4> Tys;
   3332   for (Value *ArgOperand : CI->arg_operands())
   3333     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
   3334 
   3335   FastMathFlags FMF;
   3336   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
   3337     FMF = FPMO->getFastMathFlags();
   3338 
   3339   return TTI.getIntrinsicInstrCost(ID, RetTy, Tys, FMF);
   3340 }
   3341 
   3342 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
   3343   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
   3344   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
   3345   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
   3346 }
   3347 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
   3348   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
   3349   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
   3350   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
   3351 }
   3352 
   3353 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
   3354   // For every instruction `I` in MinBWs, truncate the operands, create a
   3355   // truncated version of `I` and reextend its result. InstCombine runs
   3356   // later and will remove any ext/trunc pairs.
   3357   //
   3358   SmallPtrSet<Value *, 4> Erased;
   3359   for (const auto &KV : *MinBWs) {
   3360     VectorParts &Parts = WidenMap.get(KV.first);
   3361     for (Value *&I : Parts) {
   3362       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
   3363         continue;
   3364       Type *OriginalTy = I->getType();
   3365       Type *ScalarTruncatedTy =
   3366           IntegerType::get(OriginalTy->getContext(), KV.second);
   3367       Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
   3368                                           OriginalTy->getVectorNumElements());
   3369       if (TruncatedTy == OriginalTy)
   3370         continue;
   3371 
   3372       IRBuilder<> B(cast<Instruction>(I));
   3373       auto ShrinkOperand = [&](Value *V) -> Value * {
   3374         if (auto *ZI = dyn_cast<ZExtInst>(V))
   3375           if (ZI->getSrcTy() == TruncatedTy)
   3376             return ZI->getOperand(0);
   3377         return B.CreateZExtOrTrunc(V, TruncatedTy);
   3378       };
   3379 
   3380       // The actual instruction modification depends on the instruction type,
   3381       // unfortunately.
   3382       Value *NewI = nullptr;
   3383       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
   3384         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
   3385                              ShrinkOperand(BO->getOperand(1)));
   3386         cast<BinaryOperator>(NewI)->copyIRFlags(I);
   3387       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
   3388         NewI =
   3389             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
   3390                          ShrinkOperand(CI->getOperand(1)));
   3391       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
   3392         NewI = B.CreateSelect(SI->getCondition(),
   3393                               ShrinkOperand(SI->getTrueValue()),
   3394                               ShrinkOperand(SI->getFalseValue()));
   3395       } else if (auto *CI = dyn_cast<CastInst>(I)) {
   3396         switch (CI->getOpcode()) {
   3397         default:
   3398           llvm_unreachable("Unhandled cast!");
   3399         case Instruction::Trunc:
   3400           NewI = ShrinkOperand(CI->getOperand(0));
   3401           break;
   3402         case Instruction::SExt:
   3403           NewI = B.CreateSExtOrTrunc(
   3404               CI->getOperand(0),
   3405               smallestIntegerVectorType(OriginalTy, TruncatedTy));
   3406           break;
   3407         case Instruction::ZExt:
   3408           NewI = B.CreateZExtOrTrunc(
   3409               CI->getOperand(0),
   3410               smallestIntegerVectorType(OriginalTy, TruncatedTy));
   3411           break;
   3412         }
   3413       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
   3414         auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
   3415         auto *O0 = B.CreateZExtOrTrunc(
   3416             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
   3417         auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
   3418         auto *O1 = B.CreateZExtOrTrunc(
   3419             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
   3420 
   3421         NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
   3422       } else if (isa<LoadInst>(I)) {
   3423         // Don't do anything with the operands, just extend the result.
   3424         continue;
   3425       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
   3426         auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
   3427         auto *O0 = B.CreateZExtOrTrunc(
   3428             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
   3429         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
   3430         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
   3431       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
   3432         auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
   3433         auto *O0 = B.CreateZExtOrTrunc(
   3434             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
   3435         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
   3436       } else {
   3437         llvm_unreachable("Unhandled instruction type!");
   3438       }
   3439 
   3440       // Lastly, extend the result.
   3441       NewI->takeName(cast<Instruction>(I));
   3442       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
   3443       I->replaceAllUsesWith(Res);
   3444       cast<Instruction>(I)->eraseFromParent();
   3445       Erased.insert(I);
   3446       I = Res;
   3447     }
   3448   }
   3449 
   3450   // We'll have created a bunch of ZExts that are now parentless. Clean up.
   3451   for (const auto &KV : *MinBWs) {
   3452     VectorParts &Parts = WidenMap.get(KV.first);
   3453     for (Value *&I : Parts) {
   3454       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
   3455       if (Inst && Inst->use_empty()) {
   3456         Value *NewI = Inst->getOperand(0);
   3457         Inst->eraseFromParent();
   3458         I = NewI;
   3459       }
   3460     }
   3461   }
   3462 }
   3463 
   3464 void InnerLoopVectorizer::vectorizeLoop() {
   3465   //===------------------------------------------------===//
   3466   //
   3467   // Notice: any optimization or new instruction that go
   3468   // into the code below should be also be implemented in
   3469   // the cost-model.
   3470   //
   3471   //===------------------------------------------------===//
   3472   Constant *Zero = Builder.getInt32(0);
   3473 
   3474   // In order to support recurrences we need to be able to vectorize Phi nodes.
   3475   // Phi nodes have cycles, so we need to vectorize them in two stages. First,
   3476   // we create a new vector PHI node with no incoming edges. We use this value
   3477   // when we vectorize all of the instructions that use the PHI. Next, after
   3478   // all of the instructions in the block are complete we add the new incoming
   3479   // edges to the PHI. At this point all of the instructions in the basic block
   3480   // are vectorized, so we can use them to construct the PHI.
   3481   PhiVector PHIsToFix;
   3482 
   3483   // Scan the loop in a topological order to ensure that defs are vectorized
   3484   // before users.
   3485   LoopBlocksDFS DFS(OrigLoop);
   3486   DFS.perform(LI);
   3487 
   3488   // Vectorize all of the blocks in the original loop.
   3489   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
   3490     vectorizeBlockInLoop(BB, &PHIsToFix);
   3491 
   3492   // Insert truncates and extends for any truncated instructions as hints to
   3493   // InstCombine.
   3494   if (VF > 1)
   3495     truncateToMinimalBitwidths();
   3496 
   3497   // At this point every instruction in the original loop is widened to a
   3498   // vector form. Now we need to fix the recurrences in PHIsToFix. These PHI
   3499   // nodes are currently empty because we did not want to introduce cycles.
   3500   // This is the second stage of vectorizing recurrences.
   3501   for (PHINode *Phi : PHIsToFix) {
   3502     assert(Phi && "Unable to recover vectorized PHI");
   3503 
   3504     // Handle first-order recurrences that need to be fixed.
   3505     if (Legal->isFirstOrderRecurrence(Phi)) {
   3506       fixFirstOrderRecurrence(Phi);
   3507       continue;
   3508     }
   3509 
   3510     // If the phi node is not a first-order recurrence, it must be a reduction.
   3511     // Get it's reduction variable descriptor.
   3512     assert(Legal->isReductionVariable(Phi) &&
   3513            "Unable to find the reduction variable");
   3514     RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
   3515 
   3516     RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
   3517     TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
   3518     Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
   3519     RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
   3520         RdxDesc.getMinMaxRecurrenceKind();
   3521     setDebugLocFromInst(Builder, ReductionStartValue);
   3522 
   3523     // We need to generate a reduction vector from the incoming scalar.
   3524     // To do so, we need to generate the 'identity' vector and override
   3525     // one of the elements with the incoming scalar reduction. We need
   3526     // to do it in the vector-loop preheader.
   3527     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
   3528 
   3529     // This is the vector-clone of the value that leaves the loop.
   3530     VectorParts &VectorExit = getVectorValue(LoopExitInst);
   3531     Type *VecTy = VectorExit[0]->getType();
   3532 
   3533     // Find the reduction identity variable. Zero for addition, or, xor,
   3534     // one for multiplication, -1 for And.
   3535     Value *Identity;
   3536     Value *VectorStart;
   3537     if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
   3538         RK == RecurrenceDescriptor::RK_FloatMinMax) {
   3539       // MinMax reduction have the start value as their identify.
   3540       if (VF == 1) {
   3541         VectorStart = Identity = ReductionStartValue;
   3542       } else {
   3543         VectorStart = Identity =
   3544             Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
   3545       }
   3546     } else {
   3547       // Handle other reduction kinds:
   3548       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
   3549           RK, VecTy->getScalarType());
   3550       if (VF == 1) {
   3551         Identity = Iden;
   3552         // This vector is the Identity vector where the first element is the
   3553         // incoming scalar reduction.
   3554         VectorStart = ReductionStartValue;
   3555       } else {
   3556         Identity = ConstantVector::getSplat(VF, Iden);
   3557 
   3558         // This vector is the Identity vector where the first element is the
   3559         // incoming scalar reduction.
   3560         VectorStart =
   3561             Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
   3562       }
   3563     }
   3564 
   3565     // Fix the vector-loop phi.
   3566 
   3567     // Reductions do not have to start at zero. They can start with
   3568     // any loop invariant values.
   3569     VectorParts &VecRdxPhi = WidenMap.get(Phi);
   3570     BasicBlock *Latch = OrigLoop->getLoopLatch();
   3571     Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
   3572     VectorParts &Val = getVectorValue(LoopVal);
   3573     for (unsigned part = 0; part < UF; ++part) {
   3574       // Make sure to add the reduction stat value only to the
   3575       // first unroll part.
   3576       Value *StartVal = (part == 0) ? VectorStart : Identity;
   3577       cast<PHINode>(VecRdxPhi[part])
   3578           ->addIncoming(StartVal, LoopVectorPreHeader);
   3579       cast<PHINode>(VecRdxPhi[part])
   3580           ->addIncoming(Val[part], LoopVectorBody);
   3581     }
   3582 
   3583     // Before each round, move the insertion point right between
   3584     // the PHIs and the values we are going to write.
   3585     // This allows us to write both PHINodes and the extractelement
   3586     // instructions.
   3587     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
   3588 
   3589     VectorParts RdxParts = getVectorValue(LoopExitInst);
   3590     setDebugLocFromInst(Builder, LoopExitInst);
   3591 
   3592     // If the vector reduction can be performed in a smaller type, we truncate
   3593     // then extend the loop exit value to enable InstCombine to evaluate the
   3594     // entire expression in the smaller type.
   3595     if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
   3596       Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
   3597       Builder.SetInsertPoint(LoopVectorBody->getTerminator());
   3598       for (unsigned part = 0; part < UF; ++part) {
   3599         Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
   3600         Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
   3601                                           : Builder.CreateZExt(Trunc, VecTy);
   3602         for (Value::user_iterator UI = RdxParts[part]->user_begin();
   3603              UI != RdxParts[part]->user_end();)
   3604           if (*UI != Trunc) {
   3605             (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
   3606             RdxParts[part] = Extnd;
   3607           } else {
   3608             ++UI;
   3609           }
   3610       }
   3611       Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
   3612       for (unsigned part = 0; part < UF; ++part)
   3613         RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
   3614     }
   3615 
   3616     // Reduce all of the unrolled parts into a single vector.
   3617     Value *ReducedPartRdx = RdxParts[0];
   3618     unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
   3619     setDebugLocFromInst(Builder, ReducedPartRdx);
   3620     for (unsigned part = 1; part < UF; ++part) {
   3621       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
   3622         // Floating point operations had to be 'fast' to enable the reduction.
   3623         ReducedPartRdx = addFastMathFlag(
   3624             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
   3625                                 ReducedPartRdx, "bin.rdx"));
   3626       else
   3627         ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
   3628             Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
   3629     }
   3630 
   3631     if (VF > 1) {
   3632       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
   3633       // and vector ops, reducing the set of values being computed by half each
   3634       // round.
   3635       assert(isPowerOf2_32(VF) &&
   3636              "Reduction emission only supported for pow2 vectors!");
   3637       Value *TmpVec = ReducedPartRdx;
   3638       SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
   3639       for (unsigned i = VF; i != 1; i >>= 1) {
   3640         // Move the upper half of the vector to the lower half.
   3641         for (unsigned j = 0; j != i / 2; ++j)
   3642           ShuffleMask[j] = Builder.getInt32(i / 2 + j);
   3643 
   3644         // Fill the rest of the mask with undef.
   3645         std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
   3646                   UndefValue::get(Builder.getInt32Ty()));
   3647 
   3648         Value *Shuf = Builder.CreateShuffleVector(
   3649             TmpVec, UndefValue::get(TmpVec->getType()),
   3650             ConstantVector::get(ShuffleMask), "rdx.shuf");
   3651 
   3652         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
   3653           // Floating point operations had to be 'fast' to enable the reduction.
   3654           TmpVec = addFastMathFlag(Builder.CreateBinOp(
   3655               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
   3656         else
   3657           TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
   3658                                                         TmpVec, Shuf);
   3659       }
   3660 
   3661       // The result is in the first element of the vector.
   3662       ReducedPartRdx =
   3663           Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
   3664 
   3665       // If the reduction can be performed in a smaller type, we need to extend
   3666       // the reduction to the wider type before we branch to the original loop.
   3667       if (Phi->getType() != RdxDesc.getRecurrenceType())
   3668         ReducedPartRdx =
   3669             RdxDesc.isSigned()
   3670                 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
   3671                 : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
   3672     }
   3673 
   3674     // Create a phi node that merges control-flow from the backedge-taken check
   3675     // block and the middle block.
   3676     PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
   3677                                           LoopScalarPreHeader->getTerminator());
   3678     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
   3679       BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
   3680     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
   3681 
   3682     // Now, we need to fix the users of the reduction variable
   3683     // inside and outside of the scalar remainder loop.
   3684     // We know that the loop is in LCSSA form. We need to update the
   3685     // PHI nodes in the exit blocks.
   3686     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
   3687                               LEE = LoopExitBlock->end();
   3688          LEI != LEE; ++LEI) {
   3689       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
   3690       if (!LCSSAPhi)
   3691         break;
   3692 
   3693       // All PHINodes need to have a single entry edge, or two if
   3694       // we already fixed them.
   3695       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
   3696 
   3697       // We found our reduction value exit-PHI. Update it with the
   3698       // incoming bypass edge.
   3699       if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
   3700         // Add an edge coming from the bypass.
   3701         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
   3702         break;
   3703       }
   3704     } // end of the LCSSA phi scan.
   3705 
   3706     // Fix the scalar loop reduction variable with the incoming reduction sum
   3707     // from the vector body and from the backedge value.
   3708     int IncomingEdgeBlockIdx =
   3709         Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
   3710     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
   3711     // Pick the other block.
   3712     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
   3713     Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
   3714     Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
   3715   } // end of for each Phi in PHIsToFix.
   3716 
   3717   fixLCSSAPHIs();
   3718 
   3719   // Make sure DomTree is updated.
   3720   updateAnalysis();
   3721 
   3722   // Predicate any stores.
   3723   for (auto KV : PredicatedStores) {
   3724     BasicBlock::iterator I(KV.first);
   3725     auto *BB = SplitBlock(I->getParent(), &*std::next(I), DT, LI);
   3726     auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
   3727                                         /*BranchWeights=*/nullptr, DT, LI);
   3728     I->moveBefore(T);
   3729     I->getParent()->setName("pred.store.if");
   3730     BB->setName("pred.store.continue");
   3731   }
   3732   DEBUG(DT->verifyDomTree());
   3733   // Remove redundant induction instructions.
   3734   cse(LoopVectorBody);
   3735 }
   3736 
   3737 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
   3738 
   3739   // This is the second phase of vectorizing first-order recurrences. An
   3740   // overview of the transformation is described below. Suppose we have the
   3741   // following loop.
   3742   //
   3743   //   for (int i = 0; i < n; ++i)
   3744   //     b[i] = a[i] - a[i - 1];
   3745   //
   3746   // There is a first-order recurrence on "a". For this loop, the shorthand
   3747   // scalar IR looks like:
   3748   //
   3749   //   scalar.ph:
   3750   //     s_init = a[-1]
   3751   //     br scalar.body
   3752   //
   3753   //   scalar.body:
   3754   //     i = phi [0, scalar.ph], [i+1, scalar.body]
   3755   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
   3756   //     s2 = a[i]
   3757   //     b[i] = s2 - s1
   3758   //     br cond, scalar.body, ...
   3759   //
   3760   // In this example, s1 is a recurrence because it's value depends on the
   3761   // previous iteration. In the first phase of vectorization, we created a
   3762   // temporary value for s1. We now complete the vectorization and produce the
   3763   // shorthand vector IR shown below (for VF = 4, UF = 1).
   3764   //
   3765   //   vector.ph:
   3766   //     v_init = vector(..., ..., ..., a[-1])
   3767   //     br vector.body
   3768   //
   3769   //   vector.body
   3770   //     i = phi [0, vector.ph], [i+4, vector.body]
   3771   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
   3772   //     v2 = a[i, i+1, i+2, i+3];
   3773   //     v3 = vector(v1(3), v2(0, 1, 2))
   3774   //     b[i, i+1, i+2, i+3] = v2 - v3
   3775   //     br cond, vector.body, middle.block
   3776   //
   3777   //   middle.block:
   3778   //     x = v2(3)
   3779   //     br scalar.ph
   3780   //
   3781   //   scalar.ph:
   3782   //     s_init = phi [x, middle.block], [a[-1], otherwise]
   3783   //     br scalar.body
   3784   //
   3785   // After execution completes the vector loop, we extract the next value of
   3786   // the recurrence (x) to use as the initial value in the scalar loop.
   3787 
   3788   // Get the original loop preheader and single loop latch.
   3789   auto *Preheader = OrigLoop->getLoopPreheader();
   3790   auto *Latch = OrigLoop->getLoopLatch();
   3791 
   3792   // Get the initial and previous values of the scalar recurrence.
   3793   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
   3794   auto *Previous = Phi->getIncomingValueForBlock(Latch);
   3795 
   3796   // Create a vector from the initial value.
   3797   auto *VectorInit = ScalarInit;
   3798   if (VF > 1) {
   3799     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
   3800     VectorInit = Builder.CreateInsertElement(
   3801         UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
   3802         Builder.getInt32(VF - 1), "vector.recur.init");
   3803   }
   3804 
   3805   // We constructed a temporary phi node in the first phase of vectorization.
   3806   // This phi node will eventually be deleted.
   3807   auto &PhiParts = getVectorValue(Phi);
   3808   Builder.SetInsertPoint(cast<Instruction>(PhiParts[0]));
   3809 
   3810   // Create a phi node for the new recurrence. The current value will either be
   3811   // the initial value inserted into a vector or loop-varying vector value.
   3812   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
   3813   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
   3814 
   3815   // Get the vectorized previous value. We ensured the previous values was an
   3816   // instruction when detecting the recurrence.
   3817   auto &PreviousParts = getVectorValue(Previous);
   3818 
   3819   // Set the insertion point to be after this instruction. We ensured the
   3820   // previous value dominated all uses of the phi when detecting the
   3821   // recurrence.
   3822   Builder.SetInsertPoint(
   3823       &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1])));
   3824 
   3825   // We will construct a vector for the recurrence by combining the values for
   3826   // the current and previous iterations. This is the required shuffle mask.
   3827   SmallVector<Constant *, 8> ShuffleMask(VF);
   3828   ShuffleMask[0] = Builder.getInt32(VF - 1);
   3829   for (unsigned I = 1; I < VF; ++I)
   3830     ShuffleMask[I] = Builder.getInt32(I + VF - 1);
   3831 
   3832   // The vector from which to take the initial value for the current iteration
   3833   // (actual or unrolled). Initially, this is the vector phi node.
   3834   Value *Incoming = VecPhi;
   3835 
   3836   // Shuffle the current and previous vector and update the vector parts.
   3837   for (unsigned Part = 0; Part < UF; ++Part) {
   3838     auto *Shuffle =
   3839         VF > 1
   3840             ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part],
   3841                                           ConstantVector::get(ShuffleMask))
   3842             : Incoming;
   3843     PhiParts[Part]->replaceAllUsesWith(Shuffle);
   3844     cast<Instruction>(PhiParts[Part])->eraseFromParent();
   3845     PhiParts[Part] = Shuffle;
   3846     Incoming = PreviousParts[Part];
   3847   }
   3848 
   3849   // Fix the latch value of the new recurrence in the vector loop.
   3850   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
   3851 
   3852   // Extract the last vector element in the middle block. This will be the
   3853   // initial value for the recurrence when jumping to the scalar loop.
   3854   auto *Extract = Incoming;
   3855   if (VF > 1) {
   3856     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
   3857     Extract = Builder.CreateExtractElement(Extract, Builder.getInt32(VF - 1),
   3858                                            "vector.recur.extract");
   3859   }
   3860 
   3861   // Fix the initial value of the original recurrence in the scalar loop.
   3862   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
   3863   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
   3864   for (auto *BB : predecessors(LoopScalarPreHeader)) {
   3865     auto *Incoming = BB == LoopMiddleBlock ? Extract : ScalarInit;
   3866     Start->addIncoming(Incoming, BB);
   3867   }
   3868 
   3869   Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
   3870   Phi->setName("scalar.recur");
   3871 
   3872   // Finally, fix users of the recurrence outside the loop. The users will need
   3873   // either the last value of the scalar recurrence or the last value of the
   3874   // vector recurrence we extracted in the middle block. Since the loop is in
   3875   // LCSSA form, we just need to find the phi node for the original scalar
   3876   // recurrence in the exit block, and then add an edge for the middle block.
   3877   for (auto &I : *LoopExitBlock) {
   3878     auto *LCSSAPhi = dyn_cast<PHINode>(&I);
   3879     if (!LCSSAPhi)
   3880       break;
   3881     if (LCSSAPhi->getIncomingValue(0) == Phi) {
   3882       LCSSAPhi->addIncoming(Extract, LoopMiddleBlock);
   3883       break;
   3884     }
   3885   }
   3886 }
   3887 
   3888 void InnerLoopVectorizer::fixLCSSAPHIs() {
   3889   for (Instruction &LEI : *LoopExitBlock) {
   3890     auto *LCSSAPhi = dyn_cast<PHINode>(&LEI);
   3891     if (!LCSSAPhi)
   3892       break;
   3893     if (LCSSAPhi->getNumIncomingValues() == 1)
   3894       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
   3895                             LoopMiddleBlock);
   3896   }
   3897 }
   3898 
   3899 InnerLoopVectorizer::VectorParts
   3900 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
   3901   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
   3902          "Invalid edge");
   3903 
   3904   // Look for cached value.
   3905   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
   3906   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
   3907   if (ECEntryIt != MaskCache.end())
   3908     return ECEntryIt->second;
   3909 
   3910   VectorParts SrcMask = createBlockInMask(Src);
   3911 
   3912   // The terminator has to be a branch inst!
   3913   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
   3914   assert(BI && "Unexpected terminator found");
   3915 
   3916   if (BI->isConditional()) {
   3917     VectorParts EdgeMask = getVectorValue(BI->getCondition());
   3918 
   3919     if (BI->getSuccessor(0) != Dst)
   3920       for (unsigned part = 0; part < UF; ++part)
   3921         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
   3922 
   3923     for (unsigned part = 0; part < UF; ++part)
   3924       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
   3925 
   3926     MaskCache[Edge] = EdgeMask;
   3927     return EdgeMask;
   3928   }
   3929 
   3930   MaskCache[Edge] = SrcMask;
   3931   return SrcMask;
   3932 }
   3933 
   3934 InnerLoopVectorizer::VectorParts
   3935 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
   3936   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
   3937 
   3938   // Loop incoming mask is all-one.
   3939   if (OrigLoop->getHeader() == BB) {
   3940     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
   3941     return getVectorValue(C);
   3942   }
   3943 
   3944   // This is the block mask. We OR all incoming edges, and with zero.
   3945   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
   3946   VectorParts BlockMask = getVectorValue(Zero);
   3947 
   3948   // For each pred:
   3949   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
   3950     VectorParts EM = createEdgeMask(*it, BB);
   3951     for (unsigned part = 0; part < UF; ++part)
   3952       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
   3953   }
   3954 
   3955   return BlockMask;
   3956 }
   3957 
   3958 void InnerLoopVectorizer::widenPHIInstruction(
   3959     Instruction *PN, InnerLoopVectorizer::VectorParts &Entry, unsigned UF,
   3960     unsigned VF, PhiVector *PV) {
   3961   PHINode *P = cast<PHINode>(PN);
   3962   // Handle recurrences.
   3963   if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
   3964     for (unsigned part = 0; part < UF; ++part) {
   3965       // This is phase one of vectorizing PHIs.
   3966       Type *VecTy =
   3967           (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
   3968       Entry[part] = PHINode::Create(
   3969           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
   3970     }
   3971     PV->push_back(P);
   3972     return;
   3973   }
   3974 
   3975   setDebugLocFromInst(Builder, P);
   3976   // Check for PHI nodes that are lowered to vector selects.
   3977   if (P->getParent() != OrigLoop->getHeader()) {
   3978     // We know that all PHIs in non-header blocks are converted into
   3979     // selects, so we don't have to worry about the insertion order and we
   3980     // can just use the builder.
   3981     // At this point we generate the predication tree. There may be
   3982     // duplications since this is a simple recursive scan, but future
   3983     // optimizations will clean it up.
   3984 
   3985     unsigned NumIncoming = P->getNumIncomingValues();
   3986 
   3987     // Generate a sequence of selects of the form:
   3988     // SELECT(Mask3, In3,
   3989     //      SELECT(Mask2, In2,
   3990     //                   ( ...)))
   3991     for (unsigned In = 0; In < NumIncoming; In++) {
   3992       VectorParts Cond =
   3993           createEdgeMask(P->getIncomingBlock(In), P->getParent());
   3994       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
   3995 
   3996       for (unsigned part = 0; part < UF; ++part) {
   3997         // We might have single edge PHIs (blocks) - use an identity
   3998         // 'select' for the first PHI operand.
   3999         if (In == 0)
   4000           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]);
   4001         else
   4002           // Select between the current value and the previous incoming edge
   4003           // based on the incoming mask.
   4004           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part],
   4005                                              "predphi");
   4006       }
   4007     }
   4008     return;
   4009   }
   4010 
   4011   // This PHINode must be an induction variable.
   4012   // Make sure that we know about it.
   4013   assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
   4014 
   4015   InductionDescriptor II = Legal->getInductionVars()->lookup(P);
   4016   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
   4017 
   4018   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
   4019   // which can be found from the original scalar operations.
   4020   switch (II.getKind()) {
   4021   case InductionDescriptor::IK_NoInduction:
   4022     llvm_unreachable("Unknown induction");
   4023   case InductionDescriptor::IK_IntInduction:
   4024     return widenIntInduction(P, Entry);
   4025   case InductionDescriptor::IK_PtrInduction:
   4026     // Handle the pointer induction variable case.
   4027     assert(P->getType()->isPointerTy() && "Unexpected type.");
   4028     // This is the normalized GEP that starts counting at zero.
   4029     Value *PtrInd = Induction;
   4030     PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
   4031     // This is the vector of results. Notice that we don't generate
   4032     // vector geps because scalar geps result in better code.
   4033     for (unsigned part = 0; part < UF; ++part) {
   4034       if (VF == 1) {
   4035         int EltIndex = part;
   4036         Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
   4037         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
   4038         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
   4039         SclrGep->setName("next.gep");
   4040         Entry[part] = SclrGep;
   4041         continue;
   4042       }
   4043 
   4044       Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
   4045       for (unsigned int i = 0; i < VF; ++i) {
   4046         int EltIndex = i + part * VF;
   4047         Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
   4048         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
   4049         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
   4050         SclrGep->setName("next.gep");
   4051         VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
   4052                                              Builder.getInt32(i), "insert.gep");
   4053       }
   4054       Entry[part] = VecVal;
   4055     }
   4056     return;
   4057   }
   4058 }
   4059 
   4060 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
   4061   // For each instruction in the old loop.
   4062   for (Instruction &I : *BB) {
   4063     VectorParts &Entry = WidenMap.get(&I);
   4064 
   4065     switch (I.getOpcode()) {
   4066     case Instruction::Br:
   4067       // Nothing to do for PHIs and BR, since we already took care of the
   4068       // loop control flow instructions.
   4069       continue;
   4070     case Instruction::PHI: {
   4071       // Vectorize PHINodes.
   4072       widenPHIInstruction(&I, Entry, UF, VF, PV);
   4073       continue;
   4074     } // End of PHI.
   4075 
   4076     case Instruction::Add:
   4077     case Instruction::FAdd:
   4078     case Instruction::Sub:
   4079     case Instruction::FSub:
   4080     case Instruction::Mul:
   4081     case Instruction::FMul:
   4082     case Instruction::UDiv:
   4083     case Instruction::SDiv:
   4084     case Instruction::FDiv:
   4085     case Instruction::URem:
   4086     case Instruction::SRem:
   4087     case Instruction::FRem:
   4088     case Instruction::Shl:
   4089     case Instruction::LShr:
   4090     case Instruction::AShr:
   4091     case Instruction::And:
   4092     case Instruction::Or:
   4093     case Instruction::Xor: {
   4094       // Just widen binops.
   4095       auto *BinOp = cast<BinaryOperator>(&I);
   4096       setDebugLocFromInst(Builder, BinOp);
   4097       VectorParts &A = getVectorValue(BinOp->getOperand(0));
   4098       VectorParts &B = getVectorValue(BinOp->getOperand(1));
   4099 
   4100       // Use this vector value for all users of the original instruction.
   4101       for (unsigned Part = 0; Part < UF; ++Part) {
   4102         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
   4103 
   4104         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
   4105           VecOp->copyIRFlags(BinOp);
   4106 
   4107         Entry[Part] = V;
   4108       }
   4109 
   4110       addMetadata(Entry, BinOp);
   4111       break;
   4112     }
   4113     case Instruction::Select: {
   4114       // Widen selects.
   4115       // If the selector is loop invariant we can create a select
   4116       // instruction with a scalar condition. Otherwise, use vector-select.
   4117       auto *SE = PSE.getSE();
   4118       bool InvariantCond =
   4119           SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
   4120       setDebugLocFromInst(Builder, &I);
   4121 
   4122       // The condition can be loop invariant  but still defined inside the
   4123       // loop. This means that we can't just use the original 'cond' value.
   4124       // We have to take the 'vectorized' value and pick the first lane.
   4125       // Instcombine will make this a no-op.
   4126       VectorParts &Cond = getVectorValue(I.getOperand(0));
   4127       VectorParts &Op0 = getVectorValue(I.getOperand(1));
   4128       VectorParts &Op1 = getVectorValue(I.getOperand(2));
   4129 
   4130       Value *ScalarCond =
   4131           (VF == 1)
   4132               ? Cond[0]
   4133               : Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
   4134 
   4135       for (unsigned Part = 0; Part < UF; ++Part) {
   4136         Entry[Part] = Builder.CreateSelect(
   4137             InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]);
   4138       }
   4139 
   4140       addMetadata(Entry, &I);
   4141       break;
   4142     }
   4143 
   4144     case Instruction::ICmp:
   4145     case Instruction::FCmp: {
   4146       // Widen compares. Generate vector compares.
   4147       bool FCmp = (I.getOpcode() == Instruction::FCmp);
   4148       auto *Cmp = dyn_cast<CmpInst>(&I);
   4149       setDebugLocFromInst(Builder, Cmp);
   4150       VectorParts &A = getVectorValue(Cmp->getOperand(0));
   4151       VectorParts &B = getVectorValue(Cmp->getOperand(1));
   4152       for (unsigned Part = 0; Part < UF; ++Part) {
   4153         Value *C = nullptr;
   4154         if (FCmp) {
   4155           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
   4156           cast<FCmpInst>(C)->copyFastMathFlags(Cmp);
   4157         } else {
   4158           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
   4159         }
   4160         Entry[Part] = C;
   4161       }
   4162 
   4163       addMetadata(Entry, &I);
   4164       break;
   4165     }
   4166 
   4167     case Instruction::Store:
   4168     case Instruction::Load:
   4169       vectorizeMemoryInstruction(&I);
   4170       break;
   4171     case Instruction::ZExt:
   4172     case Instruction::SExt:
   4173     case Instruction::FPToUI:
   4174     case Instruction::FPToSI:
   4175     case Instruction::FPExt:
   4176     case Instruction::PtrToInt:
   4177     case Instruction::IntToPtr:
   4178     case Instruction::SIToFP:
   4179     case Instruction::UIToFP:
   4180     case Instruction::Trunc:
   4181     case Instruction::FPTrunc:
   4182     case Instruction::BitCast: {
   4183       auto *CI = dyn_cast<CastInst>(&I);
   4184       setDebugLocFromInst(Builder, CI);
   4185 
   4186       // Optimize the special case where the source is a constant integer
   4187       // induction variable. Notice that we can only optimize the 'trunc' case
   4188       // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
   4189       // (c) other casts depend on pointer size.
   4190       auto ID = Legal->getInductionVars()->lookup(OldInduction);
   4191       if (isa<TruncInst>(CI) && CI->getOperand(0) == OldInduction &&
   4192           ID.getConstIntStepValue()) {
   4193         widenIntInduction(OldInduction, Entry, cast<TruncInst>(CI));
   4194         addMetadata(Entry, &I);
   4195         break;
   4196       }
   4197 
   4198       /// Vectorize casts.
   4199       Type *DestTy =
   4200           (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
   4201 
   4202       VectorParts &A = getVectorValue(CI->getOperand(0));
   4203       for (unsigned Part = 0; Part < UF; ++Part)
   4204         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
   4205       addMetadata(Entry, &I);
   4206       break;
   4207     }
   4208 
   4209     case Instruction::Call: {
   4210       // Ignore dbg intrinsics.
   4211       if (isa<DbgInfoIntrinsic>(I))
   4212         break;
   4213       setDebugLocFromInst(Builder, &I);
   4214 
   4215       Module *M = BB->getParent()->getParent();
   4216       auto *CI = cast<CallInst>(&I);
   4217 
   4218       StringRef FnName = CI->getCalledFunction()->getName();
   4219       Function *F = CI->getCalledFunction();
   4220       Type *RetTy = ToVectorTy(CI->getType(), VF);
   4221       SmallVector<Type *, 4> Tys;
   4222       for (Value *ArgOperand : CI->arg_operands())
   4223         Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
   4224 
   4225       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
   4226       if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
   4227                  ID == Intrinsic::lifetime_start)) {
   4228         scalarizeInstruction(&I);
   4229         break;
   4230       }
   4231       // The flag shows whether we use Intrinsic or a usual Call for vectorized
   4232       // version of the instruction.
   4233       // Is it beneficial to perform intrinsic call compared to lib call?
   4234       bool NeedToScalarize;
   4235       unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
   4236       bool UseVectorIntrinsic =
   4237           ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
   4238       if (!UseVectorIntrinsic && NeedToScalarize) {
   4239         scalarizeInstruction(&I);
   4240         break;
   4241       }
   4242 
   4243       for (unsigned Part = 0; Part < UF; ++Part) {
   4244         SmallVector<Value *, 4> Args;
   4245         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
   4246           Value *Arg = CI->getArgOperand(i);
   4247           // Some intrinsics have a scalar argument - don't replace it with a
   4248           // vector.
   4249           if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
   4250             VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
   4251             Arg = VectorArg[Part];
   4252           }
   4253           Args.push_back(Arg);
   4254         }
   4255 
   4256         Function *VectorF;
   4257         if (UseVectorIntrinsic) {
   4258           // Use vector version of the intrinsic.
   4259           Type *TysForDecl[] = {CI->getType()};
   4260           if (VF > 1)
   4261             TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
   4262           VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
   4263         } else {
   4264           // Use vector version of the library call.
   4265           StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
   4266           assert(!VFnName.empty() && "Vector function name is empty.");
   4267           VectorF = M->getFunction(VFnName);
   4268           if (!VectorF) {
   4269             // Generate a declaration
   4270             FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
   4271             VectorF =
   4272                 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
   4273             VectorF->copyAttributesFrom(F);
   4274           }
   4275         }
   4276         assert(VectorF && "Can't create vector function.");
   4277 
   4278         SmallVector<OperandBundleDef, 1> OpBundles;
   4279         CI->getOperandBundlesAsDefs(OpBundles);
   4280         CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
   4281 
   4282         if (isa<FPMathOperator>(V))
   4283           V->copyFastMathFlags(CI);
   4284 
   4285         Entry[Part] = V;
   4286       }
   4287 
   4288       addMetadata(Entry, &I);
   4289       break;
   4290     }
   4291 
   4292     default:
   4293       // All other instructions are unsupported. Scalarize them.
   4294       scalarizeInstruction(&I);
   4295       break;
   4296     } // end of switch.
   4297   }   // end of for_each instr.
   4298 }
   4299 
   4300 void InnerLoopVectorizer::updateAnalysis() {
   4301   // Forget the original basic block.
   4302   PSE.getSE()->forgetLoop(OrigLoop);
   4303 
   4304   // Update the dominator tree information.
   4305   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
   4306          "Entry does not dominate exit.");
   4307 
   4308   // We don't predicate stores by this point, so the vector body should be a
   4309   // single loop.
   4310   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
   4311 
   4312   DT->addNewBlock(LoopMiddleBlock, LoopVectorBody);
   4313   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
   4314   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
   4315   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
   4316 
   4317   DEBUG(DT->verifyDomTree());
   4318 }
   4319 
   4320 /// \brief Check whether it is safe to if-convert this phi node.
   4321 ///
   4322 /// Phi nodes with constant expressions that can trap are not safe to if
   4323 /// convert.
   4324 static bool canIfConvertPHINodes(BasicBlock *BB) {
   4325   for (Instruction &I : *BB) {
   4326     auto *Phi = dyn_cast<PHINode>(&I);
   4327     if (!Phi)
   4328       return true;
   4329     for (Value *V : Phi->incoming_values())
   4330       if (auto *C = dyn_cast<Constant>(V))
   4331         if (C->canTrap())
   4332           return false;
   4333   }
   4334   return true;
   4335 }
   4336 
   4337 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
   4338   if (!EnableIfConversion) {
   4339     emitAnalysis(VectorizationReport() << "if-conversion is disabled");
   4340     return false;
   4341   }
   4342 
   4343   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
   4344 
   4345   // A list of pointers that we can safely read and write to.
   4346   SmallPtrSet<Value *, 8> SafePointes;
   4347 
   4348   // Collect safe addresses.
   4349   for (BasicBlock *BB : TheLoop->blocks()) {
   4350     if (blockNeedsPredication(BB))
   4351       continue;
   4352 
   4353     for (Instruction &I : *BB) {
   4354       if (auto *LI = dyn_cast<LoadInst>(&I))
   4355         SafePointes.insert(LI->getPointerOperand());
   4356       else if (auto *SI = dyn_cast<StoreInst>(&I))
   4357         SafePointes.insert(SI->getPointerOperand());
   4358     }
   4359   }
   4360 
   4361   // Collect the blocks that need predication.
   4362   BasicBlock *Header = TheLoop->getHeader();
   4363   for (BasicBlock *BB : TheLoop->blocks()) {
   4364     // We don't support switch statements inside loops.
   4365     if (!isa<BranchInst>(BB->getTerminator())) {
   4366       emitAnalysis(VectorizationReport(BB->getTerminator())
   4367                    << "loop contains a switch statement");
   4368       return false;
   4369     }
   4370 
   4371     // We must be able to predicate all blocks that need to be predicated.
   4372     if (blockNeedsPredication(BB)) {
   4373       if (!blockCanBePredicated(BB, SafePointes)) {
   4374         emitAnalysis(VectorizationReport(BB->getTerminator())
   4375                      << "control flow cannot be substituted for a select");
   4376         return false;
   4377       }
   4378     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
   4379       emitAnalysis(VectorizationReport(BB->getTerminator())
   4380                    << "control flow cannot be substituted for a select");
   4381       return false;
   4382     }
   4383   }
   4384 
   4385   // We can if-convert this loop.
   4386   return true;
   4387 }
   4388 
   4389 bool LoopVectorizationLegality::canVectorize() {
   4390   // We must have a loop in canonical form. Loops with indirectbr in them cannot
   4391   // be canonicalized.
   4392   if (!TheLoop->getLoopPreheader()) {
   4393     emitAnalysis(VectorizationReport()
   4394                  << "loop control flow is not understood by vectorizer");
   4395     return false;
   4396   }
   4397 
   4398   // We can only vectorize innermost loops.
   4399   if (!TheLoop->empty()) {
   4400     emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
   4401     return false;
   4402   }
   4403 
   4404   // We must have a single backedge.
   4405   if (TheLoop->getNumBackEdges() != 1) {
   4406     emitAnalysis(VectorizationReport()
   4407                  << "loop control flow is not understood by vectorizer");
   4408     return false;
   4409   }
   4410 
   4411   // We must have a single exiting block.
   4412   if (!TheLoop->getExitingBlock()) {
   4413     emitAnalysis(VectorizationReport()
   4414                  << "loop control flow is not understood by vectorizer");
   4415     return false;
   4416   }
   4417 
   4418   // We only handle bottom-tested loops, i.e. loop in which the condition is
   4419   // checked at the end of each iteration. With that we can assume that all
   4420   // instructions in the loop are executed the same number of times.
   4421   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
   4422     emitAnalysis(VectorizationReport()
   4423                  << "loop control flow is not understood by vectorizer");
   4424     return false;
   4425   }
   4426 
   4427   // We need to have a loop header.
   4428   DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
   4429                << '\n');
   4430 
   4431   // Check if we can if-convert non-single-bb loops.
   4432   unsigned NumBlocks = TheLoop->getNumBlocks();
   4433   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
   4434     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
   4435     return false;
   4436   }
   4437 
   4438   // ScalarEvolution needs to be able to find the exit count.
   4439   const SCEV *ExitCount = PSE.getBackedgeTakenCount();
   4440   if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
   4441     emitAnalysis(VectorizationReport()
   4442                  << "could not determine number of loop iterations");
   4443     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
   4444     return false;
   4445   }
   4446 
   4447   // Check if we can vectorize the instructions and CFG in this loop.
   4448   if (!canVectorizeInstrs()) {
   4449     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
   4450     return false;
   4451   }
   4452 
   4453   // Go over each instruction and look at memory deps.
   4454   if (!canVectorizeMemory()) {
   4455     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
   4456     return false;
   4457   }
   4458 
   4459   // Collect all of the variables that remain uniform after vectorization.
   4460   collectLoopUniforms();
   4461 
   4462   DEBUG(dbgs() << "LV: We can vectorize this loop"
   4463                << (LAI->getRuntimePointerChecking()->Need
   4464                        ? " (with a runtime bound check)"
   4465                        : "")
   4466                << "!\n");
   4467 
   4468   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
   4469 
   4470   // If an override option has been passed in for interleaved accesses, use it.
   4471   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
   4472     UseInterleaved = EnableInterleavedMemAccesses;
   4473 
   4474   // Analyze interleaved memory accesses.
   4475   if (UseInterleaved)
   4476     InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
   4477 
   4478   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
   4479   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
   4480     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
   4481 
   4482   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
   4483     emitAnalysis(VectorizationReport()
   4484                  << "Too many SCEV assumptions need to be made and checked "
   4485                  << "at runtime");
   4486     DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
   4487     return false;
   4488   }
   4489 
   4490   // Okay! We can vectorize. At this point we don't have any other mem analysis
   4491   // which may limit our maximum vectorization factor, so just return true with
   4492   // no restrictions.
   4493   return true;
   4494 }
   4495 
   4496 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
   4497   if (Ty->isPointerTy())
   4498     return DL.getIntPtrType(Ty);
   4499 
   4500   // It is possible that char's or short's overflow when we ask for the loop's
   4501   // trip count, work around this by changing the type size.
   4502   if (Ty->getScalarSizeInBits() < 32)
   4503     return Type::getInt32Ty(Ty->getContext());
   4504 
   4505   return Ty;
   4506 }
   4507 
   4508 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
   4509   Ty0 = convertPointerToIntegerType(DL, Ty0);
   4510   Ty1 = convertPointerToIntegerType(DL, Ty1);
   4511   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
   4512     return Ty0;
   4513   return Ty1;
   4514 }
   4515 
   4516 /// \brief Check that the instruction has outside loop users and is not an
   4517 /// identified reduction variable.
   4518 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
   4519                                SmallPtrSetImpl<Value *> &AllowedExit) {
   4520   // Reduction and Induction instructions are allowed to have exit users. All
   4521   // other instructions must not have external users.
   4522   if (!AllowedExit.count(Inst))
   4523     // Check that all of the users of the loop are inside the BB.
   4524     for (User *U : Inst->users()) {
   4525       Instruction *UI = cast<Instruction>(U);
   4526       // This user may be a reduction exit value.
   4527       if (!TheLoop->contains(UI)) {
   4528         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
   4529         return true;
   4530       }
   4531     }
   4532   return false;
   4533 }
   4534 
   4535 void LoopVectorizationLegality::addInductionPhi(
   4536     PHINode *Phi, const InductionDescriptor &ID,
   4537     SmallPtrSetImpl<Value *> &AllowedExit) {
   4538   Inductions[Phi] = ID;
   4539   Type *PhiTy = Phi->getType();
   4540   const DataLayout &DL = Phi->getModule()->getDataLayout();
   4541 
   4542   // Get the widest type.
   4543   if (!WidestIndTy)
   4544     WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
   4545   else
   4546     WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
   4547 
   4548   // Int inductions are special because we only allow one IV.
   4549   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
   4550       ID.getConstIntStepValue() &&
   4551       ID.getConstIntStepValue()->isOne() &&
   4552       isa<Constant>(ID.getStartValue()) &&
   4553       cast<Constant>(ID.getStartValue())->isNullValue()) {
   4554 
   4555     // Use the phi node with the widest type as induction. Use the last
   4556     // one if there are multiple (no good reason for doing this other
   4557     // than it is expedient). We've checked that it begins at zero and
   4558     // steps by one, so this is a canonical induction variable.
   4559     if (!Induction || PhiTy == WidestIndTy)
   4560       Induction = Phi;
   4561   }
   4562 
   4563   // Both the PHI node itself, and the "post-increment" value feeding
   4564   // back into the PHI node may have external users.
   4565   AllowedExit.insert(Phi);
   4566   AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
   4567 
   4568   DEBUG(dbgs() << "LV: Found an induction variable.\n");
   4569   return;
   4570 }
   4571 
   4572 bool LoopVectorizationLegality::canVectorizeInstrs() {
   4573   BasicBlock *Header = TheLoop->getHeader();
   4574 
   4575   // Look for the attribute signaling the absence of NaNs.
   4576   Function &F = *Header->getParent();
   4577   HasFunNoNaNAttr =
   4578       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
   4579 
   4580   // For each block in the loop.
   4581   for (BasicBlock *BB : TheLoop->blocks()) {
   4582     // Scan the instructions in the block and look for hazards.
   4583     for (Instruction &I : *BB) {
   4584       if (auto *Phi = dyn_cast<PHINode>(&I)) {
   4585         Type *PhiTy = Phi->getType();
   4586         // Check that this PHI type is allowed.
   4587         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
   4588             !PhiTy->isPointerTy()) {
   4589           emitAnalysis(VectorizationReport(Phi)
   4590                        << "loop control flow is not understood by vectorizer");
   4591           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
   4592           return false;
   4593         }
   4594 
   4595         // If this PHINode is not in the header block, then we know that we
   4596         // can convert it to select during if-conversion. No need to check if
   4597         // the PHIs in this block are induction or reduction variables.
   4598         if (BB != Header) {
   4599           // Check that this instruction has no outside users or is an
   4600           // identified reduction value with an outside user.
   4601           if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
   4602             continue;
   4603           emitAnalysis(VectorizationReport(Phi)
   4604                        << "value could not be identified as "
   4605                           "an induction or reduction variable");
   4606           return false;
   4607         }
   4608 
   4609         // We only allow if-converted PHIs with exactly two incoming values.
   4610         if (Phi->getNumIncomingValues() != 2) {
   4611           emitAnalysis(VectorizationReport(Phi)
   4612                        << "control flow not understood by vectorizer");
   4613           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
   4614           return false;
   4615         }
   4616 
   4617         RecurrenceDescriptor RedDes;
   4618         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) {
   4619           if (RedDes.hasUnsafeAlgebra())
   4620             Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
   4621           AllowedExit.insert(RedDes.getLoopExitInstr());
   4622           Reductions[Phi] = RedDes;
   4623           continue;
   4624         }
   4625 
   4626         InductionDescriptor ID;
   4627         if (InductionDescriptor::isInductionPHI(Phi, PSE, ID)) {
   4628           addInductionPhi(Phi, ID, AllowedExit);
   4629           continue;
   4630         }
   4631 
   4632         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) {
   4633           FirstOrderRecurrences.insert(Phi);
   4634           continue;
   4635         }
   4636 
   4637         // As a last resort, coerce the PHI to a AddRec expression
   4638         // and re-try classifying it a an induction PHI.
   4639         if (InductionDescriptor::isInductionPHI(Phi, PSE, ID, true)) {
   4640           addInductionPhi(Phi, ID, AllowedExit);
   4641           continue;
   4642         }
   4643 
   4644         emitAnalysis(VectorizationReport(Phi)
   4645                      << "value that could not be identified as "
   4646                         "reduction is used outside the loop");
   4647         DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
   4648         return false;
   4649       } // end of PHI handling
   4650 
   4651       // We handle calls that:
   4652       //   * Are debug info intrinsics.
   4653       //   * Have a mapping to an IR intrinsic.
   4654       //   * Have a vector version available.
   4655       auto *CI = dyn_cast<CallInst>(&I);
   4656       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
   4657           !isa<DbgInfoIntrinsic>(CI) &&
   4658           !(CI->getCalledFunction() && TLI &&
   4659             TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
   4660         emitAnalysis(VectorizationReport(CI)
   4661                      << "call instruction cannot be vectorized");
   4662         DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
   4663         return false;
   4664       }
   4665 
   4666       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
   4667       // second argument is the same (i.e. loop invariant)
   4668       if (CI && hasVectorInstrinsicScalarOpd(
   4669                     getVectorIntrinsicIDForCall(CI, TLI), 1)) {
   4670         auto *SE = PSE.getSE();
   4671         if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
   4672           emitAnalysis(VectorizationReport(CI)
   4673                        << "intrinsic instruction cannot be vectorized");
   4674           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
   4675           return false;
   4676         }
   4677       }
   4678 
   4679       // Check that the instruction return type is vectorizable.
   4680       // Also, we can't vectorize extractelement instructions.
   4681       if ((!VectorType::isValidElementType(I.getType()) &&
   4682            !I.getType()->isVoidTy()) ||
   4683           isa<ExtractElementInst>(I)) {
   4684         emitAnalysis(VectorizationReport(&I)
   4685                      << "instruction return type cannot be vectorized");
   4686         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
   4687         return false;
   4688       }
   4689 
   4690       // Check that the stored type is vectorizable.
   4691       if (auto *ST = dyn_cast<StoreInst>(&I)) {
   4692         Type *T = ST->getValueOperand()->getType();
   4693         if (!VectorType::isValidElementType(T)) {
   4694           emitAnalysis(VectorizationReport(ST)
   4695                        << "store instruction cannot be vectorized");
   4696           return false;
   4697         }
   4698 
   4699         // FP instructions can allow unsafe algebra, thus vectorizable by
   4700         // non-IEEE-754 compliant SIMD units.
   4701         // This applies to floating-point math operations and calls, not memory
   4702         // operations, shuffles, or casts, as they don't change precision or
   4703         // semantics.
   4704       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
   4705                  !I.hasUnsafeAlgebra()) {
   4706         DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
   4707         Hints->setPotentiallyUnsafe();
   4708       }
   4709 
   4710       // Reduction instructions are allowed to have exit users.
   4711       // All other instructions must not have external users.
   4712       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
   4713         emitAnalysis(VectorizationReport(&I)
   4714                      << "value cannot be used outside the loop");
   4715         return false;
   4716       }
   4717 
   4718     } // next instr.
   4719   }
   4720 
   4721   if (!Induction) {
   4722     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
   4723     if (Inductions.empty()) {
   4724       emitAnalysis(VectorizationReport()
   4725                    << "loop induction variable could not be identified");
   4726       return false;
   4727     }
   4728   }
   4729 
   4730   // Now we know the widest induction type, check if our found induction
   4731   // is the same size. If it's not, unset it here and InnerLoopVectorizer
   4732   // will create another.
   4733   if (Induction && WidestIndTy != Induction->getType())
   4734     Induction = nullptr;
   4735 
   4736   return true;
   4737 }
   4738 
   4739 void LoopVectorizationLegality::collectLoopUniforms() {
   4740   // We now know that the loop is vectorizable!
   4741   // Collect variables that will remain uniform after vectorization.
   4742 
   4743   // If V is not an instruction inside the current loop, it is a Value
   4744   // outside of the scope which we are interesting in.
   4745   auto isOutOfScope = [&](Value *V) -> bool {
   4746     Instruction *I = dyn_cast<Instruction>(V);
   4747     return (!I || !TheLoop->contains(I));
   4748   };
   4749 
   4750   SetVector<Instruction *> Worklist;
   4751   BasicBlock *Latch = TheLoop->getLoopLatch();
   4752   // Start with the conditional branch.
   4753   if (!isOutOfScope(Latch->getTerminator()->getOperand(0))) {
   4754     Instruction *Cmp = cast<Instruction>(Latch->getTerminator()->getOperand(0));
   4755     Worklist.insert(Cmp);
   4756     DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
   4757   }
   4758 
   4759   // Also add all consecutive pointer values; these values will be uniform
   4760   // after vectorization (and subsequent cleanup).
   4761   for (auto *BB : TheLoop->blocks()) {
   4762     for (auto &I : *BB) {
   4763       if (I.getType()->isPointerTy() && isConsecutivePtr(&I)) {
   4764         Worklist.insert(&I);
   4765         DEBUG(dbgs() << "LV: Found uniform instruction: " << I << "\n");
   4766       }
   4767     }
   4768   }
   4769 
   4770   // Expand Worklist in topological order: whenever a new instruction
   4771   // is added , its users should be either already inside Worklist, or
   4772   // out of scope. It ensures a uniform instruction will only be used
   4773   // by uniform instructions or out of scope instructions.
   4774   unsigned idx = 0;
   4775   do {
   4776     Instruction *I = Worklist[idx++];
   4777 
   4778     for (auto OV : I->operand_values()) {
   4779       if (isOutOfScope(OV))
   4780         continue;
   4781       auto *OI = cast<Instruction>(OV);
   4782       if (all_of(OI->users(), [&](User *U) -> bool {
   4783             return isOutOfScope(U) || Worklist.count(cast<Instruction>(U));
   4784           })) {
   4785         Worklist.insert(OI);
   4786         DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
   4787       }
   4788     }
   4789   } while (idx != Worklist.size());
   4790 
   4791   // For an instruction to be added into Worklist above, all its users inside
   4792   // the current loop should be already added into Worklist. This condition
   4793   // cannot be true for phi instructions which is always in a dependence loop.
   4794   // Because any instruction in the dependence cycle always depends on others
   4795   // in the cycle to be added into Worklist first, the result is no ones in
   4796   // the cycle will be added into Worklist in the end.
   4797   // That is why we process PHI separately.
   4798   for (auto &Induction : *getInductionVars()) {
   4799     auto *PN = Induction.first;
   4800     auto *UpdateV = PN->getIncomingValueForBlock(TheLoop->getLoopLatch());
   4801     if (all_of(PN->users(),
   4802                [&](User *U) -> bool {
   4803                  return U == UpdateV || isOutOfScope(U) ||
   4804                         Worklist.count(cast<Instruction>(U));
   4805                }) &&
   4806         all_of(UpdateV->users(), [&](User *U) -> bool {
   4807           return U == PN || isOutOfScope(U) ||
   4808                  Worklist.count(cast<Instruction>(U));
   4809         })) {
   4810       Worklist.insert(cast<Instruction>(PN));
   4811       Worklist.insert(cast<Instruction>(UpdateV));
   4812       DEBUG(dbgs() << "LV: Found uniform instruction: " << *PN << "\n");
   4813       DEBUG(dbgs() << "LV: Found uniform instruction: " << *UpdateV << "\n");
   4814     }
   4815   }
   4816 
   4817   Uniforms.insert(Worklist.begin(), Worklist.end());
   4818 }
   4819 
   4820 bool LoopVectorizationLegality::canVectorizeMemory() {
   4821   LAI = &(*GetLAA)(*TheLoop);
   4822   InterleaveInfo.setLAI(LAI);
   4823   auto &OptionalReport = LAI->getReport();
   4824   if (OptionalReport)
   4825     emitAnalysis(VectorizationReport(*OptionalReport));
   4826   if (!LAI->canVectorizeMemory())
   4827     return false;
   4828 
   4829   if (LAI->hasStoreToLoopInvariantAddress()) {
   4830     emitAnalysis(
   4831         VectorizationReport()
   4832         << "write to a loop invariant address could not be vectorized");
   4833     DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
   4834     return false;
   4835   }
   4836 
   4837   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
   4838   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
   4839 
   4840   return true;
   4841 }
   4842 
   4843 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
   4844   Value *In0 = const_cast<Value *>(V);
   4845   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
   4846   if (!PN)
   4847     return false;
   4848 
   4849   return Inductions.count(PN);
   4850 }
   4851 
   4852 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
   4853   return FirstOrderRecurrences.count(Phi);
   4854 }
   4855 
   4856 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
   4857   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
   4858 }
   4859 
   4860 bool LoopVectorizationLegality::blockCanBePredicated(
   4861     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
   4862   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
   4863 
   4864   for (Instruction &I : *BB) {
   4865     // Check that we don't have a constant expression that can trap as operand.
   4866     for (Value *Operand : I.operands()) {
   4867       if (auto *C = dyn_cast<Constant>(Operand))
   4868         if (C->canTrap())
   4869           return false;
   4870     }
   4871     // We might be able to hoist the load.
   4872     if (I.mayReadFromMemory()) {
   4873       auto *LI = dyn_cast<LoadInst>(&I);
   4874       if (!LI)
   4875         return false;
   4876       if (!SafePtrs.count(LI->getPointerOperand())) {
   4877         if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) ||
   4878             isLegalMaskedGather(LI->getType())) {
   4879           MaskedOp.insert(LI);
   4880           continue;
   4881         }
   4882         // !llvm.mem.parallel_loop_access implies if-conversion safety.
   4883         if (IsAnnotatedParallel)
   4884           continue;
   4885         return false;
   4886       }
   4887     }
   4888 
   4889     // We don't predicate stores at the moment.
   4890     if (I.mayWriteToMemory()) {
   4891       auto *SI = dyn_cast<StoreInst>(&I);
   4892       // We only support predication of stores in basic blocks with one
   4893       // predecessor.
   4894       if (!SI)
   4895         return false;
   4896 
   4897       // Build a masked store if it is legal for the target.
   4898       if (isLegalMaskedStore(SI->getValueOperand()->getType(),
   4899                              SI->getPointerOperand()) ||
   4900           isLegalMaskedScatter(SI->getValueOperand()->getType())) {
   4901         MaskedOp.insert(SI);
   4902         continue;
   4903       }
   4904 
   4905       bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
   4906       bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
   4907 
   4908       if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
   4909           !isSinglePredecessor)
   4910         return false;
   4911     }
   4912     if (I.mayThrow())
   4913       return false;
   4914 
   4915     // The instructions below can trap.
   4916     switch (I.getOpcode()) {
   4917     default:
   4918       continue;
   4919     case Instruction::UDiv:
   4920     case Instruction::SDiv:
   4921     case Instruction::URem:
   4922     case Instruction::SRem:
   4923       return false;
   4924     }
   4925   }
   4926 
   4927   return true;
   4928 }
   4929 
   4930 void InterleavedAccessInfo::collectConstStrideAccesses(
   4931     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
   4932     const ValueToValueMap &Strides) {
   4933 
   4934   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
   4935 
   4936   // Since it's desired that the load/store instructions be maintained in
   4937   // "program order" for the interleaved access analysis, we have to visit the
   4938   // blocks in the loop in reverse postorder (i.e., in a topological order).
   4939   // Such an ordering will ensure that any load/store that may be executed
   4940   // before a second load/store will precede the second load/store in
   4941   // AccessStrideInfo.
   4942   LoopBlocksDFS DFS(TheLoop);
   4943   DFS.perform(LI);
   4944   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
   4945     for (auto &I : *BB) {
   4946       auto *LI = dyn_cast<LoadInst>(&I);
   4947       auto *SI = dyn_cast<StoreInst>(&I);
   4948       if (!LI && !SI)
   4949         continue;
   4950 
   4951       Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
   4952       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides);
   4953 
   4954       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
   4955       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
   4956       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
   4957 
   4958       // An alignment of 0 means target ABI alignment.
   4959       unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
   4960       if (!Align)
   4961         Align = DL.getABITypeAlignment(PtrTy->getElementType());
   4962 
   4963       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
   4964     }
   4965 }
   4966 
   4967 // Analyze interleaved accesses and collect them into interleaved load and
   4968 // store groups.
   4969 //
   4970 // When generating code for an interleaved load group, we effectively hoist all
   4971 // loads in the group to the location of the first load in program order. When
   4972 // generating code for an interleaved store group, we sink all stores to the
   4973 // location of the last store. This code motion can change the order of load
   4974 // and store instructions and may break dependences.
   4975 //
   4976 // The code generation strategy mentioned above ensures that we won't violate
   4977 // any write-after-read (WAR) dependences.
   4978 //
   4979 // E.g., for the WAR dependence:  a = A[i];      // (1)
   4980 //                                A[i] = b;      // (2)
   4981 //
   4982 // The store group of (2) is always inserted at or below (2), and the load
   4983 // group of (1) is always inserted at or above (1). Thus, the instructions will
   4984 // never be reordered. All other dependences are checked to ensure the
   4985 // correctness of the instruction reordering.
   4986 //
   4987 // The algorithm visits all memory accesses in the loop in bottom-up program
   4988 // order. Program order is established by traversing the blocks in the loop in
   4989 // reverse postorder when collecting the accesses.
   4990 //
   4991 // We visit the memory accesses in bottom-up order because it can simplify the
   4992 // construction of store groups in the presence of write-after-write (WAW)
   4993 // dependences.
   4994 //
   4995 // E.g., for the WAW dependence:  A[i] = a;      // (1)
   4996 //                                A[i] = b;      // (2)
   4997 //                                A[i + 1] = c;  // (3)
   4998 //
   4999 // We will first create a store group with (3) and (2). (1) can't be added to
   5000 // this group because it and (2) are dependent. However, (1) can be grouped
   5001 // with other accesses that may precede it in program order. Note that a
   5002 // bottom-up order does not imply that WAW dependences should not be checked.
   5003 void InterleavedAccessInfo::analyzeInterleaving(
   5004     const ValueToValueMap &Strides) {
   5005   DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
   5006 
   5007   // Holds all accesses with a constant stride.
   5008   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
   5009   collectConstStrideAccesses(AccessStrideInfo, Strides);
   5010 
   5011   if (AccessStrideInfo.empty())
   5012     return;
   5013 
   5014   // Collect the dependences in the loop.
   5015   collectDependences();
   5016 
   5017   // Holds all interleaved store groups temporarily.
   5018   SmallSetVector<InterleaveGroup *, 4> StoreGroups;
   5019   // Holds all interleaved load groups temporarily.
   5020   SmallSetVector<InterleaveGroup *, 4> LoadGroups;
   5021 
   5022   // Search the load-load/write-write pair B-A in bottom-up order and try to
   5023   // insert B into the interleave group of A according to 3 rules:
   5024   //   1. A and B have the same stride.
   5025   //   2. A and B have the same memory object size.
   5026   //   3. B belongs to the group according to the distance.
   5027   for (auto AI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
   5028        AI != E; ++AI) {
   5029     Instruction *A = AI->first;
   5030     StrideDescriptor DesA = AI->second;
   5031 
   5032     // Initialize a group for A if it has an allowable stride. Even if we don't
   5033     // create a group for A, we continue with the bottom-up algorithm to ensure
   5034     // we don't break any of A's dependences.
   5035     InterleaveGroup *Group = nullptr;
   5036     if (isStrided(DesA.Stride)) {
   5037       Group = getInterleaveGroup(A);
   5038       if (!Group) {
   5039         DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
   5040         Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
   5041       }
   5042       if (A->mayWriteToMemory())
   5043         StoreGroups.insert(Group);
   5044       else
   5045         LoadGroups.insert(Group);
   5046     }
   5047 
   5048     for (auto BI = std::next(AI); BI != E; ++BI) {
   5049       Instruction *B = BI->first;
   5050       StrideDescriptor DesB = BI->second;
   5051 
   5052       // Our code motion strategy implies that we can't have dependences
   5053       // between accesses in an interleaved group and other accesses located
   5054       // between the first and last member of the group. Note that this also
   5055       // means that a group can't have more than one member at a given offset.
   5056       // The accesses in a group can have dependences with other accesses, but
   5057       // we must ensure we don't extend the boundaries of the group such that
   5058       // we encompass those dependent accesses.
   5059       //
   5060       // For example, assume we have the sequence of accesses shown below in a
   5061       // stride-2 loop:
   5062       //
   5063       //  (1, 2) is a group | A[i]   = a;  // (1)
   5064       //                    | A[i-1] = b;  // (2) |
   5065       //                      A[i-3] = c;  // (3)
   5066       //                      A[i]   = d;  // (4) | (2, 4) is not a group
   5067       //
   5068       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
   5069       // but not with (4). If we did, the dependent access (3) would be within
   5070       // the boundaries of the (2, 4) group.
   5071       if (!canReorderMemAccessesForInterleavedGroups(&*BI, &*AI)) {
   5072 
   5073         // If a dependence exists and B is already in a group, we know that B
   5074         // must be a store since B precedes A and WAR dependences are allowed.
   5075         // Thus, B would be sunk below A. We release B's group to prevent this
   5076         // illegal code motion. B will then be free to form another group with
   5077         // instructions that precede it.
   5078         if (isInterleaved(B)) {
   5079           InterleaveGroup *StoreGroup = getInterleaveGroup(B);
   5080           StoreGroups.remove(StoreGroup);
   5081           releaseGroup(StoreGroup);
   5082         }
   5083 
   5084         // If a dependence exists and B is not already in a group (or it was
   5085         // and we just released it), A might be hoisted above B (if A is a
   5086         // load) or another store might be sunk below B (if A is a store). In
   5087         // either case, we can't add additional instructions to A's group. A
   5088         // will only form a group with instructions that it precedes.
   5089         break;
   5090       }
   5091 
   5092       // At this point, we've checked for illegal code motion. If either A or B
   5093       // isn't strided, there's nothing left to do.
   5094       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
   5095         continue;
   5096 
   5097       // Ignore if B is already in a group or B is a different memory operation.
   5098       if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
   5099         continue;
   5100 
   5101       // Check the rule 1 and 2.
   5102       if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
   5103         continue;
   5104 
   5105       // Calculate the distance and prepare for the rule 3.
   5106       const SCEVConstant *DistToA = dyn_cast<SCEVConstant>(
   5107           PSE.getSE()->getMinusSCEV(DesB.Scev, DesA.Scev));
   5108       if (!DistToA)
   5109         continue;
   5110 
   5111       int64_t DistanceToA = DistToA->getAPInt().getSExtValue();
   5112 
   5113       // Skip if the distance is not multiple of size as they are not in the
   5114       // same group.
   5115       if (DistanceToA % static_cast<int64_t>(DesA.Size))
   5116         continue;
   5117 
   5118       // If either A or B is in a predicated block, we prevent adding them to a
   5119       // group. We may be able to relax this limitation in the future once we
   5120       // handle more complicated blocks.
   5121       if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
   5122         continue;
   5123 
   5124       // The index of B is the index of A plus the related index to A.
   5125       int IndexB =
   5126           Group->getIndex(A) + DistanceToA / static_cast<int64_t>(DesA.Size);
   5127 
   5128       // Try to insert B into the group.
   5129       if (Group->insertMember(B, IndexB, DesB.Align)) {
   5130         DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
   5131                      << "    into the interleave group with" << *A << '\n');
   5132         InterleaveGroupMap[B] = Group;
   5133 
   5134         // Set the first load in program order as the insert position.
   5135         if (B->mayReadFromMemory())
   5136           Group->setInsertPos(B);
   5137       }
   5138     } // Iteration on instruction B
   5139   }   // Iteration on instruction A
   5140 
   5141   // Remove interleaved store groups with gaps.
   5142   for (InterleaveGroup *Group : StoreGroups)
   5143     if (Group->getNumMembers() != Group->getFactor())
   5144       releaseGroup(Group);
   5145 
   5146   // If there is a non-reversed interleaved load group with gaps, we will need
   5147   // to execute at least one scalar epilogue iteration. This will ensure that
   5148   // we don't speculatively access memory out-of-bounds. Note that we only need
   5149   // to look for a member at index factor - 1, since every group must have a
   5150   // member at index zero.
   5151   for (InterleaveGroup *Group : LoadGroups)
   5152     if (!Group->getMember(Group->getFactor() - 1)) {
   5153       if (Group->isReverse()) {
   5154         releaseGroup(Group);
   5155       } else {
   5156         DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
   5157         RequiresScalarEpilogue = true;
   5158       }
   5159     }
   5160 }
   5161 
   5162 LoopVectorizationCostModel::VectorizationFactor
   5163 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
   5164   // Width 1 means no vectorize
   5165   VectorizationFactor Factor = {1U, 0U};
   5166   if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
   5167     emitAnalysis(
   5168         VectorizationReport()
   5169         << "runtime pointer checks needed. Enable vectorization of this "
   5170            "loop with '#pragma clang loop vectorize(enable)' when "
   5171            "compiling with -Os/-Oz");
   5172     DEBUG(dbgs()
   5173           << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
   5174     return Factor;
   5175   }
   5176 
   5177   if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
   5178     emitAnalysis(
   5179         VectorizationReport()
   5180         << "store that is conditionally executed prevents vectorization");
   5181     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
   5182     return Factor;
   5183   }
   5184 
   5185   // Find the trip count.
   5186   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
   5187   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
   5188 
   5189   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
   5190   unsigned SmallestType, WidestType;
   5191   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
   5192   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
   5193   unsigned MaxSafeDepDist = -1U;
   5194 
   5195   // Get the maximum safe dependence distance in bits computed by LAA. If the
   5196   // loop contains any interleaved accesses, we divide the dependence distance
   5197   // by the maximum interleave factor of all interleaved groups. Note that
   5198   // although the division ensures correctness, this is a fairly conservative
   5199   // computation because the maximum distance computed by LAA may not involve
   5200   // any of the interleaved accesses.
   5201   if (Legal->getMaxSafeDepDistBytes() != -1U)
   5202     MaxSafeDepDist =
   5203         Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor();
   5204 
   5205   WidestRegister =
   5206       ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist);
   5207   unsigned MaxVectorSize = WidestRegister / WidestType;
   5208 
   5209   DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
   5210                << WidestType << " bits.\n");
   5211   DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister
   5212                << " bits.\n");
   5213 
   5214   if (MaxVectorSize == 0) {
   5215     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
   5216     MaxVectorSize = 1;
   5217   }
   5218 
   5219   assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
   5220                                 " into one vector!");
   5221 
   5222   unsigned VF = MaxVectorSize;
   5223   if (MaximizeBandwidth && !OptForSize) {
   5224     // Collect all viable vectorization factors.
   5225     SmallVector<unsigned, 8> VFs;
   5226     unsigned NewMaxVectorSize = WidestRegister / SmallestType;
   5227     for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
   5228       VFs.push_back(VS);
   5229 
   5230     // For each VF calculate its register usage.
   5231     auto RUs = calculateRegisterUsage(VFs);
   5232 
   5233     // Select the largest VF which doesn't require more registers than existing
   5234     // ones.
   5235     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
   5236     for (int i = RUs.size() - 1; i >= 0; --i) {
   5237       if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
   5238         VF = VFs[i];
   5239         break;
   5240       }
   5241     }
   5242   }
   5243 
   5244   // If we optimize the program for size, avoid creating the tail loop.
   5245   if (OptForSize) {
   5246     // If we are unable to calculate the trip count then don't try to vectorize.
   5247     if (TC < 2) {
   5248       emitAnalysis(
   5249           VectorizationReport()
   5250           << "unable to calculate the loop count due to complex control flow");
   5251       DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
   5252       return Factor;
   5253     }
   5254 
   5255     // Find the maximum SIMD width that can fit within the trip count.
   5256     VF = TC % MaxVectorSize;
   5257 
   5258     if (VF == 0)
   5259       VF = MaxVectorSize;
   5260     else {
   5261       // If the trip count that we found modulo the vectorization factor is not
   5262       // zero then we require a tail.
   5263       emitAnalysis(VectorizationReport()
   5264                    << "cannot optimize for size and vectorize at the "
   5265                       "same time. Enable vectorization of this loop "
   5266                       "with '#pragma clang loop vectorize(enable)' "
   5267                       "when compiling with -Os/-Oz");
   5268       DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
   5269       return Factor;
   5270     }
   5271   }
   5272 
   5273   int UserVF = Hints->getWidth();
   5274   if (UserVF != 0) {
   5275     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
   5276     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
   5277 
   5278     Factor.Width = UserVF;
   5279     return Factor;
   5280   }
   5281 
   5282   float Cost = expectedCost(1).first;
   5283 #ifndef NDEBUG
   5284   const float ScalarCost = Cost;
   5285 #endif /* NDEBUG */
   5286   unsigned Width = 1;
   5287   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
   5288 
   5289   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
   5290   // Ignore scalar width, because the user explicitly wants vectorization.
   5291   if (ForceVectorization && VF > 1) {
   5292     Width = 2;
   5293     Cost = expectedCost(Width).first / (float)Width;
   5294   }
   5295 
   5296   for (unsigned i = 2; i <= VF; i *= 2) {
   5297     // Notice that the vector loop needs to be executed less times, so
   5298     // we need to divide the cost of the vector loops by the width of
   5299     // the vector elements.
   5300     VectorizationCostTy C = expectedCost(i);
   5301     float VectorCost = C.first / (float)i;
   5302     DEBUG(dbgs() << "LV: Vector loop of width " << i
   5303                  << " costs: " << (int)VectorCost << ".\n");
   5304     if (!C.second && !ForceVectorization) {
   5305       DEBUG(
   5306           dbgs() << "LV: Not considering vector loop of width " << i
   5307                  << " because it will not generate any vector instructions.\n");
   5308       continue;
   5309     }
   5310     if (VectorCost < Cost) {
   5311       Cost = VectorCost;
   5312       Width = i;
   5313     }
   5314   }
   5315 
   5316   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
   5317         << "LV: Vectorization seems to be not beneficial, "
   5318         << "but was forced by a user.\n");
   5319   DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
   5320   Factor.Width = Width;
   5321   Factor.Cost = Width * Cost;
   5322   return Factor;
   5323 }
   5324 
   5325 std::pair<unsigned, unsigned>
   5326 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
   5327   unsigned MinWidth = -1U;
   5328   unsigned MaxWidth = 8;
   5329   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
   5330 
   5331   // For each block.
   5332   for (BasicBlock *BB : TheLoop->blocks()) {
   5333     // For each instruction in the loop.
   5334     for (Instruction &I : *BB) {
   5335       Type *T = I.getType();
   5336 
   5337       // Skip ignored values.
   5338       if (ValuesToIgnore.count(&I))
   5339         continue;
   5340 
   5341       // Only examine Loads, Stores and PHINodes.
   5342       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
   5343         continue;
   5344 
   5345       // Examine PHI nodes that are reduction variables. Update the type to
   5346       // account for the recurrence type.
   5347       if (auto *PN = dyn_cast<PHINode>(&I)) {
   5348         if (!Legal->isReductionVariable(PN))
   5349           continue;
   5350         RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
   5351         T = RdxDesc.getRecurrenceType();
   5352       }
   5353 
   5354       // Examine the stored values.
   5355       if (auto *ST = dyn_cast<StoreInst>(&I))
   5356         T = ST->getValueOperand()->getType();
   5357 
   5358       // Ignore loaded pointer types and stored pointer types that are not
   5359       // consecutive. However, we do want to take consecutive stores/loads of
   5360       // pointer vectors into account.
   5361       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I))
   5362         continue;
   5363 
   5364       MinWidth = std::min(MinWidth,
   5365                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
   5366       MaxWidth = std::max(MaxWidth,
   5367                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
   5368     }
   5369   }
   5370 
   5371   return {MinWidth, MaxWidth};
   5372 }
   5373 
   5374 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
   5375                                                            unsigned VF,
   5376                                                            unsigned LoopCost) {
   5377 
   5378   // -- The interleave heuristics --
   5379   // We interleave the loop in order to expose ILP and reduce the loop overhead.
   5380   // There are many micro-architectural considerations that we can't predict
   5381   // at this level. For example, frontend pressure (on decode or fetch) due to
   5382   // code size, or the number and capabilities of the execution ports.
   5383   //
   5384   // We use the following heuristics to select the interleave count:
   5385   // 1. If the code has reductions, then we interleave to break the cross
   5386   // iteration dependency.
   5387   // 2. If the loop is really small, then we interleave to reduce the loop
   5388   // overhead.
   5389   // 3. We don't interleave if we think that we will spill registers to memory
   5390   // due to the increased register pressure.
   5391 
   5392   // When we optimize for size, we don't interleave.
   5393   if (OptForSize)
   5394     return 1;
   5395 
   5396   // We used the distance for the interleave count.
   5397   if (Legal->getMaxSafeDepDistBytes() != -1U)
   5398     return 1;
   5399 
   5400   // Do not interleave loops with a relatively small trip count.
   5401   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
   5402   if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
   5403     return 1;
   5404 
   5405   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
   5406   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
   5407                << " registers\n");
   5408 
   5409   if (VF == 1) {
   5410     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
   5411       TargetNumRegisters = ForceTargetNumScalarRegs;
   5412   } else {
   5413     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
   5414       TargetNumRegisters = ForceTargetNumVectorRegs;
   5415   }
   5416 
   5417   RegisterUsage R = calculateRegisterUsage({VF})[0];
   5418   // We divide by these constants so assume that we have at least one
   5419   // instruction that uses at least one register.
   5420   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
   5421   R.NumInstructions = std::max(R.NumInstructions, 1U);
   5422 
   5423   // We calculate the interleave count using the following formula.
   5424   // Subtract the number of loop invariants from the number of available
   5425   // registers. These registers are used by all of the interleaved instances.
   5426   // Next, divide the remaining registers by the number of registers that is
   5427   // required by the loop, in order to estimate how many parallel instances
   5428   // fit without causing spills. All of this is rounded down if necessary to be
   5429   // a power of two. We want power of two interleave count to simplify any
   5430   // addressing operations or alignment considerations.
   5431   unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
   5432                               R.MaxLocalUsers);
   5433 
   5434   // Don't count the induction variable as interleaved.
   5435   if (EnableIndVarRegisterHeur)
   5436     IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
   5437                        std::max(1U, (R.MaxLocalUsers - 1)));
   5438 
   5439   // Clamp the interleave ranges to reasonable counts.
   5440   unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
   5441 
   5442   // Check if the user has overridden the max.
   5443   if (VF == 1) {
   5444     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
   5445       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
   5446   } else {
   5447     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
   5448       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
   5449   }
   5450 
   5451   // If we did not calculate the cost for VF (because the user selected the VF)
   5452   // then we calculate the cost of VF here.
   5453   if (LoopCost == 0)
   5454     LoopCost = expectedCost(VF).first;
   5455 
   5456   // Clamp the calculated IC to be between the 1 and the max interleave count
   5457   // that the target allows.
   5458   if (IC > MaxInterleaveCount)
   5459     IC = MaxInterleaveCount;
   5460   else if (IC < 1)
   5461     IC = 1;
   5462 
   5463   // Interleave if we vectorized this loop and there is a reduction that could
   5464   // benefit from interleaving.
   5465   if (VF > 1 && Legal->getReductionVars()->size()) {
   5466     DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
   5467     return IC;
   5468   }
   5469 
   5470   // Note that if we've already vectorized the loop we will have done the
   5471   // runtime check and so interleaving won't require further checks.
   5472   bool InterleavingRequiresRuntimePointerCheck =
   5473       (VF == 1 && Legal->getRuntimePointerChecking()->Need);
   5474 
   5475   // We want to interleave small loops in order to reduce the loop overhead and
   5476   // potentially expose ILP opportunities.
   5477   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
   5478   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
   5479     // We assume that the cost overhead is 1 and we use the cost model
   5480     // to estimate the cost of the loop and interleave until the cost of the
   5481     // loop overhead is about 5% of the cost of the loop.
   5482     unsigned SmallIC =
   5483         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
   5484 
   5485     // Interleave until store/load ports (estimated by max interleave count) are
   5486     // saturated.
   5487     unsigned NumStores = Legal->getNumStores();
   5488     unsigned NumLoads = Legal->getNumLoads();
   5489     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
   5490     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
   5491 
   5492     // If we have a scalar reduction (vector reductions are already dealt with
   5493     // by this point), we can increase the critical path length if the loop
   5494     // we're interleaving is inside another loop. Limit, by default to 2, so the
   5495     // critical path only gets increased by one reduction operation.
   5496     if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) {
   5497       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
   5498       SmallIC = std::min(SmallIC, F);
   5499       StoresIC = std::min(StoresIC, F);
   5500       LoadsIC = std::min(LoadsIC, F);
   5501     }
   5502 
   5503     if (EnableLoadStoreRuntimeInterleave &&
   5504         std::max(StoresIC, LoadsIC) > SmallIC) {
   5505       DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
   5506       return std::max(StoresIC, LoadsIC);
   5507     }
   5508 
   5509     DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
   5510     return SmallIC;
   5511   }
   5512 
   5513   // Interleave if this is a large loop (small loops are already dealt with by
   5514   // this point) that could benefit from interleaving.
   5515   bool HasReductions = (Legal->getReductionVars()->size() > 0);
   5516   if (TTI.enableAggressiveInterleaving(HasReductions)) {
   5517     DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
   5518     return IC;
   5519   }
   5520 
   5521   DEBUG(dbgs() << "LV: Not Interleaving.\n");
   5522   return 1;
   5523 }
   5524 
   5525 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
   5526 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
   5527   // This function calculates the register usage by measuring the highest number
   5528   // of values that are alive at a single location. Obviously, this is a very
   5529   // rough estimation. We scan the loop in a topological order in order and
   5530   // assign a number to each instruction. We use RPO to ensure that defs are
   5531   // met before their users. We assume that each instruction that has in-loop
   5532   // users starts an interval. We record every time that an in-loop value is
   5533   // used, so we have a list of the first and last occurrences of each
   5534   // instruction. Next, we transpose this data structure into a multi map that
   5535   // holds the list of intervals that *end* at a specific location. This multi
   5536   // map allows us to perform a linear search. We scan the instructions linearly
   5537   // and record each time that a new interval starts, by placing it in a set.
   5538   // If we find this value in the multi-map then we remove it from the set.
   5539   // The max register usage is the maximum size of the set.
   5540   // We also search for instructions that are defined outside the loop, but are
   5541   // used inside the loop. We need this number separately from the max-interval
   5542   // usage number because when we unroll, loop-invariant values do not take
   5543   // more register.
   5544   LoopBlocksDFS DFS(TheLoop);
   5545   DFS.perform(LI);
   5546 
   5547   RegisterUsage RU;
   5548   RU.NumInstructions = 0;
   5549 
   5550   // Each 'key' in the map opens a new interval. The values
   5551   // of the map are the index of the 'last seen' usage of the
   5552   // instruction that is the key.
   5553   typedef DenseMap<Instruction *, unsigned> IntervalMap;
   5554   // Maps instruction to its index.
   5555   DenseMap<unsigned, Instruction *> IdxToInstr;
   5556   // Marks the end of each interval.
   5557   IntervalMap EndPoint;
   5558   // Saves the list of instruction indices that are used in the loop.
   5559   SmallSet<Instruction *, 8> Ends;
   5560   // Saves the list of values that are used in the loop but are
   5561   // defined outside the loop, such as arguments and constants.
   5562   SmallPtrSet<Value *, 8> LoopInvariants;
   5563 
   5564   unsigned Index = 0;
   5565   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
   5566     RU.NumInstructions += BB->size();
   5567     for (Instruction &I : *BB) {
   5568       IdxToInstr[Index++] = &I;
   5569 
   5570       // Save the end location of each USE.
   5571       for (Value *U : I.operands()) {
   5572         auto *Instr = dyn_cast<Instruction>(U);
   5573 
   5574         // Ignore non-instruction values such as arguments, constants, etc.
   5575         if (!Instr)
   5576           continue;
   5577 
   5578         // If this instruction is outside the loop then record it and continue.
   5579         if (!TheLoop->contains(Instr)) {
   5580           LoopInvariants.insert(Instr);
   5581           continue;
   5582         }
   5583 
   5584         // Overwrite previous end points.
   5585         EndPoint[Instr] = Index;
   5586         Ends.insert(Instr);
   5587       }
   5588     }
   5589   }
   5590 
   5591   // Saves the list of intervals that end with the index in 'key'.
   5592   typedef SmallVector<Instruction *, 2> InstrList;
   5593   DenseMap<unsigned, InstrList> TransposeEnds;
   5594 
   5595   // Transpose the EndPoints to a list of values that end at each index.
   5596   for (auto &Interval : EndPoint)
   5597     TransposeEnds[Interval.second].push_back(Interval.first);
   5598 
   5599   SmallSet<Instruction *, 8> OpenIntervals;
   5600 
   5601   // Get the size of the widest register.
   5602   unsigned MaxSafeDepDist = -1U;
   5603   if (Legal->getMaxSafeDepDistBytes() != -1U)
   5604     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
   5605   unsigned WidestRegister =
   5606       std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
   5607   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
   5608 
   5609   SmallVector<RegisterUsage, 8> RUs(VFs.size());
   5610   SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
   5611 
   5612   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
   5613 
   5614   // A lambda that gets the register usage for the given type and VF.
   5615   auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
   5616     if (Ty->isTokenTy())
   5617       return 0U;
   5618     unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
   5619     return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
   5620   };
   5621 
   5622   for (unsigned int i = 0; i < Index; ++i) {
   5623     Instruction *I = IdxToInstr[i];
   5624     // Ignore instructions that are never used within the loop.
   5625     if (!Ends.count(I))
   5626       continue;
   5627 
   5628     // Remove all of the instructions that end at this location.
   5629     InstrList &List = TransposeEnds[i];
   5630     for (Instruction *ToRemove : List)
   5631       OpenIntervals.erase(ToRemove);
   5632 
   5633     // Skip ignored values.
   5634     if (ValuesToIgnore.count(I))
   5635       continue;
   5636 
   5637     // For each VF find the maximum usage of registers.
   5638     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
   5639       if (VFs[j] == 1) {
   5640         MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
   5641         continue;
   5642       }
   5643 
   5644       // Count the number of live intervals.
   5645       unsigned RegUsage = 0;
   5646       for (auto Inst : OpenIntervals) {
   5647         // Skip ignored values for VF > 1.
   5648         if (VecValuesToIgnore.count(Inst))
   5649           continue;
   5650         RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
   5651       }
   5652       MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
   5653     }
   5654 
   5655     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
   5656                  << OpenIntervals.size() << '\n');
   5657 
   5658     // Add the current instruction to the list of open intervals.
   5659     OpenIntervals.insert(I);
   5660   }
   5661 
   5662   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
   5663     unsigned Invariant = 0;
   5664     if (VFs[i] == 1)
   5665       Invariant = LoopInvariants.size();
   5666     else {
   5667       for (auto Inst : LoopInvariants)
   5668         Invariant += GetRegUsage(Inst->getType(), VFs[i]);
   5669     }
   5670 
   5671     DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
   5672     DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
   5673     DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
   5674     DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
   5675 
   5676     RU.LoopInvariantRegs = Invariant;
   5677     RU.MaxLocalUsers = MaxUsages[i];
   5678     RUs[i] = RU;
   5679   }
   5680 
   5681   return RUs;
   5682 }
   5683 
   5684 LoopVectorizationCostModel::VectorizationCostTy
   5685 LoopVectorizationCostModel::expectedCost(unsigned VF) {
   5686   VectorizationCostTy Cost;
   5687 
   5688   // For each block.
   5689   for (BasicBlock *BB : TheLoop->blocks()) {
   5690     VectorizationCostTy BlockCost;
   5691 
   5692     // For each instruction in the old loop.
   5693     for (Instruction &I : *BB) {
   5694       // Skip dbg intrinsics.
   5695       if (isa<DbgInfoIntrinsic>(I))
   5696         continue;
   5697 
   5698       // Skip ignored values.
   5699       if (ValuesToIgnore.count(&I))
   5700         continue;
   5701 
   5702       VectorizationCostTy C = getInstructionCost(&I, VF);
   5703 
   5704       // Check if we should override the cost.
   5705       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
   5706         C.first = ForceTargetInstructionCost;
   5707 
   5708       BlockCost.first += C.first;
   5709       BlockCost.second |= C.second;
   5710       DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF "
   5711                    << VF << " For instruction: " << I << '\n');
   5712     }
   5713 
   5714     // We assume that if-converted blocks have a 50% chance of being executed.
   5715     // When the code is scalar then some of the blocks are avoided due to CF.
   5716     // When the code is vectorized we execute all code paths.
   5717     if (VF == 1 && Legal->blockNeedsPredication(BB))
   5718       BlockCost.first /= 2;
   5719 
   5720     Cost.first += BlockCost.first;
   5721     Cost.second |= BlockCost.second;
   5722   }
   5723 
   5724   return Cost;
   5725 }
   5726 
   5727 /// \brief Check if the load/store instruction \p I may be translated into
   5728 /// gather/scatter during vectorization.
   5729 ///
   5730 /// Pointer \p Ptr specifies address in memory for the given scalar memory
   5731 /// instruction. We need it to retrieve data type.
   5732 /// Using gather/scatter is possible when it is supported by target.
   5733 static bool isGatherOrScatterLegal(Instruction *I, Value *Ptr,
   5734                                    LoopVectorizationLegality *Legal) {
   5735   auto *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
   5736   return (isa<LoadInst>(I) && Legal->isLegalMaskedGather(DataTy)) ||
   5737          (isa<StoreInst>(I) && Legal->isLegalMaskedScatter(DataTy));
   5738 }
   5739 
   5740 /// \brief Check whether the address computation for a non-consecutive memory
   5741 /// access looks like an unlikely candidate for being merged into the indexing
   5742 /// mode.
   5743 ///
   5744 /// We look for a GEP which has one index that is an induction variable and all
   5745 /// other indices are loop invariant. If the stride of this access is also
   5746 /// within a small bound we decide that this address computation can likely be
   5747 /// merged into the addressing mode.
   5748 /// In all other cases, we identify the address computation as complex.
   5749 static bool isLikelyComplexAddressComputation(Value *Ptr,
   5750                                               LoopVectorizationLegality *Legal,
   5751                                               ScalarEvolution *SE,
   5752                                               const Loop *TheLoop) {
   5753   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
   5754   if (!Gep)
   5755     return true;
   5756 
   5757   // We are looking for a gep with all loop invariant indices except for one
   5758   // which should be an induction variable.
   5759   unsigned NumOperands = Gep->getNumOperands();
   5760   for (unsigned i = 1; i < NumOperands; ++i) {
   5761     Value *Opd = Gep->getOperand(i);
   5762     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
   5763         !Legal->isInductionVariable(Opd))
   5764       return true;
   5765   }
   5766 
   5767   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
   5768   // can likely be merged into the address computation.
   5769   unsigned MaxMergeDistance = 64;
   5770 
   5771   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
   5772   if (!AddRec)
   5773     return true;
   5774 
   5775   // Check the step is constant.
   5776   const SCEV *Step = AddRec->getStepRecurrence(*SE);
   5777   // Calculate the pointer stride and check if it is consecutive.
   5778   const auto *C = dyn_cast<SCEVConstant>(Step);
   5779   if (!C)
   5780     return true;
   5781 
   5782   const APInt &APStepVal = C->getAPInt();
   5783 
   5784   // Huge step value - give up.
   5785   if (APStepVal.getBitWidth() > 64)
   5786     return true;
   5787 
   5788   int64_t StepVal = APStepVal.getSExtValue();
   5789 
   5790   return StepVal > MaxMergeDistance;
   5791 }
   5792 
   5793 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
   5794   return Legal->hasStride(I->getOperand(0)) ||
   5795          Legal->hasStride(I->getOperand(1));
   5796 }
   5797 
   5798 LoopVectorizationCostModel::VectorizationCostTy
   5799 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
   5800   // If we know that this instruction will remain uniform, check the cost of
   5801   // the scalar version.
   5802   if (Legal->isUniformAfterVectorization(I))
   5803     VF = 1;
   5804 
   5805   Type *VectorTy;
   5806   unsigned C = getInstructionCost(I, VF, VectorTy);
   5807 
   5808   bool TypeNotScalarized =
   5809       VF > 1 && !VectorTy->isVoidTy() && TTI.getNumberOfParts(VectorTy) < VF;
   5810   return VectorizationCostTy(C, TypeNotScalarized);
   5811 }
   5812 
   5813 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
   5814                                                         unsigned VF,
   5815                                                         Type *&VectorTy) {
   5816   Type *RetTy = I->getType();
   5817   if (VF > 1 && MinBWs.count(I))
   5818     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
   5819   VectorTy = ToVectorTy(RetTy, VF);
   5820   auto SE = PSE.getSE();
   5821 
   5822   // TODO: We need to estimate the cost of intrinsic calls.
   5823   switch (I->getOpcode()) {
   5824   case Instruction::GetElementPtr:
   5825     // We mark this instruction as zero-cost because the cost of GEPs in
   5826     // vectorized code depends on whether the corresponding memory instruction
   5827     // is scalarized or not. Therefore, we handle GEPs with the memory
   5828     // instruction cost.
   5829     return 0;
   5830   case Instruction::Br: {
   5831     return TTI.getCFInstrCost(I->getOpcode());
   5832   }
   5833   case Instruction::PHI: {
   5834     auto *Phi = cast<PHINode>(I);
   5835 
   5836     // First-order recurrences are replaced by vector shuffles inside the loop.
   5837     if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
   5838       return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
   5839                                 VectorTy, VF - 1, VectorTy);
   5840 
   5841     // TODO: IF-converted IFs become selects.
   5842     return 0;
   5843   }
   5844   case Instruction::Add:
   5845   case Instruction::FAdd:
   5846   case Instruction::Sub:
   5847   case Instruction::FSub:
   5848   case Instruction::Mul:
   5849   case Instruction::FMul:
   5850   case Instruction::UDiv:
   5851   case Instruction::SDiv:
   5852   case Instruction::FDiv:
   5853   case Instruction::URem:
   5854   case Instruction::SRem:
   5855   case Instruction::FRem:
   5856   case Instruction::Shl:
   5857   case Instruction::LShr:
   5858   case Instruction::AShr:
   5859   case Instruction::And:
   5860   case Instruction::Or:
   5861   case Instruction::Xor: {
   5862     // Since we will replace the stride by 1 the multiplication should go away.
   5863     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
   5864       return 0;
   5865     // Certain instructions can be cheaper to vectorize if they have a constant
   5866     // second vector operand. One example of this are shifts on x86.
   5867     TargetTransformInfo::OperandValueKind Op1VK =
   5868         TargetTransformInfo::OK_AnyValue;
   5869     TargetTransformInfo::OperandValueKind Op2VK =
   5870         TargetTransformInfo::OK_AnyValue;
   5871     TargetTransformInfo::OperandValueProperties Op1VP =
   5872         TargetTransformInfo::OP_None;
   5873     TargetTransformInfo::OperandValueProperties Op2VP =
   5874         TargetTransformInfo::OP_None;
   5875     Value *Op2 = I->getOperand(1);
   5876 
   5877     // Check for a splat of a constant or for a non uniform vector of constants.
   5878     if (isa<ConstantInt>(Op2)) {
   5879       ConstantInt *CInt = cast<ConstantInt>(Op2);
   5880       if (CInt && CInt->getValue().isPowerOf2())
   5881         Op2VP = TargetTransformInfo::OP_PowerOf2;
   5882       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
   5883     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
   5884       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
   5885       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
   5886       if (SplatValue) {
   5887         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
   5888         if (CInt && CInt->getValue().isPowerOf2())
   5889           Op2VP = TargetTransformInfo::OP_PowerOf2;
   5890         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
   5891       }
   5892     }
   5893 
   5894     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
   5895                                       Op1VP, Op2VP);
   5896   }
   5897   case Instruction::Select: {
   5898     SelectInst *SI = cast<SelectInst>(I);
   5899     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
   5900     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
   5901     Type *CondTy = SI->getCondition()->getType();
   5902     if (!ScalarCond)
   5903       CondTy = VectorType::get(CondTy, VF);
   5904 
   5905     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
   5906   }
   5907   case Instruction::ICmp:
   5908   case Instruction::FCmp: {
   5909     Type *ValTy = I->getOperand(0)->getType();
   5910     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
   5911     auto It = MinBWs.find(Op0AsInstruction);
   5912     if (VF > 1 && It != MinBWs.end())
   5913       ValTy = IntegerType::get(ValTy->getContext(), It->second);
   5914     VectorTy = ToVectorTy(ValTy, VF);
   5915     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
   5916   }
   5917   case Instruction::Store:
   5918   case Instruction::Load: {
   5919     StoreInst *SI = dyn_cast<StoreInst>(I);
   5920     LoadInst *LI = dyn_cast<LoadInst>(I);
   5921     Type *ValTy = (SI ? SI->getValueOperand()->getType() : LI->getType());
   5922     VectorTy = ToVectorTy(ValTy, VF);
   5923 
   5924     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
   5925     unsigned AS =
   5926         SI ? SI->getPointerAddressSpace() : LI->getPointerAddressSpace();
   5927     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
   5928     // We add the cost of address computation here instead of with the gep
   5929     // instruction because only here we know whether the operation is
   5930     // scalarized.
   5931     if (VF == 1)
   5932       return TTI.getAddressComputationCost(VectorTy) +
   5933              TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
   5934 
   5935     if (LI && Legal->isUniform(Ptr)) {
   5936       // Scalar load + broadcast
   5937       unsigned Cost = TTI.getAddressComputationCost(ValTy->getScalarType());
   5938       Cost += TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
   5939                                   Alignment, AS);
   5940       return Cost +
   5941              TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, ValTy);
   5942     }
   5943 
   5944     // For an interleaved access, calculate the total cost of the whole
   5945     // interleave group.
   5946     if (Legal->isAccessInterleaved(I)) {
   5947       auto Group = Legal->getInterleavedAccessGroup(I);
   5948       assert(Group && "Fail to get an interleaved access group.");
   5949 
   5950       // Only calculate the cost once at the insert position.
   5951       if (Group->getInsertPos() != I)
   5952         return 0;
   5953 
   5954       unsigned InterleaveFactor = Group->getFactor();
   5955       Type *WideVecTy =
   5956           VectorType::get(VectorTy->getVectorElementType(),
   5957                           VectorTy->getVectorNumElements() * InterleaveFactor);
   5958 
   5959       // Holds the indices of existing members in an interleaved load group.
   5960       // An interleaved store group doesn't need this as it doesn't allow gaps.
   5961       SmallVector<unsigned, 4> Indices;
   5962       if (LI) {
   5963         for (unsigned i = 0; i < InterleaveFactor; i++)
   5964           if (Group->getMember(i))
   5965             Indices.push_back(i);
   5966       }
   5967 
   5968       // Calculate the cost of the whole interleaved group.
   5969       unsigned Cost = TTI.getInterleavedMemoryOpCost(
   5970           I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
   5971           Group->getAlignment(), AS);
   5972 
   5973       if (Group->isReverse())
   5974         Cost +=
   5975             Group->getNumMembers() *
   5976             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
   5977 
   5978       // FIXME: The interleaved load group with a huge gap could be even more
   5979       // expensive than scalar operations. Then we could ignore such group and
   5980       // use scalar operations instead.
   5981       return Cost;
   5982     }
   5983 
   5984     // Scalarized loads/stores.
   5985     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
   5986     bool UseGatherOrScatter =
   5987         (ConsecutiveStride == 0) && isGatherOrScatterLegal(I, Ptr, Legal);
   5988 
   5989     bool Reverse = ConsecutiveStride < 0;
   5990     const DataLayout &DL = I->getModule()->getDataLayout();
   5991     uint64_t ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
   5992     uint64_t VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
   5993     if ((!ConsecutiveStride && !UseGatherOrScatter) ||
   5994         ScalarAllocatedSize != VectorElementSize) {
   5995       bool IsComplexComputation =
   5996           isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
   5997       unsigned Cost = 0;
   5998       // The cost of extracting from the value vector and pointer vector.
   5999       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
   6000       for (unsigned i = 0; i < VF; ++i) {
   6001         //  The cost of extracting the pointer operand.
   6002         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
   6003         // In case of STORE, the cost of ExtractElement from the vector.
   6004         // In case of LOAD, the cost of InsertElement into the returned
   6005         // vector.
   6006         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement
   6007                                           : Instruction::InsertElement,
   6008                                        VectorTy, i);
   6009       }
   6010 
   6011       // The cost of the scalar loads/stores.
   6012       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
   6013       Cost += VF *
   6014               TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
   6015                                   Alignment, AS);
   6016       return Cost;
   6017     }
   6018 
   6019     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
   6020     if (UseGatherOrScatter) {
   6021       assert(ConsecutiveStride == 0 &&
   6022              "Gather/Scatter are not used for consecutive stride");
   6023       return Cost +
   6024              TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
   6025                                         Legal->isMaskRequired(I), Alignment);
   6026     }
   6027     // Wide load/stores.
   6028     if (Legal->isMaskRequired(I))
   6029       Cost +=
   6030           TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
   6031     else
   6032       Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
   6033 
   6034     if (Reverse)
   6035       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
   6036     return Cost;
   6037   }
   6038   case Instruction::ZExt:
   6039   case Instruction::SExt:
   6040   case Instruction::FPToUI:
   6041   case Instruction::FPToSI:
   6042   case Instruction::FPExt:
   6043   case Instruction::PtrToInt:
   6044   case Instruction::IntToPtr:
   6045   case Instruction::SIToFP:
   6046   case Instruction::UIToFP:
   6047   case Instruction::Trunc:
   6048   case Instruction::FPTrunc:
   6049   case Instruction::BitCast: {
   6050     // We optimize the truncation of induction variable.
   6051     // The cost of these is the same as the scalar operation.
   6052     if (I->getOpcode() == Instruction::Trunc &&
   6053         Legal->isInductionVariable(I->getOperand(0)))
   6054       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
   6055                                   I->getOperand(0)->getType());
   6056 
   6057     Type *SrcScalarTy = I->getOperand(0)->getType();
   6058     Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
   6059     if (VF > 1 && MinBWs.count(I)) {
   6060       // This cast is going to be shrunk. This may remove the cast or it might
   6061       // turn it into slightly different cast. For example, if MinBW == 16,
   6062       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
   6063       //
   6064       // Calculate the modified src and dest types.
   6065       Type *MinVecTy = VectorTy;
   6066       if (I->getOpcode() == Instruction::Trunc) {
   6067         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
   6068         VectorTy =
   6069             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
   6070       } else if (I->getOpcode() == Instruction::ZExt ||
   6071                  I->getOpcode() == Instruction::SExt) {
   6072         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
   6073         VectorTy =
   6074             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
   6075       }
   6076     }
   6077 
   6078     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
   6079   }
   6080   case Instruction::Call: {
   6081     bool NeedToScalarize;
   6082     CallInst *CI = cast<CallInst>(I);
   6083     unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
   6084     if (getVectorIntrinsicIDForCall(CI, TLI))
   6085       return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
   6086     return CallCost;
   6087   }
   6088   default: {
   6089     // We are scalarizing the instruction. Return the cost of the scalar
   6090     // instruction, plus the cost of insert and extract into vector
   6091     // elements, times the vector width.
   6092     unsigned Cost = 0;
   6093 
   6094     if (!RetTy->isVoidTy() && VF != 1) {
   6095       unsigned InsCost =
   6096           TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy);
   6097       unsigned ExtCost =
   6098           TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy);
   6099 
   6100       // The cost of inserting the results plus extracting each one of the
   6101       // operands.
   6102       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
   6103     }
   6104 
   6105     // The cost of executing VF copies of the scalar instruction. This opcode
   6106     // is unknown. Assume that it is the same as 'mul'.
   6107     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
   6108     return Cost;
   6109   }
   6110   } // end of switch.
   6111 }
   6112 
   6113 char LoopVectorize::ID = 0;
   6114 static const char lv_name[] = "Loop Vectorization";
   6115 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
   6116 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
   6117 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
   6118 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
   6119 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
   6120 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
   6121 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
   6122 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
   6123 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
   6124 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
   6125 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
   6126 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
   6127 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
   6128 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
   6129 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
   6130 
   6131 namespace llvm {
   6132 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
   6133   return new LoopVectorize(NoUnrolling, AlwaysVectorize);
   6134 }
   6135 }
   6136 
   6137 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
   6138   // Check for a store.
   6139   if (auto *ST = dyn_cast<StoreInst>(Inst))
   6140     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
   6141 
   6142   // Check for a load.
   6143   if (auto *LI = dyn_cast<LoadInst>(Inst))
   6144     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
   6145 
   6146   return false;
   6147 }
   6148 
   6149 void LoopVectorizationCostModel::collectValuesToIgnore() {
   6150   // Ignore ephemeral values.
   6151   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
   6152 
   6153   // Ignore type-promoting instructions we identified during reduction
   6154   // detection.
   6155   for (auto &Reduction : *Legal->getReductionVars()) {
   6156     RecurrenceDescriptor &RedDes = Reduction.second;
   6157     SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
   6158     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
   6159   }
   6160 
   6161   // Ignore induction phis that are only used in either GetElementPtr or ICmp
   6162   // instruction to exit loop. Induction variables usually have large types and
   6163   // can have big impact when estimating register usage.
   6164   // This is for when VF > 1.
   6165   for (auto &Induction : *Legal->getInductionVars()) {
   6166     auto *PN = Induction.first;
   6167     auto *UpdateV = PN->getIncomingValueForBlock(TheLoop->getLoopLatch());
   6168 
   6169     // Check that the PHI is only used by the induction increment (UpdateV) or
   6170     // by GEPs. Then check that UpdateV is only used by a compare instruction,
   6171     // the loop header PHI, or by GEPs.
   6172     // FIXME: Need precise def-use analysis to determine if this instruction
   6173     // variable will be vectorized.
   6174     if (all_of(PN->users(),
   6175                [&](const User *U) -> bool {
   6176                  return U == UpdateV || isa<GetElementPtrInst>(U);
   6177                }) &&
   6178         all_of(UpdateV->users(), [&](const User *U) -> bool {
   6179           return U == PN || isa<ICmpInst>(U) || isa<GetElementPtrInst>(U);
   6180         })) {
   6181       VecValuesToIgnore.insert(PN);
   6182       VecValuesToIgnore.insert(UpdateV);
   6183     }
   6184   }
   6185 
   6186   // Ignore instructions that will not be vectorized.
   6187   // This is for when VF > 1.
   6188   for (BasicBlock *BB : TheLoop->blocks()) {
   6189     for (auto &Inst : *BB) {
   6190       switch (Inst.getOpcode())
   6191       case Instruction::GetElementPtr: {
   6192         // Ignore GEP if its last operand is an induction variable so that it is
   6193         // a consecutive load/store and won't be vectorized as scatter/gather
   6194         // pattern.
   6195 
   6196         GetElementPtrInst *Gep = cast<GetElementPtrInst>(&Inst);
   6197         unsigned NumOperands = Gep->getNumOperands();
   6198         unsigned InductionOperand = getGEPInductionOperand(Gep);
   6199         bool GepToIgnore = true;
   6200 
   6201         // Check that all of the gep indices are uniform except for the
   6202         // induction operand.
   6203         for (unsigned i = 0; i != NumOperands; ++i) {
   6204           if (i != InductionOperand &&
   6205               !PSE.getSE()->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)),
   6206                                             TheLoop)) {
   6207             GepToIgnore = false;
   6208             break;
   6209           }
   6210         }
   6211 
   6212         if (GepToIgnore)
   6213           VecValuesToIgnore.insert(&Inst);
   6214         break;
   6215       }
   6216     }
   6217   }
   6218 }
   6219 
   6220 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
   6221                                              bool IfPredicateStore) {
   6222   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
   6223   // Holds vector parameters or scalars, in case of uniform vals.
   6224   SmallVector<VectorParts, 4> Params;
   6225 
   6226   setDebugLocFromInst(Builder, Instr);
   6227 
   6228   // Find all of the vectorized parameters.
   6229   for (Value *SrcOp : Instr->operands()) {
   6230     // If we are accessing the old induction variable, use the new one.
   6231     if (SrcOp == OldInduction) {
   6232       Params.push_back(getVectorValue(SrcOp));
   6233       continue;
   6234     }
   6235 
   6236     // Try using previously calculated values.
   6237     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
   6238 
   6239     // If the src is an instruction that appeared earlier in the basic block
   6240     // then it should already be vectorized.
   6241     if (SrcInst && OrigLoop->contains(SrcInst)) {
   6242       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
   6243       // The parameter is a vector value from earlier.
   6244       Params.push_back(WidenMap.get(SrcInst));
   6245     } else {
   6246       // The parameter is a scalar from outside the loop. Maybe even a constant.
   6247       VectorParts Scalars;
   6248       Scalars.append(UF, SrcOp);
   6249       Params.push_back(Scalars);
   6250     }
   6251   }
   6252 
   6253   assert(Params.size() == Instr->getNumOperands() &&
   6254          "Invalid number of operands");
   6255 
   6256   // Does this instruction return a value ?
   6257   bool IsVoidRetTy = Instr->getType()->isVoidTy();
   6258 
   6259   Value *UndefVec = IsVoidRetTy ? nullptr : UndefValue::get(Instr->getType());
   6260   // Create a new entry in the WidenMap and initialize it to Undef or Null.
   6261   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
   6262 
   6263   VectorParts Cond;
   6264   if (IfPredicateStore) {
   6265     assert(Instr->getParent()->getSinglePredecessor() &&
   6266            "Only support single predecessor blocks");
   6267     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
   6268                           Instr->getParent());
   6269   }
   6270 
   6271   // For each vector unroll 'part':
   6272   for (unsigned Part = 0; Part < UF; ++Part) {
   6273     // For each scalar that we create:
   6274 
   6275     // Start an "if (pred) a[i] = ..." block.
   6276     Value *Cmp = nullptr;
   6277     if (IfPredicateStore) {
   6278       if (Cond[Part]->getType()->isVectorTy())
   6279         Cond[Part] =
   6280             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
   6281       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
   6282                                ConstantInt::get(Cond[Part]->getType(), 1));
   6283     }
   6284 
   6285     Instruction *Cloned = Instr->clone();
   6286     if (!IsVoidRetTy)
   6287       Cloned->setName(Instr->getName() + ".cloned");
   6288     // Replace the operands of the cloned instructions with extracted scalars.
   6289     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
   6290       Value *Op = Params[op][Part];
   6291       Cloned->setOperand(op, Op);
   6292     }
   6293 
   6294     // Place the cloned scalar in the new loop.
   6295     Builder.Insert(Cloned);
   6296 
   6297     // If we just cloned a new assumption, add it the assumption cache.
   6298     if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
   6299       if (II->getIntrinsicID() == Intrinsic::assume)
   6300         AC->registerAssumption(II);
   6301 
   6302     // If the original scalar returns a value we need to place it in a vector
   6303     // so that future users will be able to use it.
   6304     if (!IsVoidRetTy)
   6305       VecResults[Part] = Cloned;
   6306 
   6307     // End if-block.
   6308     if (IfPredicateStore)
   6309       PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned), Cmp));
   6310   }
   6311 }
   6312 
   6313 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
   6314   auto *SI = dyn_cast<StoreInst>(Instr);
   6315   bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
   6316 
   6317   return scalarizeInstruction(Instr, IfPredicateStore);
   6318 }
   6319 
   6320 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
   6321 
   6322 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
   6323 
   6324 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
   6325   // When unrolling and the VF is 1, we only need to add a simple scalar.
   6326   Type *ITy = Val->getType();
   6327   assert(!ITy->isVectorTy() && "Val must be a scalar");
   6328   Constant *C = ConstantInt::get(ITy, StartIdx);
   6329   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
   6330 }
   6331 
   6332 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
   6333   SmallVector<Metadata *, 4> MDs;
   6334   // Reserve first location for self reference to the LoopID metadata node.
   6335   MDs.push_back(nullptr);
   6336   bool IsUnrollMetadata = false;
   6337   MDNode *LoopID = L->getLoopID();
   6338   if (LoopID) {
   6339     // First find existing loop unrolling disable metadata.
   6340     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
   6341       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
   6342       if (MD) {
   6343         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
   6344         IsUnrollMetadata =
   6345             S && S->getString().startswith("llvm.loop.unroll.disable");
   6346       }
   6347       MDs.push_back(LoopID->getOperand(i));
   6348     }
   6349   }
   6350 
   6351   if (!IsUnrollMetadata) {
   6352     // Add runtime unroll disable metadata.
   6353     LLVMContext &Context = L->getHeader()->getContext();
   6354     SmallVector<Metadata *, 1> DisableOperands;
   6355     DisableOperands.push_back(
   6356         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
   6357     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
   6358     MDs.push_back(DisableNode);
   6359     MDNode *NewLoopID = MDNode::get(Context, MDs);
   6360     // Set operand 0 to refer to the loop id itself.
   6361     NewLoopID->replaceOperandWith(0, NewLoopID);
   6362     L->setLoopID(NewLoopID);
   6363   }
   6364 }
   6365 
   6366 bool LoopVectorizePass::processLoop(Loop *L) {
   6367   assert(L->empty() && "Only process inner loops.");
   6368 
   6369 #ifndef NDEBUG
   6370   const std::string DebugLocStr = getDebugLocString(L);
   6371 #endif /* NDEBUG */
   6372 
   6373   DEBUG(dbgs() << "\nLV: Checking a loop in \""
   6374                << L->getHeader()->getParent()->getName() << "\" from "
   6375                << DebugLocStr << "\n");
   6376 
   6377   LoopVectorizeHints Hints(L, DisableUnrolling);
   6378 
   6379   DEBUG(dbgs() << "LV: Loop hints:"
   6380                << " force="
   6381                << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
   6382                        ? "disabled"
   6383                        : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
   6384                               ? "enabled"
   6385                               : "?"))
   6386                << " width=" << Hints.getWidth()
   6387                << " unroll=" << Hints.getInterleave() << "\n");
   6388 
   6389   // Function containing loop
   6390   Function *F = L->getHeader()->getParent();
   6391 
   6392   // Looking at the diagnostic output is the only way to determine if a loop
   6393   // was vectorized (other than looking at the IR or machine code), so it
   6394   // is important to generate an optimization remark for each loop. Most of
   6395   // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
   6396   // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
   6397   // less verbose reporting vectorized loops and unvectorized loops that may
   6398   // benefit from vectorization, respectively.
   6399 
   6400   if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
   6401     DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
   6402     return false;
   6403   }
   6404 
   6405   // Check the loop for a trip count threshold:
   6406   // do not vectorize loops with a tiny trip count.
   6407   const unsigned TC = SE->getSmallConstantTripCount(L);
   6408   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
   6409     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
   6410                  << "This loop is not worth vectorizing.");
   6411     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
   6412       DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
   6413     else {
   6414       DEBUG(dbgs() << "\n");
   6415       emitAnalysisDiag(F, L, Hints, VectorizationReport()
   6416                                         << "vectorization is not beneficial "
   6417                                            "and is not explicitly forced");
   6418       return false;
   6419     }
   6420   }
   6421 
   6422   PredicatedScalarEvolution PSE(*SE, *L);
   6423 
   6424   // Check if it is legal to vectorize the loop.
   6425   LoopVectorizationRequirements Requirements;
   6426   LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI,
   6427                                 &Requirements, &Hints);
   6428   if (!LVL.canVectorize()) {
   6429     DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
   6430     emitMissedWarning(F, L, Hints);
   6431     return false;
   6432   }
   6433 
   6434   // Use the cost model.
   6435   LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, F,
   6436                                 &Hints);
   6437   CM.collectValuesToIgnore();
   6438 
   6439   // Check the function attributes to find out if this function should be
   6440   // optimized for size.
   6441   bool OptForSize =
   6442       Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
   6443 
   6444   // Compute the weighted frequency of this loop being executed and see if it
   6445   // is less than 20% of the function entry baseline frequency. Note that we
   6446   // always have a canonical loop here because we think we *can* vectorize.
   6447   // FIXME: This is hidden behind a flag due to pervasive problems with
   6448   // exactly what block frequency models.
   6449   if (LoopVectorizeWithBlockFrequency) {
   6450     BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
   6451     if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
   6452         LoopEntryFreq < ColdEntryFreq)
   6453       OptForSize = true;
   6454   }
   6455 
   6456   // Check the function attributes to see if implicit floats are allowed.
   6457   // FIXME: This check doesn't seem possibly correct -- what if the loop is
   6458   // an integer loop and the vector instructions selected are purely integer
   6459   // vector instructions?
   6460   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
   6461     DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
   6462                     "attribute is used.\n");
   6463     emitAnalysisDiag(
   6464         F, L, Hints,
   6465         VectorizationReport()
   6466             << "loop not vectorized due to NoImplicitFloat attribute");
   6467     emitMissedWarning(F, L, Hints);
   6468     return false;
   6469   }
   6470 
   6471   // Check if the target supports potentially unsafe FP vectorization.
   6472   // FIXME: Add a check for the type of safety issue (denormal, signaling)
   6473   // for the target we're vectorizing for, to make sure none of the
   6474   // additional fp-math flags can help.
   6475   if (Hints.isPotentiallyUnsafe() &&
   6476       TTI->isFPVectorizationPotentiallyUnsafe()) {
   6477     DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
   6478     emitAnalysisDiag(F, L, Hints,
   6479                      VectorizationReport()
   6480                          << "loop not vectorized due to unsafe FP support.");
   6481     emitMissedWarning(F, L, Hints);
   6482     return false;
   6483   }
   6484 
   6485   // Select the optimal vectorization factor.
   6486   const LoopVectorizationCostModel::VectorizationFactor VF =
   6487       CM.selectVectorizationFactor(OptForSize);
   6488 
   6489   // Select the interleave count.
   6490   unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
   6491 
   6492   // Get user interleave count.
   6493   unsigned UserIC = Hints.getInterleave();
   6494 
   6495   // Identify the diagnostic messages that should be produced.
   6496   std::string VecDiagMsg, IntDiagMsg;
   6497   bool VectorizeLoop = true, InterleaveLoop = true;
   6498 
   6499   if (Requirements.doesNotMeet(F, L, Hints)) {
   6500     DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
   6501                     "requirements.\n");
   6502     emitMissedWarning(F, L, Hints);
   6503     return false;
   6504   }
   6505 
   6506   if (VF.Width == 1) {
   6507     DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
   6508     VecDiagMsg =
   6509         "the cost-model indicates that vectorization is not beneficial";
   6510     VectorizeLoop = false;
   6511   }
   6512 
   6513   if (IC == 1 && UserIC <= 1) {
   6514     // Tell the user interleaving is not beneficial.
   6515     DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
   6516     IntDiagMsg =
   6517         "the cost-model indicates that interleaving is not beneficial";
   6518     InterleaveLoop = false;
   6519     if (UserIC == 1)
   6520       IntDiagMsg +=
   6521           " and is explicitly disabled or interleave count is set to 1";
   6522   } else if (IC > 1 && UserIC == 1) {
   6523     // Tell the user interleaving is beneficial, but it explicitly disabled.
   6524     DEBUG(dbgs()
   6525           << "LV: Interleaving is beneficial but is explicitly disabled.");
   6526     IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
   6527                  "but is explicitly disabled or interleave count is set to 1";
   6528     InterleaveLoop = false;
   6529   }
   6530 
   6531   // Override IC if user provided an interleave count.
   6532   IC = UserIC > 0 ? UserIC : IC;
   6533 
   6534   // Emit diagnostic messages, if any.
   6535   const char *VAPassName = Hints.vectorizeAnalysisPassName();
   6536   if (!VectorizeLoop && !InterleaveLoop) {
   6537     // Do not vectorize or interleaving the loop.
   6538     emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
   6539                                    L->getStartLoc(), VecDiagMsg);
   6540     emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
   6541                                    L->getStartLoc(), IntDiagMsg);
   6542     return false;
   6543   } else if (!VectorizeLoop && InterleaveLoop) {
   6544     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
   6545     emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
   6546                                    L->getStartLoc(), VecDiagMsg);
   6547   } else if (VectorizeLoop && !InterleaveLoop) {
   6548     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
   6549                  << DebugLocStr << '\n');
   6550     emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
   6551                                    L->getStartLoc(), IntDiagMsg);
   6552   } else if (VectorizeLoop && InterleaveLoop) {
   6553     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
   6554                  << DebugLocStr << '\n');
   6555     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
   6556   }
   6557 
   6558   if (!VectorizeLoop) {
   6559     assert(IC > 1 && "interleave count should not be 1 or 0");
   6560     // If we decided that it is not legal to vectorize the loop, then
   6561     // interleave it.
   6562     InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, IC);
   6563     Unroller.vectorize(&LVL, CM.MinBWs, CM.VecValuesToIgnore);
   6564 
   6565     emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
   6566                            Twine("interleaved loop (interleaved count: ") +
   6567                                Twine(IC) + ")");
   6568   } else {
   6569     // If we decided that it is *legal* to vectorize the loop, then do it.
   6570     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, VF.Width, IC);
   6571     LB.vectorize(&LVL, CM.MinBWs, CM.VecValuesToIgnore);
   6572     ++LoopsVectorized;
   6573 
   6574     // Add metadata to disable runtime unrolling a scalar loop when there are
   6575     // no runtime checks about strides and memory. A scalar loop that is
   6576     // rarely used is not worth unrolling.
   6577     if (!LB.areSafetyChecksAdded())
   6578       AddRuntimeUnrollDisableMetaData(L);
   6579 
   6580     // Report the vectorization decision.
   6581     emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
   6582                            Twine("vectorized loop (vectorization width: ") +
   6583                                Twine(VF.Width) + ", interleaved count: " +
   6584                                Twine(IC) + ")");
   6585   }
   6586 
   6587   // Mark the loop as already vectorized to avoid vectorizing again.
   6588   Hints.setAlreadyVectorized();
   6589 
   6590   DEBUG(verifyFunction(*L->getHeader()->getParent()));
   6591   return true;
   6592 }
   6593 
   6594 bool LoopVectorizePass::runImpl(
   6595     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
   6596     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
   6597     DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
   6598     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_) {
   6599 
   6600   SE = &SE_;
   6601   LI = &LI_;
   6602   TTI = &TTI_;
   6603   DT = &DT_;
   6604   BFI = &BFI_;
   6605   TLI = TLI_;
   6606   AA = &AA_;
   6607   AC = &AC_;
   6608   GetLAA = &GetLAA_;
   6609   DB = &DB_;
   6610 
   6611   // Compute some weights outside of the loop over the loops. Compute this
   6612   // using a BranchProbability to re-use its scaling math.
   6613   const BranchProbability ColdProb(1, 5); // 20%
   6614   ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
   6615 
   6616   // Don't attempt if
   6617   // 1. the target claims to have no vector registers, and
   6618   // 2. interleaving won't help ILP.
   6619   //
   6620   // The second condition is necessary because, even if the target has no
   6621   // vector registers, loop vectorization may still enable scalar
   6622   // interleaving.
   6623   if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
   6624     return false;
   6625 
   6626   // Build up a worklist of inner-loops to vectorize. This is necessary as
   6627   // the act of vectorizing or partially unrolling a loop creates new loops
   6628   // and can invalidate iterators across the loops.
   6629   SmallVector<Loop *, 8> Worklist;
   6630 
   6631   for (Loop *L : *LI)
   6632     addInnerLoop(*L, Worklist);
   6633 
   6634   LoopsAnalyzed += Worklist.size();
   6635 
   6636   // Now walk the identified inner loops.
   6637   bool Changed = false;
   6638   while (!Worklist.empty())
   6639     Changed |= processLoop(Worklist.pop_back_val());
   6640 
   6641   // Process each loop nest in the function.
   6642   return Changed;
   6643 
   6644 }
   6645 
   6646 
   6647 PreservedAnalyses LoopVectorizePass::run(Function &F,
   6648                                          FunctionAnalysisManager &AM) {
   6649     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
   6650     auto &LI = AM.getResult<LoopAnalysis>(F);
   6651     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
   6652     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
   6653     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
   6654     auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
   6655     auto &AA = AM.getResult<AAManager>(F);
   6656     auto &AC = AM.getResult<AssumptionAnalysis>(F);
   6657     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
   6658 
   6659     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
   6660     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
   6661         [&](Loop &L) -> const LoopAccessInfo & {
   6662       return LAM.getResult<LoopAccessAnalysis>(L);
   6663     };
   6664     bool Changed = runImpl(F, SE, LI, TTI, DT, BFI, TLI, DB, AA, AC, GetLAA);
   6665     if (!Changed)
   6666       return PreservedAnalyses::all();
   6667     PreservedAnalyses PA;
   6668     PA.preserve<LoopAnalysis>();
   6669     PA.preserve<DominatorTreeAnalysis>();
   6670     PA.preserve<BasicAA>();
   6671     PA.preserve<GlobalsAA>();
   6672     return PA;
   6673 }
   6674