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