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