1 //===- LoadStoreVectorizer.cpp - GPU Load & Store Vectorizer --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass merges loads/stores to/from sequential memory addresses into vector
10 // loads/stores.  Although there's nothing GPU-specific in here, this pass is
11 // motivated by the microarchitectural quirks of nVidia and AMD GPUs.
12 //
13 // (For simplicity below we talk about loads only, but everything also applies
14 // to stores.)
15 //
16 // This pass is intended to be run late in the pipeline, after other
17 // vectorization opportunities have been exploited.  So the assumption here is
18 // that immediately following our new vector load we'll need to extract out the
19 // individual elements of the load, so we can operate on them individually.
20 //
21 // On CPUs this transformation is usually not beneficial, because extracting the
22 // elements of a vector register is expensive on most architectures.  It's
23 // usually better just to load each element individually into its own scalar
24 // register.
25 //
26 // However, nVidia and AMD GPUs don't have proper vector registers.  Instead, a
27 // "vector load" loads directly into a series of scalar registers.  In effect,
28 // extracting the elements of the vector is free.  It's therefore always
29 // beneficial to vectorize a sequence of loads on these architectures.
30 //
31 // Vectorizing (perhaps a better name might be "coalescing") loads can have
32 // large performance impacts on GPU kernels, and opportunities for vectorizing
33 // are common in GPU code.  This pass tries very hard to find such
34 // opportunities; its runtime is quadratic in the number of loads in a BB.
35 //
36 // Some CPU architectures, such as ARM, have instructions that load into
37 // multiple scalar registers, similar to a GPU vectorized load.  In theory ARM
38 // could use this pass (with some modifications), but currently it implements
39 // its own pass to do something similar to what we do here.
40 
41 #include "llvm/ADT/APInt.h"
42 #include "llvm/ADT/ArrayRef.h"
43 #include "llvm/ADT/MapVector.h"
44 #include "llvm/ADT/PostOrderIterator.h"
45 #include "llvm/ADT/STLExtras.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/iterator_range.h"
50 #include "llvm/Analysis/AliasAnalysis.h"
51 #include "llvm/Analysis/MemoryLocation.h"
52 #include "llvm/Analysis/OrderedBasicBlock.h"
53 #include "llvm/Analysis/ScalarEvolution.h"
54 #include "llvm/Analysis/TargetTransformInfo.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Analysis/ValueTracking.h"
57 #include "llvm/Analysis/VectorUtils.h"
58 #include "llvm/IR/Attributes.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DerivedTypes.h"
63 #include "llvm/IR/Dominators.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/IRBuilder.h"
66 #include "llvm/IR/InstrTypes.h"
67 #include "llvm/IR/Instruction.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/IntrinsicInst.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/Pass.h"
75 #include "llvm/Support/Casting.h"
76 #include "llvm/Support/Debug.h"
77 #include "llvm/Support/KnownBits.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Transforms/Vectorize.h"
81 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
82 #include <algorithm>
83 #include <cassert>
84 #include <cstdlib>
85 #include <tuple>
86 #include <utility>
87 
88 using namespace llvm;
89 
90 #define DEBUG_TYPE "load-store-vectorizer"
91 
92 STATISTIC(NumVectorInstructions, "Number of vector accesses generated");
93 STATISTIC(NumScalarsVectorized, "Number of scalar accesses vectorized");
94 
95 // FIXME: Assuming stack alignment of 4 is always good enough
96 static const unsigned StackAdjustedAlignment = 4;
97 
98 namespace {
99 
100 /// ChainID is an arbitrary token that is allowed to be different only for the
101 /// accesses that are guaranteed to be considered non-consecutive by
102 /// Vectorizer::isConsecutiveAccess. It's used for grouping instructions
103 /// together and reducing the number of instructions the main search operates on
104 /// at a time, i.e. this is to reduce compile time and nothing else as the main
105 /// search has O(n^2) time complexity. The underlying type of ChainID should not
106 /// be relied upon.
107 using ChainID = const Value *;
108 using InstrList = SmallVector<Instruction *, 8>;
109 using InstrListMap = MapVector<ChainID, InstrList>;
110 
111 class Vectorizer {
112   Function &F;
113   AliasAnalysis &AA;
114   DominatorTree &DT;
115   ScalarEvolution &SE;
116   TargetTransformInfo &TTI;
117   const DataLayout &DL;
118   IRBuilder<> Builder;
119 
120 public:
121   Vectorizer(Function &F, AliasAnalysis &AA, DominatorTree &DT,
122              ScalarEvolution &SE, TargetTransformInfo &TTI)
123       : F(F), AA(AA), DT(DT), SE(SE), TTI(TTI),
124         DL(F.getParent()->getDataLayout()), Builder(SE.getContext()) {}
125 
126   bool run();
127 
128 private:
129   unsigned getPointerAddressSpace(Value *I);
130 
131   unsigned getAlignment(LoadInst *LI) const {
132     unsigned Align = LI->getAlignment();
133     if (Align != 0)
134       return Align;
135 
136     return DL.getABITypeAlignment(LI->getType());
137   }
138 
139   unsigned getAlignment(StoreInst *SI) const {
140     unsigned Align = SI->getAlignment();
141     if (Align != 0)
142       return Align;
143 
144     return DL.getABITypeAlignment(SI->getValueOperand()->getType());
145   }
146 
147   static const unsigned MaxDepth = 3;
148 
149   bool isConsecutiveAccess(Value *A, Value *B);
150   bool areConsecutivePointers(Value *PtrA, Value *PtrB, const APInt &PtrDelta,
151                               unsigned Depth = 0) const;
152   bool lookThroughComplexAddresses(Value *PtrA, Value *PtrB, APInt PtrDelta,
153                                    unsigned Depth) const;
154   bool lookThroughSelects(Value *PtrA, Value *PtrB, const APInt &PtrDelta,
155                           unsigned Depth) const;
156 
157   /// After vectorization, reorder the instructions that I depends on
158   /// (the instructions defining its operands), to ensure they dominate I.
159   void reorder(Instruction *I);
160 
161   /// Returns the first and the last instructions in Chain.
162   std::pair<BasicBlock::iterator, BasicBlock::iterator>
163   getBoundaryInstrs(ArrayRef<Instruction *> Chain);
164 
165   /// Erases the original instructions after vectorizing.
166   void eraseInstructions(ArrayRef<Instruction *> Chain);
167 
168   /// "Legalize" the vector type that would be produced by combining \p
169   /// ElementSizeBits elements in \p Chain. Break into two pieces such that the
170   /// total size of each piece is 1, 2 or a multiple of 4 bytes. \p Chain is
171   /// expected to have more than 4 elements.
172   std::pair<ArrayRef<Instruction *>, ArrayRef<Instruction *>>
173   splitOddVectorElts(ArrayRef<Instruction *> Chain, unsigned ElementSizeBits);
174 
175   /// Finds the largest prefix of Chain that's vectorizable, checking for
176   /// intervening instructions which may affect the memory accessed by the
177   /// instructions within Chain.
178   ///
179   /// The elements of \p Chain must be all loads or all stores and must be in
180   /// address order.
181   ArrayRef<Instruction *> getVectorizablePrefix(ArrayRef<Instruction *> Chain);
182 
183   /// Collects load and store instructions to vectorize.
184   std::pair<InstrListMap, InstrListMap> collectInstructions(BasicBlock *BB);
185 
186   /// Processes the collected instructions, the \p Map. The values of \p Map
187   /// should be all loads or all stores.
188   bool vectorizeChains(InstrListMap &Map);
189 
190   /// Finds the load/stores to consecutive memory addresses and vectorizes them.
191   bool vectorizeInstructions(ArrayRef<Instruction *> Instrs);
192 
193   /// Vectorizes the load instructions in Chain.
194   bool
195   vectorizeLoadChain(ArrayRef<Instruction *> Chain,
196                      SmallPtrSet<Instruction *, 16> *InstructionsProcessed);
197 
198   /// Vectorizes the store instructions in Chain.
199   bool
200   vectorizeStoreChain(ArrayRef<Instruction *> Chain,
201                       SmallPtrSet<Instruction *, 16> *InstructionsProcessed);
202 
203   /// Check if this load/store access is misaligned accesses.
204   bool accessIsMisaligned(unsigned SzInBytes, unsigned AddressSpace,
205                           unsigned Alignment);
206 };
207 
208 class LoadStoreVectorizerLegacyPass : public FunctionPass {
209 public:
210   static char ID;
211 
212   LoadStoreVectorizerLegacyPass() : FunctionPass(ID) {
213     initializeLoadStoreVectorizerLegacyPassPass(*PassRegistry::getPassRegistry());
214   }
215 
216   bool runOnFunction(Function &F) override;
217 
218   StringRef getPassName() const override {
219     return "GPU Load and Store Vectorizer";
220   }
221 
222   void getAnalysisUsage(AnalysisUsage &AU) const override {
223     AU.addRequired<AAResultsWrapperPass>();
224     AU.addRequired<ScalarEvolutionWrapperPass>();
225     AU.addRequired<DominatorTreeWrapperPass>();
226     AU.addRequired<TargetTransformInfoWrapperPass>();
227     AU.setPreservesCFG();
228   }
229 };
230 
231 } // end anonymous namespace
232 
233 char LoadStoreVectorizerLegacyPass::ID = 0;
234 
235 INITIALIZE_PASS_BEGIN(LoadStoreVectorizerLegacyPass, DEBUG_TYPE,
236                       "Vectorize load and Store instructions", false, false)
237 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
238 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
239 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
240 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
241 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
242 INITIALIZE_PASS_END(LoadStoreVectorizerLegacyPass, DEBUG_TYPE,
243                     "Vectorize load and store instructions", false, false)
244 
245 Pass *llvm::createLoadStoreVectorizerPass() {
246   return new LoadStoreVectorizerLegacyPass();
247 }
248 
249 bool LoadStoreVectorizerLegacyPass::runOnFunction(Function &F) {
250   // Don't vectorize when the attribute NoImplicitFloat is used.
251   if (skipFunction(F) || F.hasFnAttribute(Attribute::NoImplicitFloat))
252     return false;
253 
254   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
255   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
256   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
257   TargetTransformInfo &TTI =
258       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
259 
260   Vectorizer V(F, AA, DT, SE, TTI);
261   return V.run();
262 }
263 
264 PreservedAnalyses LoadStoreVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
265   // Don't vectorize when the attribute NoImplicitFloat is used.
266   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
267     return PreservedAnalyses::all();
268 
269   AliasAnalysis &AA = AM.getResult<AAManager>(F);
270   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
271   ScalarEvolution &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
272   TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
273 
274   Vectorizer V(F, AA, DT, SE, TTI);
275   bool Changed = V.run();
276   PreservedAnalyses PA;
277   PA.preserveSet<CFGAnalyses>();
278   return Changed ? PA : PreservedAnalyses::all();
279 }
280 
281 // The real propagateMetadata expects a SmallVector<Value*>, but we deal in
282 // vectors of Instructions.
283 static void propagateMetadata(Instruction *I, ArrayRef<Instruction *> IL) {
284   SmallVector<Value *, 8> VL(IL.begin(), IL.end());
285   propagateMetadata(I, VL);
286 }
287 
288 // Vectorizer Implementation
289 bool Vectorizer::run() {
290   bool Changed = false;
291 
292   // Scan the blocks in the function in post order.
293   for (BasicBlock *BB : post_order(&F)) {
294     InstrListMap LoadRefs, StoreRefs;
295     std::tie(LoadRefs, StoreRefs) = collectInstructions(BB);
296     Changed |= vectorizeChains(LoadRefs);
297     Changed |= vectorizeChains(StoreRefs);
298   }
299 
300   return Changed;
301 }
302 
303 unsigned Vectorizer::getPointerAddressSpace(Value *I) {
304   if (LoadInst *L = dyn_cast<LoadInst>(I))
305     return L->getPointerAddressSpace();
306   if (StoreInst *S = dyn_cast<StoreInst>(I))
307     return S->getPointerAddressSpace();
308   return -1;
309 }
310 
311 // FIXME: Merge with llvm::isConsecutiveAccess
312 bool Vectorizer::isConsecutiveAccess(Value *A, Value *B) {
313   Value *PtrA = getLoadStorePointerOperand(A);
314   Value *PtrB = getLoadStorePointerOperand(B);
315   unsigned ASA = getPointerAddressSpace(A);
316   unsigned ASB = getPointerAddressSpace(B);
317 
318   // Check that the address spaces match and that the pointers are valid.
319   if (!PtrA || !PtrB || (ASA != ASB))
320     return false;
321 
322   // Make sure that A and B are different pointers of the same size type.
323   Type *PtrATy = PtrA->getType()->getPointerElementType();
324   Type *PtrBTy = PtrB->getType()->getPointerElementType();
325   if (PtrA == PtrB ||
326       PtrATy->isVectorTy() != PtrBTy->isVectorTy() ||
327       DL.getTypeStoreSize(PtrATy) != DL.getTypeStoreSize(PtrBTy) ||
328       DL.getTypeStoreSize(PtrATy->getScalarType()) !=
329           DL.getTypeStoreSize(PtrBTy->getScalarType()))
330     return false;
331 
332   unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
333   APInt Size(PtrBitWidth, DL.getTypeStoreSize(PtrATy));
334 
335   return areConsecutivePointers(PtrA, PtrB, Size);
336 }
337 
338 bool Vectorizer::areConsecutivePointers(Value *PtrA, Value *PtrB,
339                                         const APInt &PtrDelta,
340                                         unsigned Depth) const {
341   unsigned PtrBitWidth = DL.getPointerTypeSizeInBits(PtrA->getType());
342   unsigned PtrAS = PtrA->getType()->getPointerAddressSpace();
343   APInt OffsetA(PtrBitWidth, 0);
344   APInt OffsetB(PtrBitWidth, 0);
345   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
346   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
347 
348   if (PtrA->getType()->getPointerAddressSpace() != PtrAS ||
349       PtrB->getType()->getPointerAddressSpace() != PtrAS)
350     return false;
351 
352   APInt OffsetDelta = OffsetB - OffsetA;
353 
354   // Check if they are based on the same pointer. That makes the offsets
355   // sufficient.
356   if (PtrA == PtrB)
357     return OffsetDelta == PtrDelta;
358 
359   // Compute the necessary base pointer delta to have the necessary final delta
360   // equal to the pointer delta requested.
361   APInt BaseDelta = PtrDelta - OffsetDelta;
362 
363   // Compute the distance with SCEV between the base pointers.
364   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
365   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
366   const SCEV *C = SE.getConstant(BaseDelta);
367   const SCEV *X = SE.getAddExpr(PtrSCEVA, C);
368   if (X == PtrSCEVB)
369     return true;
370 
371   // The above check will not catch the cases where one of the pointers is
372   // factorized but the other one is not, such as (C + (S * (A + B))) vs
373   // (AS + BS). Get the minus scev. That will allow re-combining the expresions
374   // and getting the simplified difference.
375   const SCEV *Dist = SE.getMinusSCEV(PtrSCEVB, PtrSCEVA);
376   if (C == Dist)
377     return true;
378 
379   // Sometimes even this doesn't work, because SCEV can't always see through
380   // patterns that look like (gep (ext (add (shl X, C1), C2))). Try checking
381   // things the hard way.
382   return lookThroughComplexAddresses(PtrA, PtrB, BaseDelta, Depth);
383 }
384 
385 bool Vectorizer::lookThroughComplexAddresses(Value *PtrA, Value *PtrB,
386                                              APInt PtrDelta,
387                                              unsigned Depth) const {
388   auto *GEPA = dyn_cast<GetElementPtrInst>(PtrA);
389   auto *GEPB = dyn_cast<GetElementPtrInst>(PtrB);
390   if (!GEPA || !GEPB)
391     return lookThroughSelects(PtrA, PtrB, PtrDelta, Depth);
392 
393   // Look through GEPs after checking they're the same except for the last
394   // index.
395   if (GEPA->getNumOperands() != GEPB->getNumOperands() ||
396       GEPA->getPointerOperand() != GEPB->getPointerOperand())
397     return false;
398   gep_type_iterator GTIA = gep_type_begin(GEPA);
399   gep_type_iterator GTIB = gep_type_begin(GEPB);
400   for (unsigned I = 0, E = GEPA->getNumIndices() - 1; I < E; ++I) {
401     if (GTIA.getOperand() != GTIB.getOperand())
402       return false;
403     ++GTIA;
404     ++GTIB;
405   }
406 
407   Instruction *OpA = dyn_cast<Instruction>(GTIA.getOperand());
408   Instruction *OpB = dyn_cast<Instruction>(GTIB.getOperand());
409   if (!OpA || !OpB || OpA->getOpcode() != OpB->getOpcode() ||
410       OpA->getType() != OpB->getType())
411     return false;
412 
413   if (PtrDelta.isNegative()) {
414     if (PtrDelta.isMinSignedValue())
415       return false;
416     PtrDelta.negate();
417     std::swap(OpA, OpB);
418   }
419   uint64_t Stride = DL.getTypeAllocSize(GTIA.getIndexedType());
420   if (PtrDelta.urem(Stride) != 0)
421     return false;
422   unsigned IdxBitWidth = OpA->getType()->getScalarSizeInBits();
423   APInt IdxDiff = PtrDelta.udiv(Stride).zextOrSelf(IdxBitWidth);
424 
425   // Only look through a ZExt/SExt.
426   if (!isa<SExtInst>(OpA) && !isa<ZExtInst>(OpA))
427     return false;
428 
429   bool Signed = isa<SExtInst>(OpA);
430 
431   // At this point A could be a function parameter, i.e. not an instruction
432   Value *ValA = OpA->getOperand(0);
433   OpB = dyn_cast<Instruction>(OpB->getOperand(0));
434   if (!OpB || ValA->getType() != OpB->getType())
435     return false;
436 
437   // Now we need to prove that adding IdxDiff to ValA won't overflow.
438   bool Safe = false;
439   // First attempt: if OpB is an add with NSW/NUW, and OpB is IdxDiff added to
440   // ValA, we're okay.
441   if (OpB->getOpcode() == Instruction::Add &&
442       isa<ConstantInt>(OpB->getOperand(1)) &&
443       IdxDiff.sle(cast<ConstantInt>(OpB->getOperand(1))->getSExtValue())) {
444     if (Signed)
445       Safe = cast<BinaryOperator>(OpB)->hasNoSignedWrap();
446     else
447       Safe = cast<BinaryOperator>(OpB)->hasNoUnsignedWrap();
448   }
449 
450   unsigned BitWidth = ValA->getType()->getScalarSizeInBits();
451 
452   // Second attempt:
453   // If all set bits of IdxDiff or any higher order bit other than the sign bit
454   // are known to be zero in ValA, we can add Diff to it while guaranteeing no
455   // overflow of any sort.
456   if (!Safe) {
457     OpA = dyn_cast<Instruction>(ValA);
458     if (!OpA)
459       return false;
460     KnownBits Known(BitWidth);
461     computeKnownBits(OpA, Known, DL, 0, nullptr, OpA, &DT);
462     APInt BitsAllowedToBeSet = Known.Zero.zext(IdxDiff.getBitWidth());
463     if (Signed)
464       BitsAllowedToBeSet.clearBit(BitWidth - 1);
465     if (BitsAllowedToBeSet.ult(IdxDiff))
466       return false;
467   }
468 
469   const SCEV *OffsetSCEVA = SE.getSCEV(ValA);
470   const SCEV *OffsetSCEVB = SE.getSCEV(OpB);
471   const SCEV *C = SE.getConstant(IdxDiff.trunc(BitWidth));
472   const SCEV *X = SE.getAddExpr(OffsetSCEVA, C);
473   return X == OffsetSCEVB;
474 }
475 
476 bool Vectorizer::lookThroughSelects(Value *PtrA, Value *PtrB,
477                                     const APInt &PtrDelta,
478                                     unsigned Depth) const {
479   if (Depth++ == MaxDepth)
480     return false;
481 
482   if (auto *SelectA = dyn_cast<SelectInst>(PtrA)) {
483     if (auto *SelectB = dyn_cast<SelectInst>(PtrB)) {
484       return SelectA->getCondition() == SelectB->getCondition() &&
485              areConsecutivePointers(SelectA->getTrueValue(),
486                                     SelectB->getTrueValue(), PtrDelta, Depth) &&
487              areConsecutivePointers(SelectA->getFalseValue(),
488                                     SelectB->getFalseValue(), PtrDelta, Depth);
489     }
490   }
491   return false;
492 }
493 
494 void Vectorizer::reorder(Instruction *I) {
495   OrderedBasicBlock OBB(I->getParent());
496   SmallPtrSet<Instruction *, 16> InstructionsToMove;
497   SmallVector<Instruction *, 16> Worklist;
498 
499   Worklist.push_back(I);
500   while (!Worklist.empty()) {
501     Instruction *IW = Worklist.pop_back_val();
502     int NumOperands = IW->getNumOperands();
503     for (int i = 0; i < NumOperands; i++) {
504       Instruction *IM = dyn_cast<Instruction>(IW->getOperand(i));
505       if (!IM || IM->getOpcode() == Instruction::PHI)
506         continue;
507 
508       // If IM is in another BB, no need to move it, because this pass only
509       // vectorizes instructions within one BB.
510       if (IM->getParent() != I->getParent())
511         continue;
512 
513       if (!OBB.dominates(IM, I)) {
514         InstructionsToMove.insert(IM);
515         Worklist.push_back(IM);
516       }
517     }
518   }
519 
520   // All instructions to move should follow I. Start from I, not from begin().
521   for (auto BBI = I->getIterator(), E = I->getParent()->end(); BBI != E;
522        ++BBI) {
523     if (!InstructionsToMove.count(&*BBI))
524       continue;
525     Instruction *IM = &*BBI;
526     --BBI;
527     IM->removeFromParent();
528     IM->insertBefore(I);
529   }
530 }
531 
532 std::pair<BasicBlock::iterator, BasicBlock::iterator>
533 Vectorizer::getBoundaryInstrs(ArrayRef<Instruction *> Chain) {
534   Instruction *C0 = Chain[0];
535   BasicBlock::iterator FirstInstr = C0->getIterator();
536   BasicBlock::iterator LastInstr = C0->getIterator();
537 
538   BasicBlock *BB = C0->getParent();
539   unsigned NumFound = 0;
540   for (Instruction &I : *BB) {
541     if (!is_contained(Chain, &I))
542       continue;
543 
544     ++NumFound;
545     if (NumFound == 1) {
546       FirstInstr = I.getIterator();
547     }
548     if (NumFound == Chain.size()) {
549       LastInstr = I.getIterator();
550       break;
551     }
552   }
553 
554   // Range is [first, last).
555   return std::make_pair(FirstInstr, ++LastInstr);
556 }
557 
558 void Vectorizer::eraseInstructions(ArrayRef<Instruction *> Chain) {
559   SmallVector<Instruction *, 16> Instrs;
560   for (Instruction *I : Chain) {
561     Value *PtrOperand = getLoadStorePointerOperand(I);
562     assert(PtrOperand && "Instruction must have a pointer operand.");
563     Instrs.push_back(I);
564     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(PtrOperand))
565       Instrs.push_back(GEP);
566   }
567 
568   // Erase instructions.
569   for (Instruction *I : Instrs)
570     if (I->use_empty())
571       I->eraseFromParent();
572 }
573 
574 std::pair<ArrayRef<Instruction *>, ArrayRef<Instruction *>>
575 Vectorizer::splitOddVectorElts(ArrayRef<Instruction *> Chain,
576                                unsigned ElementSizeBits) {
577   unsigned ElementSizeBytes = ElementSizeBits / 8;
578   unsigned SizeBytes = ElementSizeBytes * Chain.size();
579   unsigned NumLeft = (SizeBytes - (SizeBytes % 4)) / ElementSizeBytes;
580   if (NumLeft == Chain.size()) {
581     if ((NumLeft & 1) == 0)
582       NumLeft /= 2; // Split even in half
583     else
584       --NumLeft;    // Split off last element
585   } else if (NumLeft == 0)
586     NumLeft = 1;
587   return std::make_pair(Chain.slice(0, NumLeft), Chain.slice(NumLeft));
588 }
589 
590 ArrayRef<Instruction *>
591 Vectorizer::getVectorizablePrefix(ArrayRef<Instruction *> Chain) {
592   // These are in BB order, unlike Chain, which is in address order.
593   SmallVector<Instruction *, 16> MemoryInstrs;
594   SmallVector<Instruction *, 16> ChainInstrs;
595 
596   bool IsLoadChain = isa<LoadInst>(Chain[0]);
597   LLVM_DEBUG({
598     for (Instruction *I : Chain) {
599       if (IsLoadChain)
600         assert(isa<LoadInst>(I) &&
601                "All elements of Chain must be loads, or all must be stores.");
602       else
603         assert(isa<StoreInst>(I) &&
604                "All elements of Chain must be loads, or all must be stores.");
605     }
606   });
607 
608   for (Instruction &I : make_range(getBoundaryInstrs(Chain))) {
609     if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
610       if (!is_contained(Chain, &I))
611         MemoryInstrs.push_back(&I);
612       else
613         ChainInstrs.push_back(&I);
614     } else if (isa<IntrinsicInst>(&I) &&
615                cast<IntrinsicInst>(&I)->getIntrinsicID() ==
616                    Intrinsic::sideeffect) {
617       // Ignore llvm.sideeffect calls.
618     } else if (IsLoadChain && (I.mayWriteToMemory() || I.mayThrow())) {
619       LLVM_DEBUG(dbgs() << "LSV: Found may-write/throw operation: " << I
620                         << '\n');
621       break;
622     } else if (!IsLoadChain && (I.mayReadOrWriteMemory() || I.mayThrow())) {
623       LLVM_DEBUG(dbgs() << "LSV: Found may-read/write/throw operation: " << I
624                         << '\n');
625       break;
626     }
627   }
628 
629   OrderedBasicBlock OBB(Chain[0]->getParent());
630 
631   // Loop until we find an instruction in ChainInstrs that we can't vectorize.
632   unsigned ChainInstrIdx = 0;
633   Instruction *BarrierMemoryInstr = nullptr;
634 
635   for (unsigned E = ChainInstrs.size(); ChainInstrIdx < E; ++ChainInstrIdx) {
636     Instruction *ChainInstr = ChainInstrs[ChainInstrIdx];
637 
638     // If a barrier memory instruction was found, chain instructions that follow
639     // will not be added to the valid prefix.
640     if (BarrierMemoryInstr && OBB.dominates(BarrierMemoryInstr, ChainInstr))
641       break;
642 
643     // Check (in BB order) if any instruction prevents ChainInstr from being
644     // vectorized. Find and store the first such "conflicting" instruction.
645     for (Instruction *MemInstr : MemoryInstrs) {
646       // If a barrier memory instruction was found, do not check past it.
647       if (BarrierMemoryInstr && OBB.dominates(BarrierMemoryInstr, MemInstr))
648         break;
649 
650       auto *MemLoad = dyn_cast<LoadInst>(MemInstr);
651       auto *ChainLoad = dyn_cast<LoadInst>(ChainInstr);
652       if (MemLoad && ChainLoad)
653         continue;
654 
655       // We can ignore the alias if the we have a load store pair and the load
656       // is known to be invariant. The load cannot be clobbered by the store.
657       auto IsInvariantLoad = [](const LoadInst *LI) -> bool {
658         return LI->getMetadata(LLVMContext::MD_invariant_load);
659       };
660 
661       // We can ignore the alias as long as the load comes before the store,
662       // because that means we won't be moving the load past the store to
663       // vectorize it (the vectorized load is inserted at the location of the
664       // first load in the chain).
665       if (isa<StoreInst>(MemInstr) && ChainLoad &&
666           (IsInvariantLoad(ChainLoad) || OBB.dominates(ChainLoad, MemInstr)))
667         continue;
668 
669       // Same case, but in reverse.
670       if (MemLoad && isa<StoreInst>(ChainInstr) &&
671           (IsInvariantLoad(MemLoad) || OBB.dominates(MemLoad, ChainInstr)))
672         continue;
673 
674       if (!AA.isNoAlias(MemoryLocation::get(MemInstr),
675                         MemoryLocation::get(ChainInstr))) {
676         LLVM_DEBUG({
677           dbgs() << "LSV: Found alias:\n"
678                     "  Aliasing instruction and pointer:\n"
679                  << "  " << *MemInstr << '\n'
680                  << "  " << *getLoadStorePointerOperand(MemInstr) << '\n'
681                  << "  Aliased instruction and pointer:\n"
682                  << "  " << *ChainInstr << '\n'
683                  << "  " << *getLoadStorePointerOperand(ChainInstr) << '\n';
684         });
685         // Save this aliasing memory instruction as a barrier, but allow other
686         // instructions that precede the barrier to be vectorized with this one.
687         BarrierMemoryInstr = MemInstr;
688         break;
689       }
690     }
691     // Continue the search only for store chains, since vectorizing stores that
692     // precede an aliasing load is valid. Conversely, vectorizing loads is valid
693     // up to an aliasing store, but should not pull loads from further down in
694     // the basic block.
695     if (IsLoadChain && BarrierMemoryInstr) {
696       // The BarrierMemoryInstr is a store that precedes ChainInstr.
697       assert(OBB.dominates(BarrierMemoryInstr, ChainInstr));
698       break;
699     }
700   }
701 
702   // Find the largest prefix of Chain whose elements are all in
703   // ChainInstrs[0, ChainInstrIdx).  This is the largest vectorizable prefix of
704   // Chain.  (Recall that Chain is in address order, but ChainInstrs is in BB
705   // order.)
706   SmallPtrSet<Instruction *, 8> VectorizableChainInstrs(
707       ChainInstrs.begin(), ChainInstrs.begin() + ChainInstrIdx);
708   unsigned ChainIdx = 0;
709   for (unsigned ChainLen = Chain.size(); ChainIdx < ChainLen; ++ChainIdx) {
710     if (!VectorizableChainInstrs.count(Chain[ChainIdx]))
711       break;
712   }
713   return Chain.slice(0, ChainIdx);
714 }
715 
716 static ChainID getChainID(const Value *Ptr, const DataLayout &DL) {
717   const Value *ObjPtr = GetUnderlyingObject(Ptr, DL);
718   if (const auto *Sel = dyn_cast<SelectInst>(ObjPtr)) {
719     // The select's themselves are distinct instructions even if they share the
720     // same condition and evaluate to consecutive pointers for true and false
721     // values of the condition. Therefore using the select's themselves for
722     // grouping instructions would put consecutive accesses into different lists
723     // and they won't be even checked for being consecutive, and won't be
724     // vectorized.
725     return Sel->getCondition();
726   }
727   return ObjPtr;
728 }
729 
730 std::pair<InstrListMap, InstrListMap>
731 Vectorizer::collectInstructions(BasicBlock *BB) {
732   InstrListMap LoadRefs;
733   InstrListMap StoreRefs;
734 
735   for (Instruction &I : *BB) {
736     if (!I.mayReadOrWriteMemory())
737       continue;
738 
739     if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
740       if (!LI->isSimple())
741         continue;
742 
743       // Skip if it's not legal.
744       if (!TTI.isLegalToVectorizeLoad(LI))
745         continue;
746 
747       Type *Ty = LI->getType();
748       if (!VectorType::isValidElementType(Ty->getScalarType()))
749         continue;
750 
751       // Skip weird non-byte sizes. They probably aren't worth the effort of
752       // handling correctly.
753       unsigned TySize = DL.getTypeSizeInBits(Ty);
754       if ((TySize % 8) != 0)
755         continue;
756 
757       // Skip vectors of pointers. The vectorizeLoadChain/vectorizeStoreChain
758       // functions are currently using an integer type for the vectorized
759       // load/store, and does not support casting between the integer type and a
760       // vector of pointers (e.g. i64 to <2 x i16*>)
761       if (Ty->isVectorTy() && Ty->isPtrOrPtrVectorTy())
762         continue;
763 
764       Value *Ptr = LI->getPointerOperand();
765       unsigned AS = Ptr->getType()->getPointerAddressSpace();
766       unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
767 
768       unsigned VF = VecRegSize / TySize;
769       VectorType *VecTy = dyn_cast<VectorType>(Ty);
770 
771       // No point in looking at these if they're too big to vectorize.
772       if (TySize > VecRegSize / 2 ||
773           (VecTy && TTI.getLoadVectorFactor(VF, TySize, TySize / 8, VecTy) == 0))
774         continue;
775 
776       // Make sure all the users of a vector are constant-index extracts.
777       if (isa<VectorType>(Ty) && !llvm::all_of(LI->users(), [](const User *U) {
778             const ExtractElementInst *EEI = dyn_cast<ExtractElementInst>(U);
779             return EEI && isa<ConstantInt>(EEI->getOperand(1));
780           }))
781         continue;
782 
783       // Save the load locations.
784       const ChainID ID = getChainID(Ptr, DL);
785       LoadRefs[ID].push_back(LI);
786     } else if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
787       if (!SI->isSimple())
788         continue;
789 
790       // Skip if it's not legal.
791       if (!TTI.isLegalToVectorizeStore(SI))
792         continue;
793 
794       Type *Ty = SI->getValueOperand()->getType();
795       if (!VectorType::isValidElementType(Ty->getScalarType()))
796         continue;
797 
798       // Skip vectors of pointers. The vectorizeLoadChain/vectorizeStoreChain
799       // functions are currently using an integer type for the vectorized
800       // load/store, and does not support casting between the integer type and a
801       // vector of pointers (e.g. i64 to <2 x i16*>)
802       if (Ty->isVectorTy() && Ty->isPtrOrPtrVectorTy())
803         continue;
804 
805       // Skip weird non-byte sizes. They probably aren't worth the effort of
806       // handling correctly.
807       unsigned TySize = DL.getTypeSizeInBits(Ty);
808       if ((TySize % 8) != 0)
809         continue;
810 
811       Value *Ptr = SI->getPointerOperand();
812       unsigned AS = Ptr->getType()->getPointerAddressSpace();
813       unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
814 
815       unsigned VF = VecRegSize / TySize;
816       VectorType *VecTy = dyn_cast<VectorType>(Ty);
817 
818       // No point in looking at these if they're too big to vectorize.
819       if (TySize > VecRegSize / 2 ||
820           (VecTy && TTI.getStoreVectorFactor(VF, TySize, TySize / 8, VecTy) == 0))
821         continue;
822 
823       if (isa<VectorType>(Ty) && !llvm::all_of(SI->users(), [](const User *U) {
824             const ExtractElementInst *EEI = dyn_cast<ExtractElementInst>(U);
825             return EEI && isa<ConstantInt>(EEI->getOperand(1));
826           }))
827         continue;
828 
829       // Save store location.
830       const ChainID ID = getChainID(Ptr, DL);
831       StoreRefs[ID].push_back(SI);
832     }
833   }
834 
835   return {LoadRefs, StoreRefs};
836 }
837 
838 bool Vectorizer::vectorizeChains(InstrListMap &Map) {
839   bool Changed = false;
840 
841   for (const std::pair<ChainID, InstrList> &Chain : Map) {
842     unsigned Size = Chain.second.size();
843     if (Size < 2)
844       continue;
845 
846     LLVM_DEBUG(dbgs() << "LSV: Analyzing a chain of length " << Size << ".\n");
847 
848     // Process the stores in chunks of 64.
849     for (unsigned CI = 0, CE = Size; CI < CE; CI += 64) {
850       unsigned Len = std::min<unsigned>(CE - CI, 64);
851       ArrayRef<Instruction *> Chunk(&Chain.second[CI], Len);
852       Changed |= vectorizeInstructions(Chunk);
853     }
854   }
855 
856   return Changed;
857 }
858 
859 bool Vectorizer::vectorizeInstructions(ArrayRef<Instruction *> Instrs) {
860   LLVM_DEBUG(dbgs() << "LSV: Vectorizing " << Instrs.size()
861                     << " instructions.\n");
862   SmallVector<int, 16> Heads, Tails;
863   int ConsecutiveChain[64];
864 
865   // Do a quadratic search on all of the given loads/stores and find all of the
866   // pairs of loads/stores that follow each other.
867   for (int i = 0, e = Instrs.size(); i < e; ++i) {
868     ConsecutiveChain[i] = -1;
869     for (int j = e - 1; j >= 0; --j) {
870       if (i == j)
871         continue;
872 
873       if (isConsecutiveAccess(Instrs[i], Instrs[j])) {
874         if (ConsecutiveChain[i] != -1) {
875           int CurDistance = std::abs(ConsecutiveChain[i] - i);
876           int NewDistance = std::abs(ConsecutiveChain[i] - j);
877           if (j < i || NewDistance > CurDistance)
878             continue; // Should not insert.
879         }
880 
881         Tails.push_back(j);
882         Heads.push_back(i);
883         ConsecutiveChain[i] = j;
884       }
885     }
886   }
887 
888   bool Changed = false;
889   SmallPtrSet<Instruction *, 16> InstructionsProcessed;
890 
891   for (int Head : Heads) {
892     if (InstructionsProcessed.count(Instrs[Head]))
893       continue;
894     bool LongerChainExists = false;
895     for (unsigned TIt = 0; TIt < Tails.size(); TIt++)
896       if (Head == Tails[TIt] &&
897           !InstructionsProcessed.count(Instrs[Heads[TIt]])) {
898         LongerChainExists = true;
899         break;
900       }
901     if (LongerChainExists)
902       continue;
903 
904     // We found an instr that starts a chain. Now follow the chain and try to
905     // vectorize it.
906     SmallVector<Instruction *, 16> Operands;
907     int I = Head;
908     while (I != -1 && (is_contained(Tails, I) || is_contained(Heads, I))) {
909       if (InstructionsProcessed.count(Instrs[I]))
910         break;
911 
912       Operands.push_back(Instrs[I]);
913       I = ConsecutiveChain[I];
914     }
915 
916     bool Vectorized = false;
917     if (isa<LoadInst>(*Operands.begin()))
918       Vectorized = vectorizeLoadChain(Operands, &InstructionsProcessed);
919     else
920       Vectorized = vectorizeStoreChain(Operands, &InstructionsProcessed);
921 
922     Changed |= Vectorized;
923   }
924 
925   return Changed;
926 }
927 
928 bool Vectorizer::vectorizeStoreChain(
929     ArrayRef<Instruction *> Chain,
930     SmallPtrSet<Instruction *, 16> *InstructionsProcessed) {
931   StoreInst *S0 = cast<StoreInst>(Chain[0]);
932 
933   // If the vector has an int element, default to int for the whole store.
934   Type *StoreTy = nullptr;
935   for (Instruction *I : Chain) {
936     StoreTy = cast<StoreInst>(I)->getValueOperand()->getType();
937     if (StoreTy->isIntOrIntVectorTy())
938       break;
939 
940     if (StoreTy->isPtrOrPtrVectorTy()) {
941       StoreTy = Type::getIntNTy(F.getParent()->getContext(),
942                                 DL.getTypeSizeInBits(StoreTy));
943       break;
944     }
945   }
946   assert(StoreTy && "Failed to find store type");
947 
948   unsigned Sz = DL.getTypeSizeInBits(StoreTy);
949   unsigned AS = S0->getPointerAddressSpace();
950   unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
951   unsigned VF = VecRegSize / Sz;
952   unsigned ChainSize = Chain.size();
953   unsigned Alignment = getAlignment(S0);
954 
955   if (!isPowerOf2_32(Sz) || VF < 2 || ChainSize < 2) {
956     InstructionsProcessed->insert(Chain.begin(), Chain.end());
957     return false;
958   }
959 
960   ArrayRef<Instruction *> NewChain = getVectorizablePrefix(Chain);
961   if (NewChain.empty()) {
962     // No vectorization possible.
963     InstructionsProcessed->insert(Chain.begin(), Chain.end());
964     return false;
965   }
966   if (NewChain.size() == 1) {
967     // Failed after the first instruction. Discard it and try the smaller chain.
968     InstructionsProcessed->insert(NewChain.front());
969     return false;
970   }
971 
972   // Update Chain to the valid vectorizable subchain.
973   Chain = NewChain;
974   ChainSize = Chain.size();
975 
976   // Check if it's legal to vectorize this chain. If not, split the chain and
977   // try again.
978   unsigned EltSzInBytes = Sz / 8;
979   unsigned SzInBytes = EltSzInBytes * ChainSize;
980 
981   VectorType *VecTy;
982   VectorType *VecStoreTy = dyn_cast<VectorType>(StoreTy);
983   if (VecStoreTy)
984     VecTy = VectorType::get(StoreTy->getScalarType(),
985                             Chain.size() * VecStoreTy->getNumElements());
986   else
987     VecTy = VectorType::get(StoreTy, Chain.size());
988 
989   // If it's more than the max vector size or the target has a better
990   // vector factor, break it into two pieces.
991   unsigned TargetVF = TTI.getStoreVectorFactor(VF, Sz, SzInBytes, VecTy);
992   if (ChainSize > VF || (VF != TargetVF && TargetVF < ChainSize)) {
993     LLVM_DEBUG(dbgs() << "LSV: Chain doesn't match with the vector factor."
994                          " Creating two separate arrays.\n");
995     return vectorizeStoreChain(Chain.slice(0, TargetVF),
996                                InstructionsProcessed) |
997            vectorizeStoreChain(Chain.slice(TargetVF), InstructionsProcessed);
998   }
999 
1000   LLVM_DEBUG({
1001     dbgs() << "LSV: Stores to vectorize:\n";
1002     for (Instruction *I : Chain)
1003       dbgs() << "  " << *I << "\n";
1004   });
1005 
1006   // We won't try again to vectorize the elements of the chain, regardless of
1007   // whether we succeed below.
1008   InstructionsProcessed->insert(Chain.begin(), Chain.end());
1009 
1010   // If the store is going to be misaligned, don't vectorize it.
1011   if (accessIsMisaligned(SzInBytes, AS, Alignment)) {
1012     if (S0->getPointerAddressSpace() != DL.getAllocaAddrSpace()) {
1013       auto Chains = splitOddVectorElts(Chain, Sz);
1014       return vectorizeStoreChain(Chains.first, InstructionsProcessed) |
1015              vectorizeStoreChain(Chains.second, InstructionsProcessed);
1016     }
1017 
1018     unsigned NewAlign = getOrEnforceKnownAlignment(S0->getPointerOperand(),
1019                                                    StackAdjustedAlignment,
1020                                                    DL, S0, nullptr, &DT);
1021     if (NewAlign != 0)
1022       Alignment = NewAlign;
1023   }
1024 
1025   if (!TTI.isLegalToVectorizeStoreChain(SzInBytes, Alignment, AS)) {
1026     auto Chains = splitOddVectorElts(Chain, Sz);
1027     return vectorizeStoreChain(Chains.first, InstructionsProcessed) |
1028            vectorizeStoreChain(Chains.second, InstructionsProcessed);
1029   }
1030 
1031   BasicBlock::iterator First, Last;
1032   std::tie(First, Last) = getBoundaryInstrs(Chain);
1033   Builder.SetInsertPoint(&*Last);
1034 
1035   Value *Vec = UndefValue::get(VecTy);
1036 
1037   if (VecStoreTy) {
1038     unsigned VecWidth = VecStoreTy->getNumElements();
1039     for (unsigned I = 0, E = Chain.size(); I != E; ++I) {
1040       StoreInst *Store = cast<StoreInst>(Chain[I]);
1041       for (unsigned J = 0, NE = VecStoreTy->getNumElements(); J != NE; ++J) {
1042         unsigned NewIdx = J + I * VecWidth;
1043         Value *Extract = Builder.CreateExtractElement(Store->getValueOperand(),
1044                                                       Builder.getInt32(J));
1045         if (Extract->getType() != StoreTy->getScalarType())
1046           Extract = Builder.CreateBitCast(Extract, StoreTy->getScalarType());
1047 
1048         Value *Insert =
1049             Builder.CreateInsertElement(Vec, Extract, Builder.getInt32(NewIdx));
1050         Vec = Insert;
1051       }
1052     }
1053   } else {
1054     for (unsigned I = 0, E = Chain.size(); I != E; ++I) {
1055       StoreInst *Store = cast<StoreInst>(Chain[I]);
1056       Value *Extract = Store->getValueOperand();
1057       if (Extract->getType() != StoreTy->getScalarType())
1058         Extract =
1059             Builder.CreateBitOrPointerCast(Extract, StoreTy->getScalarType());
1060 
1061       Value *Insert =
1062           Builder.CreateInsertElement(Vec, Extract, Builder.getInt32(I));
1063       Vec = Insert;
1064     }
1065   }
1066 
1067   StoreInst *SI = Builder.CreateAlignedStore(
1068     Vec,
1069     Builder.CreateBitCast(S0->getPointerOperand(), VecTy->getPointerTo(AS)),
1070     Alignment);
1071   propagateMetadata(SI, Chain);
1072 
1073   eraseInstructions(Chain);
1074   ++NumVectorInstructions;
1075   NumScalarsVectorized += Chain.size();
1076   return true;
1077 }
1078 
1079 bool Vectorizer::vectorizeLoadChain(
1080     ArrayRef<Instruction *> Chain,
1081     SmallPtrSet<Instruction *, 16> *InstructionsProcessed) {
1082   LoadInst *L0 = cast<LoadInst>(Chain[0]);
1083 
1084   // If the vector has an int element, default to int for the whole load.
1085   Type *LoadTy;
1086   for (const auto &V : Chain) {
1087     LoadTy = cast<LoadInst>(V)->getType();
1088     if (LoadTy->isIntOrIntVectorTy())
1089       break;
1090 
1091     if (LoadTy->isPtrOrPtrVectorTy()) {
1092       LoadTy = Type::getIntNTy(F.getParent()->getContext(),
1093                                DL.getTypeSizeInBits(LoadTy));
1094       break;
1095     }
1096   }
1097 
1098   unsigned Sz = DL.getTypeSizeInBits(LoadTy);
1099   unsigned AS = L0->getPointerAddressSpace();
1100   unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
1101   unsigned VF = VecRegSize / Sz;
1102   unsigned ChainSize = Chain.size();
1103   unsigned Alignment = getAlignment(L0);
1104 
1105   if (!isPowerOf2_32(Sz) || VF < 2 || ChainSize < 2) {
1106     InstructionsProcessed->insert(Chain.begin(), Chain.end());
1107     return false;
1108   }
1109 
1110   ArrayRef<Instruction *> NewChain = getVectorizablePrefix(Chain);
1111   if (NewChain.empty()) {
1112     // No vectorization possible.
1113     InstructionsProcessed->insert(Chain.begin(), Chain.end());
1114     return false;
1115   }
1116   if (NewChain.size() == 1) {
1117     // Failed after the first instruction. Discard it and try the smaller chain.
1118     InstructionsProcessed->insert(NewChain.front());
1119     return false;
1120   }
1121 
1122   // Update Chain to the valid vectorizable subchain.
1123   Chain = NewChain;
1124   ChainSize = Chain.size();
1125 
1126   // Check if it's legal to vectorize this chain. If not, split the chain and
1127   // try again.
1128   unsigned EltSzInBytes = Sz / 8;
1129   unsigned SzInBytes = EltSzInBytes * ChainSize;
1130   VectorType *VecTy;
1131   VectorType *VecLoadTy = dyn_cast<VectorType>(LoadTy);
1132   if (VecLoadTy)
1133     VecTy = VectorType::get(LoadTy->getScalarType(),
1134                             Chain.size() * VecLoadTy->getNumElements());
1135   else
1136     VecTy = VectorType::get(LoadTy, Chain.size());
1137 
1138   // If it's more than the max vector size or the target has a better
1139   // vector factor, break it into two pieces.
1140   unsigned TargetVF = TTI.getLoadVectorFactor(VF, Sz, SzInBytes, VecTy);
1141   if (ChainSize > VF || (VF != TargetVF && TargetVF < ChainSize)) {
1142     LLVM_DEBUG(dbgs() << "LSV: Chain doesn't match with the vector factor."
1143                          " Creating two separate arrays.\n");
1144     return vectorizeLoadChain(Chain.slice(0, TargetVF), InstructionsProcessed) |
1145            vectorizeLoadChain(Chain.slice(TargetVF), InstructionsProcessed);
1146   }
1147 
1148   // We won't try again to vectorize the elements of the chain, regardless of
1149   // whether we succeed below.
1150   InstructionsProcessed->insert(Chain.begin(), Chain.end());
1151 
1152   // If the load is going to be misaligned, don't vectorize it.
1153   if (accessIsMisaligned(SzInBytes, AS, Alignment)) {
1154     if (L0->getPointerAddressSpace() != DL.getAllocaAddrSpace()) {
1155       auto Chains = splitOddVectorElts(Chain, Sz);
1156       return vectorizeLoadChain(Chains.first, InstructionsProcessed) |
1157              vectorizeLoadChain(Chains.second, InstructionsProcessed);
1158     }
1159 
1160     Alignment = getOrEnforceKnownAlignment(
1161         L0->getPointerOperand(), StackAdjustedAlignment, DL, L0, nullptr, &DT);
1162   }
1163 
1164   if (!TTI.isLegalToVectorizeLoadChain(SzInBytes, Alignment, AS)) {
1165     auto Chains = splitOddVectorElts(Chain, Sz);
1166     return vectorizeLoadChain(Chains.first, InstructionsProcessed) |
1167            vectorizeLoadChain(Chains.second, InstructionsProcessed);
1168   }
1169 
1170   LLVM_DEBUG({
1171     dbgs() << "LSV: Loads to vectorize:\n";
1172     for (Instruction *I : Chain)
1173       I->dump();
1174   });
1175 
1176   // getVectorizablePrefix already computed getBoundaryInstrs.  The value of
1177   // Last may have changed since then, but the value of First won't have.  If it
1178   // matters, we could compute getBoundaryInstrs only once and reuse it here.
1179   BasicBlock::iterator First, Last;
1180   std::tie(First, Last) = getBoundaryInstrs(Chain);
1181   Builder.SetInsertPoint(&*First);
1182 
1183   Value *Bitcast =
1184       Builder.CreateBitCast(L0->getPointerOperand(), VecTy->getPointerTo(AS));
1185   LoadInst *LI = Builder.CreateAlignedLoad(VecTy, Bitcast, Alignment);
1186   propagateMetadata(LI, Chain);
1187 
1188   if (VecLoadTy) {
1189     SmallVector<Instruction *, 16> InstrsToErase;
1190 
1191     unsigned VecWidth = VecLoadTy->getNumElements();
1192     for (unsigned I = 0, E = Chain.size(); I != E; ++I) {
1193       for (auto Use : Chain[I]->users()) {
1194         // All users of vector loads are ExtractElement instructions with
1195         // constant indices, otherwise we would have bailed before now.
1196         Instruction *UI = cast<Instruction>(Use);
1197         unsigned Idx = cast<ConstantInt>(UI->getOperand(1))->getZExtValue();
1198         unsigned NewIdx = Idx + I * VecWidth;
1199         Value *V = Builder.CreateExtractElement(LI, Builder.getInt32(NewIdx),
1200                                                 UI->getName());
1201         if (V->getType() != UI->getType())
1202           V = Builder.CreateBitCast(V, UI->getType());
1203 
1204         // Replace the old instruction.
1205         UI->replaceAllUsesWith(V);
1206         InstrsToErase.push_back(UI);
1207       }
1208     }
1209 
1210     // Bitcast might not be an Instruction, if the value being loaded is a
1211     // constant.  In that case, no need to reorder anything.
1212     if (Instruction *BitcastInst = dyn_cast<Instruction>(Bitcast))
1213       reorder(BitcastInst);
1214 
1215     for (auto I : InstrsToErase)
1216       I->eraseFromParent();
1217   } else {
1218     for (unsigned I = 0, E = Chain.size(); I != E; ++I) {
1219       Value *CV = Chain[I];
1220       Value *V =
1221           Builder.CreateExtractElement(LI, Builder.getInt32(I), CV->getName());
1222       if (V->getType() != CV->getType()) {
1223         V = Builder.CreateBitOrPointerCast(V, CV->getType());
1224       }
1225 
1226       // Replace the old instruction.
1227       CV->replaceAllUsesWith(V);
1228     }
1229 
1230     if (Instruction *BitcastInst = dyn_cast<Instruction>(Bitcast))
1231       reorder(BitcastInst);
1232   }
1233 
1234   eraseInstructions(Chain);
1235 
1236   ++NumVectorInstructions;
1237   NumScalarsVectorized += Chain.size();
1238   return true;
1239 }
1240 
1241 bool Vectorizer::accessIsMisaligned(unsigned SzInBytes, unsigned AddressSpace,
1242                                     unsigned Alignment) {
1243   if (Alignment % SzInBytes == 0)
1244     return false;
1245 
1246   bool Fast = false;
1247   bool Allows = TTI.allowsMisalignedMemoryAccesses(F.getParent()->getContext(),
1248                                                    SzInBytes * 8, AddressSpace,
1249                                                    Alignment, &Fast);
1250   LLVM_DEBUG(dbgs() << "LSV: Target said misaligned is allowed? " << Allows
1251                     << " and fast? " << Fast << "\n";);
1252   return !Allows || !Fast;
1253 }
1254