xref: /llvm-project/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp (revision b1b04ed96ac92d77ebb6de1ef8522f62ae4f517f)
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 // Overview of the algorithm and terminology in this pass:
42 //
43 //  - Break up each basic block into pseudo-BBs, composed of instructions which
44 //    are guaranteed to transfer control to their successors.
45 //  - Within a single pseudo-BB, find all loads, and group them into
46 //    "equivalence classes" according to getUnderlyingObject() and loaded
47 //    element size.  Do the same for stores.
48 //  - For each equivalence class, greedily build "chains".  Each chain has a
49 //    leader instruction, and every other member of the chain has a known
50 //    constant offset from the first instr in the chain.
51 //  - Break up chains so that they contain only contiguous accesses of legal
52 //    size with no intervening may-alias instrs.
53 //  - Convert each chain to vector instructions.
54 //
55 // The O(n^2) behavior of this pass comes from initially building the chains.
56 // In the worst case we have to compare each new instruction to all of those
57 // that came before. To limit this, we only calculate the offset to the leaders
58 // of the N most recently-used chains.
59 
60 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/MapVector.h"
65 #include "llvm/ADT/PostOrderIterator.h"
66 #include "llvm/ADT/STLExtras.h"
67 #include "llvm/ADT/Sequence.h"
68 #include "llvm/ADT/SmallPtrSet.h"
69 #include "llvm/ADT/SmallVector.h"
70 #include "llvm/ADT/Statistic.h"
71 #include "llvm/ADT/iterator_range.h"
72 #include "llvm/Analysis/AliasAnalysis.h"
73 #include "llvm/Analysis/AssumptionCache.h"
74 #include "llvm/Analysis/MemoryLocation.h"
75 #include "llvm/Analysis/ScalarEvolution.h"
76 #include "llvm/Analysis/TargetTransformInfo.h"
77 #include "llvm/Analysis/ValueTracking.h"
78 #include "llvm/Analysis/VectorUtils.h"
79 #include "llvm/IR/Attributes.h"
80 #include "llvm/IR/BasicBlock.h"
81 #include "llvm/IR/ConstantRange.h"
82 #include "llvm/IR/Constants.h"
83 #include "llvm/IR/DataLayout.h"
84 #include "llvm/IR/DerivedTypes.h"
85 #include "llvm/IR/Dominators.h"
86 #include "llvm/IR/Function.h"
87 #include "llvm/IR/GetElementPtrTypeIterator.h"
88 #include "llvm/IR/IRBuilder.h"
89 #include "llvm/IR/InstrTypes.h"
90 #include "llvm/IR/Instruction.h"
91 #include "llvm/IR/Instructions.h"
92 #include "llvm/IR/LLVMContext.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Type.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/InitializePasses.h"
97 #include "llvm/Pass.h"
98 #include "llvm/Support/Alignment.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/Debug.h"
101 #include "llvm/Support/KnownBits.h"
102 #include "llvm/Support/MathExtras.h"
103 #include "llvm/Support/ModRef.h"
104 #include "llvm/Support/raw_ostream.h"
105 #include "llvm/Transforms/Utils/Local.h"
106 #include "llvm/Transforms/Vectorize.h"
107 #include <algorithm>
108 #include <cassert>
109 #include <cstdint>
110 #include <cstdlib>
111 #include <iterator>
112 #include <limits>
113 #include <numeric>
114 #include <optional>
115 #include <tuple>
116 #include <type_traits>
117 #include <utility>
118 #include <vector>
119 
120 using namespace llvm;
121 
122 #define DEBUG_TYPE "load-store-vectorizer"
123 
124 STATISTIC(NumVectorInstructions, "Number of vector accesses generated");
125 STATISTIC(NumScalarsVectorized, "Number of scalar accesses vectorized");
126 
127 namespace {
128 
129 // Equivalence class key, the initial tuple by which we group loads/stores.
130 // Loads/stores with different EqClassKeys are never merged.
131 //
132 // (We could in theory remove element-size from the this tuple.  We'd just need
133 // to fix up the vector packing/unpacking code.)
134 using EqClassKey =
135     std::tuple<const Value * /* result of getUnderlyingObject() */,
136                unsigned /* AddrSpace */,
137                unsigned /* Load/Store element size bits */,
138                char /* IsLoad; char b/c bool can't be a DenseMap key */
139                >;
140 [[maybe_unused]] llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
141                                                const EqClassKey &K) {
142   const auto &[UnderlyingObject, AddrSpace, ElementSize, IsLoad] = K;
143   return OS << (IsLoad ? "load" : "store") << " of " << *UnderlyingObject
144             << " of element size " << ElementSize << " bits in addrspace "
145             << AddrSpace;
146 }
147 
148 // A Chain is a set of instructions such that:
149 //  - All instructions have the same equivalence class, so in particular all are
150 //    loads, or all are stores.
151 //  - We know the address accessed by the i'th chain elem relative to the
152 //    chain's leader instruction, which is the first instr of the chain in BB
153 //    order.
154 //
155 // Chains have two canonical orderings:
156 //  - BB order, sorted by Instr->comesBefore.
157 //  - Offset order, sorted by OffsetFromLeader.
158 // This pass switches back and forth between these orders.
159 struct ChainElem {
160   Instruction *Inst;
161   APInt OffsetFromLeader;
162 };
163 using Chain = SmallVector<ChainElem, 1>;
164 
165 void sortChainInBBOrder(Chain &C) {
166   sort(C, [](auto &A, auto &B) { return A.Inst->comesBefore(B.Inst); });
167 }
168 
169 void sortChainInOffsetOrder(Chain &C) {
170   sort(C, [](const auto &A, const auto &B) {
171     if (A.OffsetFromLeader != B.OffsetFromLeader)
172       return A.OffsetFromLeader.slt(B.OffsetFromLeader);
173     return A.Inst->comesBefore(B.Inst); // stable tiebreaker
174   });
175 }
176 
177 [[maybe_unused]] void dumpChain(ArrayRef<ChainElem> C) {
178   for (const auto &E : C) {
179     dbgs() << "  " << *E.Inst << " (offset " << E.OffsetFromLeader << ")\n";
180   }
181 }
182 
183 using EquivalenceClassMap =
184     MapVector<EqClassKey, SmallVector<Instruction *, 8>>;
185 
186 // FIXME: Assuming stack alignment of 4 is always good enough
187 constexpr unsigned StackAdjustedAlignment = 4;
188 
189 Instruction *propagateMetadata(Instruction *I, const Chain &C) {
190   SmallVector<Value *, 8> Values;
191   for (const ChainElem &E : C)
192     Values.push_back(E.Inst);
193   return propagateMetadata(I, Values);
194 }
195 
196 bool isInvariantLoad(const Instruction *I) {
197   const LoadInst *LI = dyn_cast<LoadInst>(I);
198   return LI != nullptr && LI->hasMetadata(LLVMContext::MD_invariant_load);
199 }
200 
201 /// Reorders the instructions that I depends on (the instructions defining its
202 /// operands), to ensure they dominate I.
203 void reorder(Instruction *I) {
204   SmallPtrSet<Instruction *, 16> InstructionsToMove;
205   SmallVector<Instruction *, 16> Worklist;
206 
207   Worklist.push_back(I);
208   while (!Worklist.empty()) {
209     Instruction *IW = Worklist.pop_back_val();
210     int NumOperands = IW->getNumOperands();
211     for (int i = 0; i < NumOperands; i++) {
212       Instruction *IM = dyn_cast<Instruction>(IW->getOperand(i));
213       if (!IM || IM->getOpcode() == Instruction::PHI)
214         continue;
215 
216       // If IM is in another BB, no need to move it, because this pass only
217       // vectorizes instructions within one BB.
218       if (IM->getParent() != I->getParent())
219         continue;
220 
221       if (!IM->comesBefore(I)) {
222         InstructionsToMove.insert(IM);
223         Worklist.push_back(IM);
224       }
225     }
226   }
227 
228   // All instructions to move should follow I. Start from I, not from begin().
229   for (auto BBI = I->getIterator(), E = I->getParent()->end(); BBI != E;) {
230     Instruction *IM = &*(BBI++);
231     if (!InstructionsToMove.count(IM))
232       continue;
233     IM->moveBefore(I);
234   }
235 }
236 
237 class Vectorizer {
238   Function &F;
239   AliasAnalysis &AA;
240   AssumptionCache &AC;
241   DominatorTree &DT;
242   ScalarEvolution &SE;
243   TargetTransformInfo &TTI;
244   const DataLayout &DL;
245   IRBuilder<> Builder;
246 
247   // We could erase instrs right after vectorizing them, but that can mess up
248   // our BB iterators, and also can make the equivalence class keys point to
249   // freed memory.  This is fixable, but it's simpler just to wait until we're
250   // done with the BB and erase all at once.
251   SmallVector<Instruction *, 128> ToErase;
252 
253 public:
254   Vectorizer(Function &F, AliasAnalysis &AA, AssumptionCache &AC,
255              DominatorTree &DT, ScalarEvolution &SE, TargetTransformInfo &TTI)
256       : F(F), AA(AA), AC(AC), DT(DT), SE(SE), TTI(TTI),
257         DL(F.getParent()->getDataLayout()), Builder(SE.getContext()) {}
258 
259   bool run();
260 
261 private:
262   static const unsigned MaxDepth = 3;
263 
264   /// Runs the vectorizer on a "pseudo basic block", which is a range of
265   /// instructions [Begin, End) within one BB all of which have
266   /// isGuaranteedToTransferExecutionToSuccessor(I) == true.
267   bool runOnPseudoBB(BasicBlock::iterator Begin, BasicBlock::iterator End);
268 
269   /// Runs the vectorizer on one equivalence class, i.e. one set of loads/stores
270   /// in the same BB with the same value for getUnderlyingObject() etc.
271   bool runOnEquivalenceClass(const EqClassKey &EqClassKey,
272                              ArrayRef<Instruction *> EqClass);
273 
274   /// Runs the vectorizer on one chain, i.e. a subset of an equivalence class
275   /// where all instructions access a known, constant offset from the first
276   /// instruction.
277   bool runOnChain(Chain &C);
278 
279   /// Splits the chain into subchains of instructions which read/write a
280   /// contiguous block of memory.  Discards any length-1 subchains (because
281   /// there's nothing to vectorize in there).
282   std::vector<Chain> splitChainByContiguity(Chain &C);
283 
284   /// Splits the chain into subchains where it's safe to hoist loads up to the
285   /// beginning of the sub-chain and it's safe to sink loads up to the end of
286   /// the sub-chain.  Discards any length-1 subchains.
287   std::vector<Chain> splitChainByMayAliasInstrs(Chain &C);
288 
289   /// Splits the chain into subchains that make legal, aligned accesses.
290   /// Discards any length-1 subchains.
291   std::vector<Chain> splitChainByAlignment(Chain &C);
292 
293   /// Converts the instrs in the chain into a single vectorized load or store.
294   /// Adds the old scalar loads/stores to ToErase.
295   bool vectorizeChain(Chain &C);
296 
297   /// Tries to compute the offset in bytes PtrB - PtrA.
298   std::optional<APInt> getConstantOffset(Value *PtrA, Value *PtrB,
299                                          unsigned Depth = 0);
300   std::optional<APInt> gtConstantOffsetComplexAddrs(Value *PtrA, Value *PtrB,
301                                                     unsigned Depth);
302   std::optional<APInt> getConstantOffsetSelects(Value *PtrA, Value *PtrB,
303                                                 unsigned Depth);
304 
305   /// Gets the element type of the vector that the chain will load or store.
306   /// This is nontrivial because the chain may contain elements of different
307   /// types; e.g. it's legal to have a chain that contains both i32 and float.
308   Type *getChainElemTy(const Chain &C);
309 
310   /// Determines whether ChainElem can be moved up (if IsLoad) or down (if
311   /// !IsLoad) to ChainBegin -- i.e. there are no intervening may-alias
312   /// instructions.
313   ///
314   /// The map ChainElemOffsets must contain all of the elements in
315   /// [ChainBegin, ChainElem] and their offsets from some arbitrary base
316   /// address.  It's ok if it contains additional entries.
317   template <bool IsLoadChain>
318   bool isSafeToMove(
319       Instruction *ChainElem, Instruction *ChainBegin,
320       const DenseMap<Instruction *, APInt /*OffsetFromLeader*/> &ChainOffsets);
321 
322   /// Collects loads and stores grouped by "equivalence class", where:
323   ///   - all elements in an eq class are a load or all are a store,
324   ///   - they all load/store the same element size (it's OK to have e.g. i8 and
325   ///     <4 x i8> in the same class, but not i32 and <4 x i8>), and
326   ///   - they all have the same value for getUnderlyingObject().
327   EquivalenceClassMap collectEquivalenceClasses(BasicBlock::iterator Begin,
328                                                 BasicBlock::iterator End);
329 
330   /// Partitions Instrs into "chains" where every instruction has a known
331   /// constant offset from the first instr in the chain.
332   ///
333   /// Postcondition: For all i, ret[i][0].second == 0, because the first instr
334   /// in the chain is the leader, and an instr touches distance 0 from itself.
335   std::vector<Chain> gatherChains(ArrayRef<Instruction *> Instrs);
336 };
337 
338 class LoadStoreVectorizerLegacyPass : public FunctionPass {
339 public:
340   static char ID;
341 
342   LoadStoreVectorizerLegacyPass() : FunctionPass(ID) {
343     initializeLoadStoreVectorizerLegacyPassPass(
344         *PassRegistry::getPassRegistry());
345   }
346 
347   bool runOnFunction(Function &F) override;
348 
349   StringRef getPassName() const override {
350     return "GPU Load and Store Vectorizer";
351   }
352 
353   void getAnalysisUsage(AnalysisUsage &AU) const override {
354     AU.addRequired<AAResultsWrapperPass>();
355     AU.addRequired<AssumptionCacheTracker>();
356     AU.addRequired<ScalarEvolutionWrapperPass>();
357     AU.addRequired<DominatorTreeWrapperPass>();
358     AU.addRequired<TargetTransformInfoWrapperPass>();
359     AU.setPreservesCFG();
360   }
361 };
362 
363 } // end anonymous namespace
364 
365 char LoadStoreVectorizerLegacyPass::ID = 0;
366 
367 INITIALIZE_PASS_BEGIN(LoadStoreVectorizerLegacyPass, DEBUG_TYPE,
368                       "Vectorize load and Store instructions", false, false)
369 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
370 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
371 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
372 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
373 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
374 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
375 INITIALIZE_PASS_END(LoadStoreVectorizerLegacyPass, DEBUG_TYPE,
376                     "Vectorize load and store instructions", false, false)
377 
378 Pass *llvm::createLoadStoreVectorizerPass() {
379   return new LoadStoreVectorizerLegacyPass();
380 }
381 
382 bool LoadStoreVectorizerLegacyPass::runOnFunction(Function &F) {
383   // Don't vectorize when the attribute NoImplicitFloat is used.
384   if (skipFunction(F) || F.hasFnAttribute(Attribute::NoImplicitFloat))
385     return false;
386 
387   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
388   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
389   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
390   TargetTransformInfo &TTI =
391       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
392 
393   AssumptionCache &AC =
394       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
395 
396   return Vectorizer(F, AA, AC, DT, SE, TTI).run();
397 }
398 
399 PreservedAnalyses LoadStoreVectorizerPass::run(Function &F,
400                                                FunctionAnalysisManager &AM) {
401   // Don't vectorize when the attribute NoImplicitFloat is used.
402   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
403     return PreservedAnalyses::all();
404 
405   AliasAnalysis &AA = AM.getResult<AAManager>(F);
406   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
407   ScalarEvolution &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
408   TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
409   AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
410 
411   bool Changed = Vectorizer(F, AA, AC, DT, SE, TTI).run();
412   PreservedAnalyses PA;
413   PA.preserveSet<CFGAnalyses>();
414   return Changed ? PA : PreservedAnalyses::all();
415 }
416 
417 bool Vectorizer::run() {
418   bool Changed = false;
419   // Break up the BB if there are any instrs which aren't guaranteed to transfer
420   // execution to their successor.
421   //
422   // Consider, for example:
423   //
424   //   def assert_arr_len(int n) { if (n < 2) exit(); }
425   //
426   //   load arr[0]
427   //   call assert_array_len(arr.length)
428   //   load arr[1]
429   //
430   // Even though assert_arr_len does not read or write any memory, we can't
431   // speculate the second load before the call.  More info at
432   // https://github.com/llvm/llvm-project/issues/52950.
433   for (BasicBlock *BB : post_order(&F)) {
434     // BB must at least have a terminator.
435     assert(!BB->empty());
436 
437     SmallVector<BasicBlock::iterator, 8> Barriers;
438     Barriers.push_back(BB->begin());
439     for (Instruction &I : *BB)
440       if (!isGuaranteedToTransferExecutionToSuccessor(&I))
441         Barriers.push_back(I.getIterator());
442     Barriers.push_back(BB->end());
443 
444     for (auto It = Barriers.begin(), End = std::prev(Barriers.end()); It != End;
445          ++It)
446       Changed |= runOnPseudoBB(*It, *std::next(It));
447 
448     for (Instruction *I : ToErase) {
449       auto *PtrOperand = getLoadStorePointerOperand(I);
450       if (I->use_empty())
451         I->eraseFromParent();
452       RecursivelyDeleteTriviallyDeadInstructions(PtrOperand);
453     }
454     ToErase.clear();
455   }
456 
457   return Changed;
458 }
459 
460 bool Vectorizer::runOnPseudoBB(BasicBlock::iterator Begin,
461                                BasicBlock::iterator End) {
462   LLVM_DEBUG({
463     dbgs() << "LSV: Running on pseudo-BB [" << *Begin << " ... ";
464     if (End != Begin->getParent()->end())
465       dbgs() << *End;
466     else
467       dbgs() << "<BB end>";
468     dbgs() << ")\n";
469   });
470 
471   bool Changed = false;
472   for (const auto &[EqClassKey, EqClass] :
473        collectEquivalenceClasses(Begin, End))
474     Changed |= runOnEquivalenceClass(EqClassKey, EqClass);
475 
476   return Changed;
477 }
478 
479 bool Vectorizer::runOnEquivalenceClass(const EqClassKey &EqClassKey,
480                                        ArrayRef<Instruction *> EqClass) {
481   bool Changed = false;
482 
483   LLVM_DEBUG({
484     dbgs() << "LSV: Running on equivalence class of size " << EqClass.size()
485            << " keyed on " << EqClassKey << ":\n";
486     for (Instruction *I : EqClass)
487       dbgs() << "  " << *I << "\n";
488   });
489 
490   std::vector<Chain> Chains = gatherChains(EqClass);
491   LLVM_DEBUG(dbgs() << "LSV: Got " << Chains.size()
492                     << " nontrivial chains.\n";);
493   for (Chain &C : Chains)
494     Changed |= runOnChain(C);
495   return Changed;
496 }
497 
498 bool Vectorizer::runOnChain(Chain &C) {
499   LLVM_DEBUG({
500     dbgs() << "LSV: Running on chain with " << C.size() << " instructions:\n";
501     dumpChain(C);
502   });
503 
504   // Split up the chain into increasingly smaller chains, until we can finally
505   // vectorize the chains.
506   //
507   // (Don't be scared by the depth of the loop nest here.  These operations are
508   // all at worst O(n lg n) in the number of instructions, and splitting chains
509   // doesn't change the number of instrs.  So the whole loop nest is O(n lg n).)
510   bool Changed = false;
511   for (auto &C : splitChainByMayAliasInstrs(C))
512     for (auto &C : splitChainByContiguity(C))
513       for (auto &C : splitChainByAlignment(C))
514         Changed |= vectorizeChain(C);
515   return Changed;
516 }
517 
518 std::vector<Chain> Vectorizer::splitChainByMayAliasInstrs(Chain &C) {
519   if (C.empty())
520     return {};
521 
522   sortChainInBBOrder(C);
523 
524   LLVM_DEBUG({
525     dbgs() << "LSV: splitChainByMayAliasInstrs considering chain:\n";
526     dumpChain(C);
527   });
528 
529   // We know that elements in the chain with nonverlapping offsets can't
530   // alias, but AA may not be smart enough to figure this out.  Use a
531   // hashtable.
532   DenseMap<Instruction *, APInt /*OffsetFromLeader*/> ChainOffsets;
533   for (const auto &E : C)
534     ChainOffsets.insert({&*E.Inst, E.OffsetFromLeader});
535 
536   // Loads get hoisted up to the first load in the chain.  Stores get sunk
537   // down to the last store in the chain.  Our algorithm for loads is:
538   //
539   //  - Take the first element of the chain.  This is the start of a new chain.
540   //  - Take the next element of `Chain` and check for may-alias instructions
541   //    up to the start of NewChain.  If no may-alias instrs, add it to
542   //    NewChain.  Otherwise, start a new NewChain.
543   //
544   // For stores it's the same except in the reverse direction.
545   //
546   // We expect IsLoad to be an std::bool_constant.
547   auto Impl = [&](auto IsLoad) {
548     // MSVC is unhappy if IsLoad is a capture, so pass it as an arg.
549     auto [ChainBegin, ChainEnd] = [&](auto IsLoad) {
550       if constexpr (IsLoad())
551         return std::make_pair(C.begin(), C.end());
552       else
553         return std::make_pair(C.rbegin(), C.rend());
554     }(IsLoad);
555     assert(ChainBegin != ChainEnd);
556 
557     std::vector<Chain> Chains;
558     SmallVector<ChainElem, 1> NewChain;
559     NewChain.push_back(*ChainBegin);
560     for (auto ChainIt = std::next(ChainBegin); ChainIt != ChainEnd; ++ChainIt) {
561       if (isSafeToMove<IsLoad>(ChainIt->Inst, NewChain.front().Inst,
562                                ChainOffsets)) {
563         LLVM_DEBUG(dbgs() << "LSV: No intervening may-alias instrs; can merge "
564                           << *ChainIt->Inst << " into " << *ChainBegin->Inst
565                           << "\n");
566         NewChain.push_back(*ChainIt);
567       } else {
568         LLVM_DEBUG(
569             dbgs() << "LSV: Found intervening may-alias instrs; cannot merge "
570                    << *ChainIt->Inst << " into " << *ChainBegin->Inst << "\n");
571         if (NewChain.size() > 1) {
572           LLVM_DEBUG({
573             dbgs() << "LSV: got nontrivial chain without aliasing instrs:\n";
574             dumpChain(NewChain);
575           });
576           Chains.push_back(std::move(NewChain));
577         }
578 
579         // Start a new chain.
580         NewChain = SmallVector<ChainElem, 1>({*ChainIt});
581       }
582     }
583     if (NewChain.size() > 1) {
584       LLVM_DEBUG({
585         dbgs() << "LSV: got nontrivial chain without aliasing instrs:\n";
586         dumpChain(NewChain);
587       });
588       Chains.push_back(std::move(NewChain));
589     }
590     return Chains;
591   };
592 
593   if (isa<LoadInst>(C[0].Inst))
594     return Impl(/*IsLoad=*/std::bool_constant<true>());
595 
596   assert(isa<StoreInst>(C[0].Inst));
597   return Impl(/*IsLoad=*/std::bool_constant<false>());
598 }
599 
600 std::vector<Chain> Vectorizer::splitChainByContiguity(Chain &C) {
601   if (C.empty())
602     return {};
603 
604   sortChainInOffsetOrder(C);
605 
606   LLVM_DEBUG({
607     dbgs() << "LSV: splitChainByContiguity considering chain:\n";
608     dumpChain(C);
609   });
610 
611   std::vector<Chain> Ret;
612   Ret.push_back({C.front()});
613 
614   for (auto It = std::next(C.begin()), End = C.end(); It != End; ++It) {
615     // `prev` accesses offsets [PrevDistFromBase, PrevReadEnd).
616     auto &CurChain = Ret.back();
617     const ChainElem &Prev = CurChain.back();
618     unsigned SzBits = DL.getTypeSizeInBits(getLoadStoreType(&*Prev.Inst));
619     assert(SzBits % 8 == 0 && "Non-byte sizes should have been filtered out by "
620                               "collectEquivalenceClass");
621     APInt PrevReadEnd = Prev.OffsetFromLeader + SzBits / 8;
622 
623     // Add this instruction to the end of the current chain, or start a new one.
624     bool AreContiguous = It->OffsetFromLeader == PrevReadEnd;
625     LLVM_DEBUG(dbgs() << "LSV: Instructions are "
626                       << (AreContiguous ? "" : "not ") << "contiguous: "
627                       << *Prev.Inst << " (ends at offset " << PrevReadEnd
628                       << ") -> " << *It->Inst << " (starts at offset "
629                       << It->OffsetFromLeader << ")\n");
630     if (AreContiguous)
631       CurChain.push_back(*It);
632     else
633       Ret.push_back({*It});
634   }
635 
636   // Filter out length-1 chains, these are uninteresting.
637   llvm::erase_if(Ret, [](const auto &Chain) { return Chain.size() <= 1; });
638   return Ret;
639 }
640 
641 Type *Vectorizer::getChainElemTy(const Chain &C) {
642   assert(!C.empty());
643   // The rules are:
644   //  - If there are any pointer types in the chain, use an integer type.
645   //  - Prefer an integer type if it appears in the chain.
646   //  - Otherwise, use the first type in the chain.
647   //
648   // The rule about pointer types is a simplification when we merge e.g.  a load
649   // of a ptr and a double.  There's no direct conversion from a ptr to a
650   // double; it requires a ptrtoint followed by a bitcast.
651   //
652   // It's unclear to me if the other rules have any practical effect, but we do
653   // it to match this pass's previous behavior.
654   if (any_of(C, [](const ChainElem &E) {
655         return getLoadStoreType(E.Inst)->getScalarType()->isPointerTy();
656       })) {
657     return Type::getIntNTy(
658         F.getContext(),
659         DL.getTypeSizeInBits(getLoadStoreType(C[0].Inst)->getScalarType()));
660   }
661 
662   for (const ChainElem &E : C)
663     if (Type *T = getLoadStoreType(E.Inst)->getScalarType(); T->isIntegerTy())
664       return T;
665   return getLoadStoreType(C[0].Inst)->getScalarType();
666 }
667 
668 std::vector<Chain> Vectorizer::splitChainByAlignment(Chain &C) {
669   // We use a simple greedy algorithm.
670   //  - Given a chain of length N, find all prefixes that
671   //    (a) are not longer than the max register length, and
672   //    (b) are a power of 2.
673   //  - Starting from the longest prefix, try to create a vector of that length.
674   //  - If one of them works, great.  Repeat the algorithm on any remaining
675   //    elements in the chain.
676   //  - If none of them work, discard the first element and repeat on a chain
677   //    of length N-1.
678   if (C.empty())
679     return {};
680 
681   sortChainInOffsetOrder(C);
682 
683   LLVM_DEBUG({
684     dbgs() << "LSV: splitChainByAlignment considering chain:\n";
685     dumpChain(C);
686   });
687 
688   bool IsLoadChain = isa<LoadInst>(C[0].Inst);
689   auto getVectorFactor = [&](unsigned VF, unsigned LoadStoreSize,
690                              unsigned ChainSizeBytes, VectorType *VecTy) {
691     return IsLoadChain ? TTI.getLoadVectorFactor(VF, LoadStoreSize,
692                                                  ChainSizeBytes, VecTy)
693                        : TTI.getStoreVectorFactor(VF, LoadStoreSize,
694                                                   ChainSizeBytes, VecTy);
695   };
696 
697 #ifndef NDEBUG
698   for (const auto &E : C) {
699     Type *Ty = getLoadStoreType(E.Inst)->getScalarType();
700     assert(isPowerOf2_32(DL.getTypeSizeInBits(Ty)) &&
701            "Should have filtered out non-power-of-two elements in "
702            "collectEquivalenceClasses.");
703   }
704 #endif
705 
706   unsigned AS = getLoadStoreAddressSpace(C[0].Inst);
707   unsigned VecRegBytes = TTI.getLoadStoreVecRegBitWidth(AS) / 8;
708 
709   std::vector<Chain> Ret;
710   for (unsigned CBegin = 0; CBegin < C.size(); ++CBegin) {
711     // Find candidate chains of size not greater than the largest vector reg.
712     // These chains are over the closed interval [CBegin, CEnd].
713     SmallVector<std::pair<unsigned /*CEnd*/, unsigned /*SizeBytes*/>, 8>
714         CandidateChains;
715     for (unsigned CEnd = CBegin + 1, Size = C.size(); CEnd < Size; ++CEnd) {
716       APInt Sz = C[CEnd].OffsetFromLeader +
717                  DL.getTypeStoreSize(getLoadStoreType(C[CEnd].Inst)) -
718                  C[CBegin].OffsetFromLeader;
719       if (Sz.sgt(VecRegBytes))
720         break;
721       CandidateChains.push_back(
722           {CEnd, static_cast<unsigned>(Sz.getLimitedValue())});
723     }
724 
725     // Consider the longest chain first.
726     for (auto It = CandidateChains.rbegin(), End = CandidateChains.rend();
727          It != End; ++It) {
728       auto [CEnd, SizeBytes] = *It;
729       LLVM_DEBUG(
730           dbgs() << "LSV: splitChainByAlignment considering candidate chain ["
731                  << *C[CBegin].Inst << " ... " << *C[CEnd].Inst << "]\n");
732 
733       Type *VecElemTy = getChainElemTy(C);
734       // Note, VecElemTy is a power of 2, but might be less than one byte.  For
735       // example, we can vectorize 2 x <2 x i4> to <4 x i4>, and in this case
736       // VecElemTy would be i4.
737       unsigned VecElemBits = DL.getTypeSizeInBits(VecElemTy);
738 
739       // SizeBytes and VecElemBits are powers of 2, so they divide evenly.
740       assert((8 * SizeBytes) % VecElemBits == 0);
741       unsigned NumVecElems = 8 * SizeBytes / VecElemBits;
742       FixedVectorType *VecTy = FixedVectorType::get(VecElemTy, NumVecElems);
743       unsigned VF = 8 * VecRegBytes / VecElemBits;
744 
745       // Check that TTI is happy with this vectorization factor.
746       unsigned TargetVF = getVectorFactor(VF, VecElemBits,
747                                           VecElemBits * NumVecElems / 8, VecTy);
748       if (TargetVF != VF && TargetVF < NumVecElems) {
749         LLVM_DEBUG(
750             dbgs() << "LSV: splitChainByAlignment discarding candidate chain "
751                       "because TargetVF="
752                    << TargetVF << " != VF=" << VF
753                    << " and TargetVF < NumVecElems=" << NumVecElems << "\n");
754         continue;
755       }
756 
757       // Is a load/store with this alignment allowed by TTI and at least as fast
758       // as an unvectorized load/store?
759       //
760       // TTI and F are passed as explicit captures to WAR an MSVC misparse (??).
761       auto IsAllowedAndFast = [&, SizeBytes = SizeBytes, &TTI = TTI,
762                                &F = F](Align Alignment) {
763         if (Alignment.value() % SizeBytes == 0)
764           return true;
765         unsigned VectorizedSpeed = 0;
766         bool AllowsMisaligned = TTI.allowsMisalignedMemoryAccesses(
767             F.getContext(), SizeBytes * 8, AS, Alignment, &VectorizedSpeed);
768         if (!AllowsMisaligned) {
769           LLVM_DEBUG(dbgs()
770                      << "LSV: Access of " << SizeBytes << "B in addrspace "
771                      << AS << " with alignment " << Alignment.value()
772                      << " is misaligned, and therefore can't be vectorized.\n");
773           return false;
774         }
775 
776         unsigned ElementwiseSpeed = 0;
777         (TTI).allowsMisalignedMemoryAccesses((F).getContext(), VecElemBits, AS,
778                                              Alignment, &ElementwiseSpeed);
779         if (VectorizedSpeed < ElementwiseSpeed) {
780           LLVM_DEBUG(dbgs()
781                      << "LSV: Access of " << SizeBytes << "B in addrspace "
782                      << AS << " with alignment " << Alignment.value()
783                      << " has relative speed " << VectorizedSpeed
784                      << ", which is lower than the elementwise speed of "
785                      << ElementwiseSpeed
786                      << ".  Therefore this access won't be vectorized.\n");
787           return false;
788         }
789         return true;
790       };
791 
792       // If we're loading/storing from an alloca, align it if possible.
793       //
794       // FIXME: We eagerly upgrade the alignment, regardless of whether TTI
795       // tells us this is beneficial.  This feels a bit odd, but it matches
796       // existing tests.  This isn't *so* bad, because at most we align to 4
797       // bytes (current value of StackAdjustedAlignment).
798       //
799       // FIXME: We will upgrade the alignment of the alloca even if it turns out
800       // we can't vectorize for some other reason.
801       Align Alignment = getLoadStoreAlignment(C[CBegin].Inst);
802       if (AS == DL.getAllocaAddrSpace() && Alignment.value() % SizeBytes != 0 &&
803           IsAllowedAndFast(Align(StackAdjustedAlignment))) {
804         Align NewAlign = getOrEnforceKnownAlignment(
805             getLoadStorePointerOperand(C[CBegin].Inst),
806             Align(StackAdjustedAlignment), DL, C[CBegin].Inst, nullptr, &DT);
807         if (NewAlign >= Alignment) {
808           LLVM_DEBUG(dbgs()
809                      << "LSV: splitByChain upgrading alloca alignment from "
810                      << Alignment.value() << " to " << NewAlign.value()
811                      << "\n");
812           Alignment = NewAlign;
813         }
814       }
815 
816       if (!IsAllowedAndFast(Alignment)) {
817         LLVM_DEBUG(
818             dbgs() << "LSV: splitChainByAlignment discarding candidate chain "
819                       "because its alignment is not AllowedAndFast: "
820                    << Alignment.value() << "\n");
821         continue;
822       }
823 
824       if ((IsLoadChain &&
825            !TTI.isLegalToVectorizeLoadChain(SizeBytes, Alignment, AS)) ||
826           (!IsLoadChain &&
827            !TTI.isLegalToVectorizeStoreChain(SizeBytes, Alignment, AS))) {
828         LLVM_DEBUG(
829             dbgs() << "LSV: splitChainByAlignment discarding candidate chain "
830                       "because !isLegalToVectorizeLoad/StoreChain.");
831         continue;
832       }
833 
834       // Hooray, we can vectorize this chain!
835       Chain &NewChain = Ret.emplace_back();
836       for (unsigned I = CBegin; I <= CEnd; ++I)
837         NewChain.push_back(C[I]);
838       CBegin = CEnd; // Skip over the instructions we've added to the chain.
839       break;
840     }
841   }
842   return Ret;
843 }
844 
845 bool Vectorizer::vectorizeChain(Chain &C) {
846   if (C.size() < 2)
847     return false;
848 
849   sortChainInOffsetOrder(C);
850 
851   LLVM_DEBUG({
852     dbgs() << "LSV: Vectorizing chain of " << C.size() << " instructions:\n";
853     dumpChain(C);
854   });
855 
856   Type *VecElemTy = getChainElemTy(C);
857   bool IsLoadChain = isa<LoadInst>(C[0].Inst);
858   unsigned AS = getLoadStoreAddressSpace(C[0].Inst);
859   unsigned ChainBytes = std::accumulate(
860       C.begin(), C.end(), 0u, [&](unsigned Bytes, const ChainElem &E) {
861         return Bytes + DL.getTypeStoreSize(getLoadStoreType(E.Inst));
862       });
863   assert(ChainBytes % DL.getTypeStoreSize(VecElemTy) == 0);
864   // VecTy is a power of 2 and 1 byte at smallest, but VecElemTy may be smaller
865   // than 1 byte (e.g. VecTy == <32 x i1>).
866   Type *VecTy = FixedVectorType::get(
867       VecElemTy, 8 * ChainBytes / DL.getTypeSizeInBits(VecElemTy));
868 
869   Align Alignment = getLoadStoreAlignment(C[0].Inst);
870   // If this is a load/store of an alloca, we might have upgraded the alloca's
871   // alignment earlier.  Get the new alignment.
872   if (AS == DL.getAllocaAddrSpace()) {
873     Alignment = std::max(
874         Alignment,
875         getOrEnforceKnownAlignment(getLoadStorePointerOperand(C[0].Inst),
876                                    MaybeAlign(), DL, C[0].Inst, nullptr, &DT));
877   }
878 
879   // All elements of the chain must have the same scalar-type size.
880 #ifndef NDEBUG
881   for (const ChainElem &E : C)
882     assert(DL.getTypeStoreSize(getLoadStoreType(E.Inst)->getScalarType()) ==
883            DL.getTypeStoreSize(VecElemTy));
884 #endif
885 
886   Instruction *VecInst;
887   if (IsLoadChain) {
888     // Loads get hoisted to the location of the first load in the chain.  We may
889     // also need to hoist the (transitive) operands of the loads.
890     Builder.SetInsertPoint(
891         std::min_element(C.begin(), C.end(), [](const auto &A, const auto &B) {
892           return A.Inst->comesBefore(B.Inst);
893         })->Inst);
894 
895     // Chain is in offset order, so C[0] is the instr with the lowest offset,
896     // i.e. the root of the vector.
897     Value *Bitcast = Builder.CreateBitCast(
898         getLoadStorePointerOperand(C[0].Inst), VecTy->getPointerTo(AS));
899     VecInst = Builder.CreateAlignedLoad(VecTy, Bitcast, Alignment);
900 
901     unsigned VecIdx = 0;
902     for (const ChainElem &E : C) {
903       Instruction *I = E.Inst;
904       Value *V;
905       Type *T = getLoadStoreType(I);
906       if (auto *VT = dyn_cast<FixedVectorType>(T)) {
907         auto Mask = llvm::to_vector<8>(
908             llvm::seq<int>(VecIdx, VecIdx + VT->getNumElements()));
909         V = Builder.CreateShuffleVector(VecInst, Mask, I->getName());
910         VecIdx += VT->getNumElements();
911       } else {
912         V = Builder.CreateExtractElement(VecInst, Builder.getInt32(VecIdx),
913                                          I->getName());
914         ++VecIdx;
915       }
916       if (V->getType() != I->getType())
917         V = Builder.CreateBitOrPointerCast(V, I->getType());
918       I->replaceAllUsesWith(V);
919     }
920 
921     // Finally, we need to reorder the instrs in the BB so that the (transitive)
922     // operands of VecInst appear before it.  To see why, suppose we have
923     // vectorized the following code:
924     //
925     //   ptr1  = gep a, 1
926     //   load1 = load i32 ptr1
927     //   ptr0  = gep a, 0
928     //   load0 = load i32 ptr0
929     //
930     // We will put the vectorized load at the location of the earliest load in
931     // the BB, i.e. load1.  We get:
932     //
933     //   ptr1  = gep a, 1
934     //   loadv = load <2 x i32> ptr0
935     //   load0 = extractelement loadv, 0
936     //   load1 = extractelement loadv, 1
937     //   ptr0 = gep a, 0
938     //
939     // Notice that loadv uses ptr0, which is defined *after* it!
940     reorder(VecInst);
941   } else {
942     // Stores get sunk to the location of the last store in the chain.
943     Builder.SetInsertPoint(
944         std::max_element(C.begin(), C.end(), [](auto &A, auto &B) {
945           return A.Inst->comesBefore(B.Inst);
946         })->Inst);
947 
948     // Build the vector to store.
949     Value *Vec = PoisonValue::get(VecTy);
950     unsigned VecIdx = 0;
951     auto InsertElem = [&](Value *V) {
952       if (V->getType() != VecElemTy)
953         V = Builder.CreateBitOrPointerCast(V, VecElemTy);
954       Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(VecIdx++));
955     };
956     for (const ChainElem &E : C) {
957       auto I = cast<StoreInst>(E.Inst);
958       if (FixedVectorType *VT =
959               dyn_cast<FixedVectorType>(getLoadStoreType(I))) {
960         for (int J = 0, JE = VT->getNumElements(); J < JE; ++J) {
961           InsertElem(Builder.CreateExtractElement(I->getValueOperand(),
962                                                   Builder.getInt32(J)));
963         }
964       } else {
965         InsertElem(I->getValueOperand());
966       }
967     }
968 
969     // Chain is in offset order, so C[0] is the instr with the lowest offset,
970     // i.e. the root of the vector.
971     VecInst = Builder.CreateAlignedStore(
972         Vec,
973         Builder.CreateBitCast(getLoadStorePointerOperand(C[0].Inst),
974                               VecTy->getPointerTo(AS)),
975         Alignment);
976   }
977 
978   propagateMetadata(VecInst, C);
979 
980   for (const ChainElem &E : C)
981     ToErase.push_back(E.Inst);
982 
983   ++NumVectorInstructions;
984   NumScalarsVectorized += C.size();
985   return true;
986 }
987 
988 template <bool IsLoadChain>
989 bool Vectorizer::isSafeToMove(
990     Instruction *ChainElem, Instruction *ChainBegin,
991     const DenseMap<Instruction *, APInt /*OffsetFromLeader*/> &ChainOffsets) {
992   LLVM_DEBUG(dbgs() << "LSV: isSafeToMove(" << *ChainElem << " -> "
993                     << *ChainBegin << ")\n");
994 
995   assert(isa<LoadInst>(ChainElem) == IsLoadChain);
996   if (ChainElem == ChainBegin)
997     return true;
998 
999   // Invariant loads can always be reordered; by definition they are not
1000   // clobbered by stores.
1001   if (isInvariantLoad(ChainElem))
1002     return true;
1003 
1004   auto BBIt = std::next([&] {
1005     if constexpr (IsLoadChain)
1006       return BasicBlock::reverse_iterator(ChainElem);
1007     else
1008       return BasicBlock::iterator(ChainElem);
1009   }());
1010   auto BBItEnd = std::next([&] {
1011     if constexpr (IsLoadChain)
1012       return BasicBlock::reverse_iterator(ChainBegin);
1013     else
1014       return BasicBlock::iterator(ChainBegin);
1015   }());
1016 
1017   const APInt &ChainElemOffset = ChainOffsets.at(ChainElem);
1018   const unsigned ChainElemSize =
1019       DL.getTypeStoreSize(getLoadStoreType(ChainElem));
1020 
1021   for (; BBIt != BBItEnd; ++BBIt) {
1022     Instruction *I = &*BBIt;
1023 
1024     if (!I->mayReadOrWriteMemory())
1025       continue;
1026 
1027     // Loads can be reordered with other loads.
1028     if (IsLoadChain && isa<LoadInst>(I))
1029       continue;
1030 
1031     // Stores can be sunk below invariant loads.
1032     if (!IsLoadChain && isInvariantLoad(I))
1033       continue;
1034 
1035     // If I is in the chain, we can tell whether it aliases ChainIt by checking
1036     // what offset ChainIt accesses.  This may be better than AA is able to do.
1037     //
1038     // We should really only have duplicate offsets for stores (the duplicate
1039     // loads should be CSE'ed), but in case we have a duplicate load, we'll
1040     // split the chain so we don't have to handle this case specially.
1041     if (auto OffsetIt = ChainOffsets.find(I); OffsetIt != ChainOffsets.end()) {
1042       // I and ChainElem overlap if:
1043       //   - I and ChainElem have the same offset, OR
1044       //   - I's offset is less than ChainElem's, but I touches past the
1045       //     beginning of ChainElem, OR
1046       //   - ChainElem's offset is less than I's, but ChainElem touches past the
1047       //     beginning of I.
1048       const APInt &IOffset = OffsetIt->second;
1049       unsigned IElemSize = DL.getTypeStoreSize(getLoadStoreType(I));
1050       if (IOffset == ChainElemOffset ||
1051           (IOffset.sle(ChainElemOffset) &&
1052            (IOffset + IElemSize).sgt(ChainElemOffset)) ||
1053           (ChainElemOffset.sle(IOffset) &&
1054            (ChainElemOffset + ChainElemSize).sgt(OffsetIt->second))) {
1055         LLVM_DEBUG({
1056           // Double check that AA also sees this alias.  If not, we probably
1057           // have a bug.
1058           ModRefInfo MR = AA.getModRefInfo(I, MemoryLocation::get(ChainElem));
1059           assert(IsLoadChain ? isModSet(MR) : isModOrRefSet(MR));
1060           dbgs() << "LSV: Found alias in chain: " << *I << "\n";
1061         });
1062         return false; // We found an aliasing instruction; bail.
1063       }
1064 
1065       continue; // We're confident there's no alias.
1066     }
1067 
1068     LLVM_DEBUG(dbgs() << "LSV: Querying AA for " << *I << "\n");
1069     ModRefInfo MR = AA.getModRefInfo(I, MemoryLocation::get(ChainElem));
1070     if (IsLoadChain ? isModSet(MR) : isModOrRefSet(MR)) {
1071       LLVM_DEBUG(dbgs() << "LSV: Found alias in chain:\n"
1072                         << "  Aliasing instruction:\n"
1073                         << "    " << *I << '\n'
1074                         << "  Aliased instruction and pointer:\n"
1075                         << "    " << *ChainElem << '\n'
1076                         << "    " << *getLoadStorePointerOperand(ChainElem)
1077                         << '\n');
1078 
1079       return false;
1080     }
1081   }
1082   return true;
1083 }
1084 
1085 static bool checkNoWrapFlags(Instruction *I, bool Signed) {
1086   BinaryOperator *BinOpI = cast<BinaryOperator>(I);
1087   return (Signed && BinOpI->hasNoSignedWrap()) ||
1088          (!Signed && BinOpI->hasNoUnsignedWrap());
1089 }
1090 
1091 static bool checkIfSafeAddSequence(const APInt &IdxDiff, Instruction *AddOpA,
1092                                    unsigned MatchingOpIdxA, Instruction *AddOpB,
1093                                    unsigned MatchingOpIdxB, bool Signed) {
1094   LLVM_DEBUG(dbgs() << "LSV: checkIfSafeAddSequence IdxDiff=" << IdxDiff
1095                     << ", AddOpA=" << *AddOpA << ", MatchingOpIdxA="
1096                     << MatchingOpIdxA << ", AddOpB=" << *AddOpB
1097                     << ", MatchingOpIdxB=" << MatchingOpIdxB
1098                     << ", Signed=" << Signed << "\n");
1099   // If both OpA and OpB are adds with NSW/NUW and with one of the operands
1100   // being the same, we can guarantee that the transformation is safe if we can
1101   // prove that OpA won't overflow when Ret added to the other operand of OpA.
1102   // For example:
1103   //  %tmp7 = add nsw i32 %tmp2, %v0
1104   //  %tmp8 = sext i32 %tmp7 to i64
1105   //  ...
1106   //  %tmp11 = add nsw i32 %v0, 1
1107   //  %tmp12 = add nsw i32 %tmp2, %tmp11
1108   //  %tmp13 = sext i32 %tmp12 to i64
1109   //
1110   //  Both %tmp7 and %tmp12 have the nsw flag and the first operand is %tmp2.
1111   //  It's guaranteed that adding 1 to %tmp7 won't overflow because %tmp11 adds
1112   //  1 to %v0 and both %tmp11 and %tmp12 have the nsw flag.
1113   assert(AddOpA->getOpcode() == Instruction::Add &&
1114          AddOpB->getOpcode() == Instruction::Add &&
1115          checkNoWrapFlags(AddOpA, Signed) && checkNoWrapFlags(AddOpB, Signed));
1116   if (AddOpA->getOperand(MatchingOpIdxA) ==
1117       AddOpB->getOperand(MatchingOpIdxB)) {
1118     Value *OtherOperandA = AddOpA->getOperand(MatchingOpIdxA == 1 ? 0 : 1);
1119     Value *OtherOperandB = AddOpB->getOperand(MatchingOpIdxB == 1 ? 0 : 1);
1120     Instruction *OtherInstrA = dyn_cast<Instruction>(OtherOperandA);
1121     Instruction *OtherInstrB = dyn_cast<Instruction>(OtherOperandB);
1122     // Match `x +nsw/nuw y` and `x +nsw/nuw (y +nsw/nuw IdxDiff)`.
1123     if (OtherInstrB && OtherInstrB->getOpcode() == Instruction::Add &&
1124         checkNoWrapFlags(OtherInstrB, Signed) &&
1125         isa<ConstantInt>(OtherInstrB->getOperand(1))) {
1126       int64_t CstVal =
1127           cast<ConstantInt>(OtherInstrB->getOperand(1))->getSExtValue();
1128       if (OtherInstrB->getOperand(0) == OtherOperandA &&
1129           IdxDiff.getSExtValue() == CstVal)
1130         return true;
1131     }
1132     // Match `x +nsw/nuw (y +nsw/nuw -Idx)` and `x +nsw/nuw (y +nsw/nuw x)`.
1133     if (OtherInstrA && OtherInstrA->getOpcode() == Instruction::Add &&
1134         checkNoWrapFlags(OtherInstrA, Signed) &&
1135         isa<ConstantInt>(OtherInstrA->getOperand(1))) {
1136       int64_t CstVal =
1137           cast<ConstantInt>(OtherInstrA->getOperand(1))->getSExtValue();
1138       if (OtherInstrA->getOperand(0) == OtherOperandB &&
1139           IdxDiff.getSExtValue() == -CstVal)
1140         return true;
1141     }
1142     // Match `x +nsw/nuw (y +nsw/nuw c)` and
1143     // `x +nsw/nuw (y +nsw/nuw (c + IdxDiff))`.
1144     if (OtherInstrA && OtherInstrB &&
1145         OtherInstrA->getOpcode() == Instruction::Add &&
1146         OtherInstrB->getOpcode() == Instruction::Add &&
1147         checkNoWrapFlags(OtherInstrA, Signed) &&
1148         checkNoWrapFlags(OtherInstrB, Signed) &&
1149         isa<ConstantInt>(OtherInstrA->getOperand(1)) &&
1150         isa<ConstantInt>(OtherInstrB->getOperand(1))) {
1151       int64_t CstValA =
1152           cast<ConstantInt>(OtherInstrA->getOperand(1))->getSExtValue();
1153       int64_t CstValB =
1154           cast<ConstantInt>(OtherInstrB->getOperand(1))->getSExtValue();
1155       if (OtherInstrA->getOperand(0) == OtherInstrB->getOperand(0) &&
1156           IdxDiff.getSExtValue() == (CstValB - CstValA))
1157         return true;
1158     }
1159   }
1160   return false;
1161 }
1162 
1163 std::optional<APInt> Vectorizer::gtConstantOffsetComplexAddrs(Value *PtrA,
1164                                                               Value *PtrB,
1165                                                               unsigned Depth) {
1166   LLVM_DEBUG(dbgs() << "LSV: gtConstantOffsetComplexAddrs PtrA=" << *PtrA
1167                     << " PtrB=" << *PtrB << " Depth=" << Depth << "\n");
1168   auto *GEPA = dyn_cast<GetElementPtrInst>(PtrA);
1169   auto *GEPB = dyn_cast<GetElementPtrInst>(PtrB);
1170   if (!GEPA || !GEPB)
1171     return getConstantOffsetSelects(PtrA, PtrB, Depth);
1172 
1173   // Look through GEPs after checking they're the same except for the last
1174   // index.
1175   if (GEPA->getNumOperands() != GEPB->getNumOperands() ||
1176       GEPA->getPointerOperand() != GEPB->getPointerOperand())
1177     return std::nullopt;
1178   gep_type_iterator GTIA = gep_type_begin(GEPA);
1179   gep_type_iterator GTIB = gep_type_begin(GEPB);
1180   for (unsigned I = 0, E = GEPA->getNumIndices() - 1; I < E; ++I) {
1181     if (GTIA.getOperand() != GTIB.getOperand())
1182       return std::nullopt;
1183     ++GTIA;
1184     ++GTIB;
1185   }
1186 
1187   Instruction *OpA = dyn_cast<Instruction>(GTIA.getOperand());
1188   Instruction *OpB = dyn_cast<Instruction>(GTIB.getOperand());
1189   if (!OpA || !OpB || OpA->getOpcode() != OpB->getOpcode() ||
1190       OpA->getType() != OpB->getType())
1191     return std::nullopt;
1192 
1193   uint64_t Stride = DL.getTypeAllocSize(GTIA.getIndexedType());
1194 
1195   // Only look through a ZExt/SExt.
1196   if (!isa<SExtInst>(OpA) && !isa<ZExtInst>(OpA))
1197     return std::nullopt;
1198 
1199   bool Signed = isa<SExtInst>(OpA);
1200 
1201   // At this point A could be a function parameter, i.e. not an instruction
1202   Value *ValA = OpA->getOperand(0);
1203   OpB = dyn_cast<Instruction>(OpB->getOperand(0));
1204   if (!OpB || ValA->getType() != OpB->getType())
1205     return std::nullopt;
1206 
1207   const SCEV *OffsetSCEVA = SE.getSCEV(ValA);
1208   const SCEV *OffsetSCEVB = SE.getSCEV(OpB);
1209   const SCEV *IdxDiffSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
1210   if (IdxDiffSCEV == SE.getCouldNotCompute())
1211     return std::nullopt;
1212 
1213   ConstantRange IdxDiffRange = SE.getSignedRange(IdxDiffSCEV);
1214   if (!IdxDiffRange.isSingleElement())
1215     return std::nullopt;
1216   APInt IdxDiff = *IdxDiffRange.getSingleElement();
1217 
1218   LLVM_DEBUG(dbgs() << "LSV: gtConstantOffsetComplexAddrs IdxDiff=" << IdxDiff
1219                     << "\n");
1220 
1221   // Now we need to prove that adding IdxDiff to ValA won't overflow.
1222   bool Safe = false;
1223 
1224   // First attempt: if OpB is an add with NSW/NUW, and OpB is IdxDiff added to
1225   // ValA, we're okay.
1226   if (OpB->getOpcode() == Instruction::Add &&
1227       isa<ConstantInt>(OpB->getOperand(1)) &&
1228       IdxDiff.sle(cast<ConstantInt>(OpB->getOperand(1))->getSExtValue()) &&
1229       checkNoWrapFlags(OpB, Signed))
1230     Safe = true;
1231 
1232   // Second attempt: check if we have eligible add NSW/NUW instruction
1233   // sequences.
1234   OpA = dyn_cast<Instruction>(ValA);
1235   if (!Safe && OpA && OpA->getOpcode() == Instruction::Add &&
1236       OpB->getOpcode() == Instruction::Add && checkNoWrapFlags(OpA, Signed) &&
1237       checkNoWrapFlags(OpB, Signed)) {
1238     // In the checks below a matching operand in OpA and OpB is an operand which
1239     // is the same in those two instructions.  Below we account for possible
1240     // orders of the operands of these add instructions.
1241     for (unsigned MatchingOpIdxA : {0, 1})
1242       for (unsigned MatchingOpIdxB : {0, 1})
1243         if (!Safe)
1244           Safe = checkIfSafeAddSequence(IdxDiff, OpA, MatchingOpIdxA, OpB,
1245                                         MatchingOpIdxB, Signed);
1246   }
1247 
1248   unsigned BitWidth = ValA->getType()->getScalarSizeInBits();
1249 
1250   // Third attempt:
1251   //
1252   // Assuming IdxDiff is positive: If all set bits of IdxDiff or any higher
1253   // order bit other than the sign bit are known to be zero in ValA, we can add
1254   // Diff to it while guaranteeing no overflow of any sort.
1255   //
1256   // If IdxDiff is negative, do the same, but swap ValA and ValB.
1257   if (!Safe) {
1258     // When computing known bits, use the GEPs as context instructions, since
1259     // they likely are in the same BB as the load/store.
1260     Instruction *ContextInst = GEPA->comesBefore(GEPB) ? GEPB : GEPA;
1261     KnownBits Known(BitWidth);
1262     computeKnownBits((IdxDiff.sge(0) ? ValA : OpB), Known, DL, 0, &AC,
1263                      ContextInst, &DT);
1264     APInt BitsAllowedToBeSet = Known.Zero.zext(IdxDiff.getBitWidth());
1265     if (Signed)
1266       BitsAllowedToBeSet.clearBit(BitWidth - 1);
1267     if (BitsAllowedToBeSet.ult(IdxDiff.abs()))
1268       return std::nullopt;
1269     Safe = true;
1270   }
1271 
1272   if (Safe)
1273     return IdxDiff * Stride;
1274   return std::nullopt;
1275 }
1276 
1277 std::optional<APInt>
1278 Vectorizer::getConstantOffsetSelects(Value *PtrA, Value *PtrB, unsigned Depth) {
1279   if (Depth++ == MaxDepth)
1280     return std::nullopt;
1281 
1282   if (auto *SelectA = dyn_cast<SelectInst>(PtrA)) {
1283     if (auto *SelectB = dyn_cast<SelectInst>(PtrB)) {
1284       if (SelectA->getCondition() != SelectB->getCondition())
1285         return std::nullopt;
1286       LLVM_DEBUG(dbgs() << "LSV: getConstantOffsetSelects, PtrA=" << *PtrA
1287                         << ", PtrB=" << *PtrB << ", Depth=" << Depth << "\n");
1288       std::optional<APInt> TrueDiff = getConstantOffset(
1289           SelectA->getTrueValue(), SelectB->getTrueValue(), Depth);
1290       if (!TrueDiff.has_value())
1291         return std::nullopt;
1292       std::optional<APInt> FalseDiff = getConstantOffset(
1293           SelectA->getFalseValue(), SelectB->getFalseValue(), Depth);
1294       if (TrueDiff == FalseDiff)
1295         return TrueDiff;
1296     }
1297   }
1298   return std::nullopt;
1299 }
1300 
1301 EquivalenceClassMap
1302 Vectorizer::collectEquivalenceClasses(BasicBlock::iterator Begin,
1303                                       BasicBlock::iterator End) {
1304   EquivalenceClassMap Ret;
1305 
1306   auto getUnderlyingObject = [](const Value *Ptr) -> const Value * {
1307     const Value *ObjPtr = llvm::getUnderlyingObject(Ptr);
1308     if (const auto *Sel = dyn_cast<SelectInst>(ObjPtr)) {
1309       // The select's themselves are distinct instructions even if they share
1310       // the same condition and evaluate to consecutive pointers for true and
1311       // false values of the condition. Therefore using the select's themselves
1312       // for grouping instructions would put consecutive accesses into different
1313       // lists and they won't be even checked for being consecutive, and won't
1314       // be vectorized.
1315       return Sel->getCondition();
1316     }
1317     return ObjPtr;
1318   };
1319 
1320   for (Instruction &I : make_range(Begin, End)) {
1321     auto *LI = dyn_cast<LoadInst>(&I);
1322     auto *SI = dyn_cast<StoreInst>(&I);
1323     if (!LI && !SI)
1324       continue;
1325 
1326     if ((LI && !LI->isSimple()) || (SI && !SI->isSimple()))
1327       continue;
1328 
1329     if ((LI && !TTI.isLegalToVectorizeLoad(LI)) ||
1330         (SI && !TTI.isLegalToVectorizeStore(SI)))
1331       continue;
1332 
1333     Type *Ty = getLoadStoreType(&I);
1334     if (!VectorType::isValidElementType(Ty->getScalarType()))
1335       continue;
1336 
1337     // Skip weird non-byte sizes. They probably aren't worth the effort of
1338     // handling correctly.
1339     unsigned TySize = DL.getTypeSizeInBits(Ty);
1340     if ((TySize % 8) != 0)
1341       continue;
1342 
1343     // Skip vectors of pointers. The vectorizeLoadChain/vectorizeStoreChain
1344     // functions are currently using an integer type for the vectorized
1345     // load/store, and does not support casting between the integer type and a
1346     // vector of pointers (e.g. i64 to <2 x i16*>)
1347     if (Ty->isVectorTy() && Ty->isPtrOrPtrVectorTy())
1348       continue;
1349 
1350     Value *Ptr = getLoadStorePointerOperand(&I);
1351     unsigned AS = Ptr->getType()->getPointerAddressSpace();
1352     unsigned VecRegSize = TTI.getLoadStoreVecRegBitWidth(AS);
1353 
1354     unsigned VF = VecRegSize / TySize;
1355     VectorType *VecTy = dyn_cast<VectorType>(Ty);
1356 
1357     // Only handle power-of-two sized elements.
1358     if ((!VecTy && !isPowerOf2_32(DL.getTypeSizeInBits(Ty))) ||
1359         (VecTy && !isPowerOf2_32(DL.getTypeSizeInBits(VecTy->getScalarType()))))
1360       continue;
1361 
1362     // No point in looking at these if they're too big to vectorize.
1363     if (TySize > VecRegSize / 2 ||
1364         (VecTy && TTI.getLoadVectorFactor(VF, TySize, TySize / 8, VecTy) == 0))
1365       continue;
1366 
1367     Ret[{getUnderlyingObject(Ptr), AS,
1368          DL.getTypeSizeInBits(getLoadStoreType(&I)->getScalarType()),
1369          /*IsLoad=*/LI != nullptr}]
1370         .push_back(&I);
1371   }
1372 
1373   return Ret;
1374 }
1375 
1376 std::vector<Chain> Vectorizer::gatherChains(ArrayRef<Instruction *> Instrs) {
1377   if (Instrs.empty())
1378     return {};
1379 
1380   unsigned AS = getLoadStoreAddressSpace(Instrs[0]);
1381   unsigned ASPtrBits = DL.getIndexSizeInBits(AS);
1382 
1383 #ifndef NDEBUG
1384   // Check that Instrs is in BB order and all have the same addr space.
1385   for (size_t I = 1; I < Instrs.size(); ++I) {
1386     assert(Instrs[I - 1]->comesBefore(Instrs[I]));
1387     assert(getLoadStoreAddressSpace(Instrs[I]) == AS);
1388   }
1389 #endif
1390 
1391   // Machinery to build an MRU-hashtable of Chains.
1392   //
1393   // (Ideally this could be done with MapVector, but as currently implemented,
1394   // moving an element to the front of a MapVector is O(n).)
1395   struct InstrListElem : ilist_node<InstrListElem>,
1396                          std::pair<Instruction *, Chain> {
1397     explicit InstrListElem(Instruction *I)
1398         : std::pair<Instruction *, Chain>(I, {}) {}
1399   };
1400   struct InstrListElemDenseMapInfo {
1401     using PtrInfo = DenseMapInfo<InstrListElem *>;
1402     using IInfo = DenseMapInfo<Instruction *>;
1403     static InstrListElem *getEmptyKey() { return PtrInfo::getEmptyKey(); }
1404     static InstrListElem *getTombstoneKey() {
1405       return PtrInfo::getTombstoneKey();
1406     }
1407     static unsigned getHashValue(const InstrListElem *E) {
1408       return IInfo::getHashValue(E->first);
1409     }
1410     static bool isEqual(const InstrListElem *A, const InstrListElem *B) {
1411       if (A == getEmptyKey() || B == getEmptyKey())
1412         return A == getEmptyKey() && B == getEmptyKey();
1413       if (A == getTombstoneKey() || B == getTombstoneKey())
1414         return A == getTombstoneKey() && B == getTombstoneKey();
1415       return IInfo::isEqual(A->first, B->first);
1416     }
1417   };
1418   SpecificBumpPtrAllocator<InstrListElem> Allocator;
1419   simple_ilist<InstrListElem> MRU;
1420   DenseSet<InstrListElem *, InstrListElemDenseMapInfo> Chains;
1421 
1422   // Compare each instruction in `instrs` to leader of the N most recently-used
1423   // chains.  This limits the O(n^2) behavior of this pass while also allowing
1424   // us to build arbitrarily long chains.
1425   for (Instruction *I : Instrs) {
1426     constexpr int MaxChainsToTry = 64;
1427 
1428     bool MatchFound = false;
1429     auto ChainIter = MRU.begin();
1430     for (size_t J = 0; J < MaxChainsToTry && ChainIter != MRU.end();
1431          ++J, ++ChainIter) {
1432       std::optional<APInt> Offset =
1433           getConstantOffset(getLoadStorePointerOperand(ChainIter->first),
1434                             getLoadStorePointerOperand(I));
1435       if (Offset.has_value()) {
1436         // `Offset` might not have the expected number of bits, if e.g. AS has a
1437         // different number of bits than opaque pointers.
1438         ChainIter->second.push_back(
1439             ChainElem{I, Offset.value().sextOrTrunc(ASPtrBits)});
1440         // Move ChainIter to the front of the MRU list.
1441         MRU.remove(*ChainIter);
1442         MRU.push_front(*ChainIter);
1443         MatchFound = true;
1444         break;
1445       }
1446     }
1447 
1448     if (!MatchFound) {
1449       APInt ZeroOffset(ASPtrBits, 0);
1450       InstrListElem *E = new (Allocator.Allocate()) InstrListElem(I);
1451       E->second.push_back(ChainElem{I, ZeroOffset});
1452       MRU.push_front(*E);
1453       Chains.insert(E);
1454     }
1455   }
1456 
1457   std::vector<Chain> Ret;
1458   Ret.reserve(Chains.size());
1459   // Iterate over MRU rather than Chains so the order is deterministic.
1460   for (auto &E : MRU)
1461     if (E.second.size() > 1)
1462       Ret.push_back(std::move(E.second));
1463   return Ret;
1464 }
1465 
1466 std::optional<APInt> Vectorizer::getConstantOffset(Value *PtrA, Value *PtrB,
1467                                                    unsigned Depth) {
1468   LLVM_DEBUG(dbgs() << "LSV: getConstantOffset, PtrA=" << *PtrA
1469                     << ", PtrB=" << *PtrB << ", Depth=" << Depth << "\n");
1470   unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(PtrA->getType());
1471   APInt OffsetA(OffsetBitWidth, 0);
1472   APInt OffsetB(OffsetBitWidth, 0);
1473   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1474   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1475   unsigned NewPtrBitWidth = DL.getTypeStoreSizeInBits(PtrA->getType());
1476   if (NewPtrBitWidth != DL.getTypeStoreSizeInBits(PtrB->getType()))
1477     return std::nullopt;
1478 
1479   // If we have to shrink the pointer, stripAndAccumulateInBoundsConstantOffsets
1480   // should properly handle a possible overflow and the value should fit into
1481   // the smallest data type used in the cast/gep chain.
1482   assert(OffsetA.getSignificantBits() <= NewPtrBitWidth &&
1483          OffsetB.getSignificantBits() <= NewPtrBitWidth);
1484 
1485   OffsetA = OffsetA.sextOrTrunc(NewPtrBitWidth);
1486   OffsetB = OffsetB.sextOrTrunc(NewPtrBitWidth);
1487   if (PtrA == PtrB)
1488     return OffsetB - OffsetA;
1489 
1490   // Try to compute B - A.
1491   const SCEV *DistScev = SE.getMinusSCEV(SE.getSCEV(PtrB), SE.getSCEV(PtrA));
1492   if (DistScev != SE.getCouldNotCompute()) {
1493     LLVM_DEBUG(dbgs() << "LSV: SCEV PtrB - PtrA =" << *DistScev << "\n");
1494     ConstantRange DistRange = SE.getSignedRange(DistScev);
1495     if (DistRange.isSingleElement())
1496       return OffsetB - OffsetA + *DistRange.getSingleElement();
1497   }
1498   std::optional<APInt> Diff = gtConstantOffsetComplexAddrs(PtrA, PtrB, Depth);
1499   if (Diff.has_value())
1500     return OffsetB - OffsetA + Diff->sext(OffsetB.getBitWidth());
1501   return std::nullopt;
1502 }
1503