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