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