1 //===- InterleavedAccessPass.cpp ------------------------------------------===// 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 file implements the Interleaved Access pass, which identifies 10 // interleaved memory accesses and transforms them into target specific 11 // intrinsics. 12 // 13 // An interleaved load reads data from memory into several vectors, with 14 // DE-interleaving the data on a factor. An interleaved store writes several 15 // vectors to memory with RE-interleaving the data on a factor. 16 // 17 // As interleaved accesses are difficult to identified in CodeGen (mainly 18 // because the VECTOR_SHUFFLE DAG node is quite different from the shufflevector 19 // IR), we identify and transform them to intrinsics in this pass so the 20 // intrinsics can be easily matched into target specific instructions later in 21 // CodeGen. 22 // 23 // E.g. An interleaved load (Factor = 2): 24 // %wide.vec = load <8 x i32>, <8 x i32>* %ptr 25 // %v0 = shuffle <8 x i32> %wide.vec, <8 x i32> poison, <0, 2, 4, 6> 26 // %v1 = shuffle <8 x i32> %wide.vec, <8 x i32> poison, <1, 3, 5, 7> 27 // 28 // It could be transformed into a ld2 intrinsic in AArch64 backend or a vld2 29 // intrinsic in ARM backend. 30 // 31 // In X86, this can be further optimized into a set of target 32 // specific loads followed by an optimized sequence of shuffles. 33 // 34 // E.g. An interleaved store (Factor = 3): 35 // %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 36 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 37 // store <12 x i32> %i.vec, <12 x i32>* %ptr 38 // 39 // It could be transformed into a st3 intrinsic in AArch64 backend or a vst3 40 // intrinsic in ARM backend. 41 // 42 // Similarly, a set of interleaved stores can be transformed into an optimized 43 // sequence of shuffles followed by a set of target specific stores for X86. 44 // 45 //===----------------------------------------------------------------------===// 46 47 #include "llvm/ADT/ArrayRef.h" 48 #include "llvm/ADT/DenseMap.h" 49 #include "llvm/ADT/SetVector.h" 50 #include "llvm/ADT/SmallVector.h" 51 #include "llvm/CodeGen/TargetLowering.h" 52 #include "llvm/CodeGen/TargetPassConfig.h" 53 #include "llvm/CodeGen/TargetSubtargetInfo.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/Dominators.h" 56 #include "llvm/IR/Function.h" 57 #include "llvm/IR/IRBuilder.h" 58 #include "llvm/IR/InstIterator.h" 59 #include "llvm/IR/Instruction.h" 60 #include "llvm/IR/Instructions.h" 61 #include "llvm/IR/Type.h" 62 #include "llvm/InitializePasses.h" 63 #include "llvm/Pass.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CommandLine.h" 66 #include "llvm/Support/Debug.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Transforms/Utils/Local.h" 71 #include <cassert> 72 #include <utility> 73 74 using namespace llvm; 75 76 #define DEBUG_TYPE "interleaved-access" 77 78 static cl::opt<bool> LowerInterleavedAccesses( 79 "lower-interleaved-accesses", 80 cl::desc("Enable lowering interleaved accesses to intrinsics"), 81 cl::init(true), cl::Hidden); 82 83 namespace { 84 85 class InterleavedAccess : public FunctionPass { 86 public: 87 static char ID; 88 89 InterleavedAccess() : FunctionPass(ID) { 90 initializeInterleavedAccessPass(*PassRegistry::getPassRegistry()); 91 } 92 93 StringRef getPassName() const override { return "Interleaved Access Pass"; } 94 95 bool runOnFunction(Function &F) override; 96 97 void getAnalysisUsage(AnalysisUsage &AU) const override { 98 AU.addRequired<DominatorTreeWrapperPass>(); 99 AU.setPreservesCFG(); 100 } 101 102 private: 103 DominatorTree *DT = nullptr; 104 const TargetLowering *TLI = nullptr; 105 106 /// The maximum supported interleave factor. 107 unsigned MaxFactor; 108 109 /// Transform an interleaved load into target specific intrinsics. 110 bool lowerInterleavedLoad(LoadInst *LI, 111 SmallVector<Instruction *, 32> &DeadInsts); 112 113 /// Transform an interleaved store into target specific intrinsics. 114 bool lowerInterleavedStore(StoreInst *SI, 115 SmallVector<Instruction *, 32> &DeadInsts); 116 117 /// Returns true if the uses of an interleaved load by the 118 /// extractelement instructions in \p Extracts can be replaced by uses of the 119 /// shufflevector instructions in \p Shuffles instead. If so, the necessary 120 /// replacements are also performed. 121 bool tryReplaceExtracts(ArrayRef<ExtractElementInst *> Extracts, 122 ArrayRef<ShuffleVectorInst *> Shuffles); 123 124 /// Given a number of shuffles of the form shuffle(binop(x,y)), convert them 125 /// to binop(shuffle(x), shuffle(y)) to allow the formation of an 126 /// interleaving load. Any newly created shuffles that operate on \p LI will 127 /// be added to \p Shuffles. Returns true, if any changes to the IR have been 128 /// made. 129 bool replaceBinOpShuffles(ArrayRef<ShuffleVectorInst *> BinOpShuffles, 130 SmallVectorImpl<ShuffleVectorInst *> &Shuffles, 131 LoadInst *LI); 132 }; 133 134 } // end anonymous namespace. 135 136 char InterleavedAccess::ID = 0; 137 138 INITIALIZE_PASS_BEGIN(InterleavedAccess, DEBUG_TYPE, 139 "Lower interleaved memory accesses to target specific intrinsics", false, 140 false) 141 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 142 INITIALIZE_PASS_END(InterleavedAccess, DEBUG_TYPE, 143 "Lower interleaved memory accesses to target specific intrinsics", false, 144 false) 145 146 FunctionPass *llvm::createInterleavedAccessPass() { 147 return new InterleavedAccess(); 148 } 149 150 /// Check if the mask is a DE-interleave mask of the given factor 151 /// \p Factor like: 152 /// <Index, Index+Factor, ..., Index+(NumElts-1)*Factor> 153 static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor, 154 unsigned &Index) { 155 // Check all potential start indices from 0 to (Factor - 1). 156 for (Index = 0; Index < Factor; Index++) { 157 unsigned i = 0; 158 159 // Check that elements are in ascending order by Factor. Ignore undef 160 // elements. 161 for (; i < Mask.size(); i++) 162 if (Mask[i] >= 0 && static_cast<unsigned>(Mask[i]) != Index + i * Factor) 163 break; 164 165 if (i == Mask.size()) 166 return true; 167 } 168 169 return false; 170 } 171 172 /// Check if the mask is a DE-interleave mask for an interleaved load. 173 /// 174 /// E.g. DE-interleave masks (Factor = 2) could be: 175 /// <0, 2, 4, 6> (mask of index 0 to extract even elements) 176 /// <1, 3, 5, 7> (mask of index 1 to extract odd elements) 177 static bool isDeInterleaveMask(ArrayRef<int> Mask, unsigned &Factor, 178 unsigned &Index, unsigned MaxFactor, 179 unsigned NumLoadElements) { 180 if (Mask.size() < 2) 181 return false; 182 183 // Check potential Factors. 184 for (Factor = 2; Factor <= MaxFactor; Factor++) { 185 // Make sure we don't produce a load wider than the input load. 186 if (Mask.size() * Factor > NumLoadElements) 187 return false; 188 if (isDeInterleaveMaskOfFactor(Mask, Factor, Index)) 189 return true; 190 } 191 192 return false; 193 } 194 195 /// Check if the mask can be used in an interleaved store. 196 // 197 /// It checks for a more general pattern than the RE-interleave mask. 198 /// I.e. <x, y, ... z, x+1, y+1, ...z+1, x+2, y+2, ...z+2, ...> 199 /// E.g. For a Factor of 2 (LaneLen=4): <4, 32, 5, 33, 6, 34, 7, 35> 200 /// E.g. For a Factor of 3 (LaneLen=4): <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 201 /// E.g. For a Factor of 4 (LaneLen=2): <8, 2, 12, 4, 9, 3, 13, 5> 202 /// 203 /// The particular case of an RE-interleave mask is: 204 /// I.e. <0, LaneLen, ... , LaneLen*(Factor - 1), 1, LaneLen + 1, ...> 205 /// E.g. For a Factor of 2 (LaneLen=4): <0, 4, 1, 5, 2, 6, 3, 7> 206 static bool isReInterleaveMask(ArrayRef<int> Mask, unsigned &Factor, 207 unsigned MaxFactor, unsigned OpNumElts) { 208 unsigned NumElts = Mask.size(); 209 if (NumElts < 4) 210 return false; 211 212 // Check potential Factors. 213 for (Factor = 2; Factor <= MaxFactor; Factor++) { 214 if (NumElts % Factor) 215 continue; 216 217 unsigned LaneLen = NumElts / Factor; 218 if (!isPowerOf2_32(LaneLen)) 219 continue; 220 221 // Check whether each element matches the general interleaved rule. 222 // Ignore undef elements, as long as the defined elements match the rule. 223 // Outer loop processes all factors (x, y, z in the above example) 224 unsigned I = 0, J; 225 for (; I < Factor; I++) { 226 unsigned SavedLaneValue; 227 unsigned SavedNoUndefs = 0; 228 229 // Inner loop processes consecutive accesses (x, x+1... in the example) 230 for (J = 0; J < LaneLen - 1; J++) { 231 // Lane computes x's position in the Mask 232 unsigned Lane = J * Factor + I; 233 unsigned NextLane = Lane + Factor; 234 int LaneValue = Mask[Lane]; 235 int NextLaneValue = Mask[NextLane]; 236 237 // If both are defined, values must be sequential 238 if (LaneValue >= 0 && NextLaneValue >= 0 && 239 LaneValue + 1 != NextLaneValue) 240 break; 241 242 // If the next value is undef, save the current one as reference 243 if (LaneValue >= 0 && NextLaneValue < 0) { 244 SavedLaneValue = LaneValue; 245 SavedNoUndefs = 1; 246 } 247 248 // Undefs are allowed, but defined elements must still be consecutive: 249 // i.e.: x,..., undef,..., x + 2,..., undef,..., undef,..., x + 5, .... 250 // Verify this by storing the last non-undef followed by an undef 251 // Check that following non-undef masks are incremented with the 252 // corresponding distance. 253 if (SavedNoUndefs > 0 && LaneValue < 0) { 254 SavedNoUndefs++; 255 if (NextLaneValue >= 0 && 256 SavedLaneValue + SavedNoUndefs != (unsigned)NextLaneValue) 257 break; 258 } 259 } 260 261 if (J < LaneLen - 1) 262 break; 263 264 int StartMask = 0; 265 if (Mask[I] >= 0) { 266 // Check that the start of the I range (J=0) is greater than 0 267 StartMask = Mask[I]; 268 } else if (Mask[(LaneLen - 1) * Factor + I] >= 0) { 269 // StartMask defined by the last value in lane 270 StartMask = Mask[(LaneLen - 1) * Factor + I] - J; 271 } else if (SavedNoUndefs > 0) { 272 // StartMask defined by some non-zero value in the j loop 273 StartMask = SavedLaneValue - (LaneLen - 1 - SavedNoUndefs); 274 } 275 // else StartMask remains set to 0, i.e. all elements are undefs 276 277 if (StartMask < 0) 278 break; 279 // We must stay within the vectors; This case can happen with undefs. 280 if (StartMask + LaneLen > OpNumElts*2) 281 break; 282 } 283 284 // Found an interleaved mask of current factor. 285 if (I == Factor) 286 return true; 287 } 288 289 return false; 290 } 291 292 bool InterleavedAccess::lowerInterleavedLoad( 293 LoadInst *LI, SmallVector<Instruction *, 32> &DeadInsts) { 294 if (!LI->isSimple() || isa<ScalableVectorType>(LI->getType())) 295 return false; 296 297 // Check if all users of this load are shufflevectors. If we encounter any 298 // users that are extractelement instructions or binary operators, we save 299 // them to later check if they can be modified to extract from one of the 300 // shufflevectors instead of the load. 301 302 SmallVector<ShuffleVectorInst *, 4> Shuffles; 303 SmallVector<ExtractElementInst *, 4> Extracts; 304 // BinOpShuffles need to be handled a single time in case both operands of the 305 // binop are the same load. 306 SmallSetVector<ShuffleVectorInst *, 4> BinOpShuffles; 307 308 for (auto *User : LI->users()) { 309 auto *Extract = dyn_cast<ExtractElementInst>(User); 310 if (Extract && isa<ConstantInt>(Extract->getIndexOperand())) { 311 Extracts.push_back(Extract); 312 continue; 313 } 314 auto *BI = dyn_cast<BinaryOperator>(User); 315 if (BI && BI->hasOneUse()) { 316 if (auto *SVI = dyn_cast<ShuffleVectorInst>(*BI->user_begin())) { 317 BinOpShuffles.insert(SVI); 318 continue; 319 } 320 } 321 auto *SVI = dyn_cast<ShuffleVectorInst>(User); 322 if (!SVI || !isa<UndefValue>(SVI->getOperand(1))) 323 return false; 324 325 Shuffles.push_back(SVI); 326 } 327 328 if (Shuffles.empty() && BinOpShuffles.empty()) 329 return false; 330 331 unsigned Factor, Index; 332 333 unsigned NumLoadElements = 334 cast<FixedVectorType>(LI->getType())->getNumElements(); 335 auto *FirstSVI = Shuffles.size() > 0 ? Shuffles[0] : BinOpShuffles[0]; 336 // Check if the first shufflevector is DE-interleave shuffle. 337 if (!isDeInterleaveMask(FirstSVI->getShuffleMask(), Factor, Index, MaxFactor, 338 NumLoadElements)) 339 return false; 340 341 // Holds the corresponding index for each DE-interleave shuffle. 342 SmallVector<unsigned, 4> Indices; 343 344 Type *VecTy = FirstSVI->getType(); 345 346 // Check if other shufflevectors are also DE-interleaved of the same type 347 // and factor as the first shufflevector. 348 for (auto *Shuffle : Shuffles) { 349 if (Shuffle->getType() != VecTy) 350 return false; 351 if (!isDeInterleaveMaskOfFactor(Shuffle->getShuffleMask(), Factor, 352 Index)) 353 return false; 354 355 assert(Shuffle->getShuffleMask().size() <= NumLoadElements); 356 Indices.push_back(Index); 357 } 358 for (auto *Shuffle : BinOpShuffles) { 359 if (Shuffle->getType() != VecTy) 360 return false; 361 if (!isDeInterleaveMaskOfFactor(Shuffle->getShuffleMask(), Factor, 362 Index)) 363 return false; 364 365 assert(Shuffle->getShuffleMask().size() <= NumLoadElements); 366 367 if (cast<Instruction>(Shuffle->getOperand(0))->getOperand(0) == LI) 368 Indices.push_back(Index); 369 if (cast<Instruction>(Shuffle->getOperand(0))->getOperand(1) == LI) 370 Indices.push_back(Index); 371 } 372 373 // Try and modify users of the load that are extractelement instructions to 374 // use the shufflevector instructions instead of the load. 375 if (!tryReplaceExtracts(Extracts, Shuffles)) 376 return false; 377 378 bool BinOpShuffleChanged = 379 replaceBinOpShuffles(BinOpShuffles.getArrayRef(), Shuffles, LI); 380 381 LLVM_DEBUG(dbgs() << "IA: Found an interleaved load: " << *LI << "\n"); 382 383 // Try to create target specific intrinsics to replace the load and shuffles. 384 if (!TLI->lowerInterleavedLoad(LI, Shuffles, Indices, Factor)) { 385 // If Extracts is not empty, tryReplaceExtracts made changes earlier. 386 return !Extracts.empty() || BinOpShuffleChanged; 387 } 388 389 append_range(DeadInsts, Shuffles); 390 391 DeadInsts.push_back(LI); 392 return true; 393 } 394 395 bool InterleavedAccess::replaceBinOpShuffles( 396 ArrayRef<ShuffleVectorInst *> BinOpShuffles, 397 SmallVectorImpl<ShuffleVectorInst *> &Shuffles, LoadInst *LI) { 398 for (auto *SVI : BinOpShuffles) { 399 BinaryOperator *BI = cast<BinaryOperator>(SVI->getOperand(0)); 400 Type *BIOp0Ty = BI->getOperand(0)->getType(); 401 ArrayRef<int> Mask = SVI->getShuffleMask(); 402 assert(all_of(Mask, [&](int Idx) { 403 return Idx < (int)cast<FixedVectorType>(BIOp0Ty)->getNumElements(); 404 })); 405 406 auto *NewSVI1 = 407 new ShuffleVectorInst(BI->getOperand(0), PoisonValue::get(BIOp0Ty), 408 Mask, SVI->getName(), SVI); 409 auto *NewSVI2 = new ShuffleVectorInst( 410 BI->getOperand(1), PoisonValue::get(BI->getOperand(1)->getType()), Mask, 411 SVI->getName(), SVI); 412 BinaryOperator *NewBI = BinaryOperator::CreateWithCopiedFlags( 413 BI->getOpcode(), NewSVI1, NewSVI2, BI, BI->getName(), SVI); 414 SVI->replaceAllUsesWith(NewBI); 415 LLVM_DEBUG(dbgs() << " Replaced: " << *BI << "\n And : " << *SVI 416 << "\n With : " << *NewSVI1 << "\n And : " 417 << *NewSVI2 << "\n And : " << *NewBI << "\n"); 418 RecursivelyDeleteTriviallyDeadInstructions(SVI); 419 if (NewSVI1->getOperand(0) == LI) 420 Shuffles.push_back(NewSVI1); 421 if (NewSVI2->getOperand(0) == LI) 422 Shuffles.push_back(NewSVI2); 423 } 424 425 return !BinOpShuffles.empty(); 426 } 427 428 bool InterleavedAccess::tryReplaceExtracts( 429 ArrayRef<ExtractElementInst *> Extracts, 430 ArrayRef<ShuffleVectorInst *> Shuffles) { 431 // If there aren't any extractelement instructions to modify, there's nothing 432 // to do. 433 if (Extracts.empty()) 434 return true; 435 436 // Maps extractelement instructions to vector-index pairs. The extractlement 437 // instructions will be modified to use the new vector and index operands. 438 DenseMap<ExtractElementInst *, std::pair<Value *, int>> ReplacementMap; 439 440 for (auto *Extract : Extracts) { 441 // The vector index that is extracted. 442 auto *IndexOperand = cast<ConstantInt>(Extract->getIndexOperand()); 443 auto Index = IndexOperand->getSExtValue(); 444 445 // Look for a suitable shufflevector instruction. The goal is to modify the 446 // extractelement instruction (which uses an interleaved load) to use one 447 // of the shufflevector instructions instead of the load. 448 for (auto *Shuffle : Shuffles) { 449 // If the shufflevector instruction doesn't dominate the extract, we 450 // can't create a use of it. 451 if (!DT->dominates(Shuffle, Extract)) 452 continue; 453 454 // Inspect the indices of the shufflevector instruction. If the shuffle 455 // selects the same index that is extracted, we can modify the 456 // extractelement instruction. 457 SmallVector<int, 4> Indices; 458 Shuffle->getShuffleMask(Indices); 459 for (unsigned I = 0; I < Indices.size(); ++I) 460 if (Indices[I] == Index) { 461 assert(Extract->getOperand(0) == Shuffle->getOperand(0) && 462 "Vector operations do not match"); 463 ReplacementMap[Extract] = std::make_pair(Shuffle, I); 464 break; 465 } 466 467 // If we found a suitable shufflevector instruction, stop looking. 468 if (ReplacementMap.count(Extract)) 469 break; 470 } 471 472 // If we did not find a suitable shufflevector instruction, the 473 // extractelement instruction cannot be modified, so we must give up. 474 if (!ReplacementMap.count(Extract)) 475 return false; 476 } 477 478 // Finally, perform the replacements. 479 IRBuilder<> Builder(Extracts[0]->getContext()); 480 for (auto &Replacement : ReplacementMap) { 481 auto *Extract = Replacement.first; 482 auto *Vector = Replacement.second.first; 483 auto Index = Replacement.second.second; 484 Builder.SetInsertPoint(Extract); 485 Extract->replaceAllUsesWith(Builder.CreateExtractElement(Vector, Index)); 486 Extract->eraseFromParent(); 487 } 488 489 return true; 490 } 491 492 bool InterleavedAccess::lowerInterleavedStore( 493 StoreInst *SI, SmallVector<Instruction *, 32> &DeadInsts) { 494 if (!SI->isSimple()) 495 return false; 496 497 auto *SVI = dyn_cast<ShuffleVectorInst>(SI->getValueOperand()); 498 if (!SVI || !SVI->hasOneUse() || isa<ScalableVectorType>(SVI->getType())) 499 return false; 500 501 // Check if the shufflevector is RE-interleave shuffle. 502 unsigned Factor; 503 unsigned OpNumElts = 504 cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements(); 505 if (!isReInterleaveMask(SVI->getShuffleMask(), Factor, MaxFactor, OpNumElts)) 506 return false; 507 508 LLVM_DEBUG(dbgs() << "IA: Found an interleaved store: " << *SI << "\n"); 509 510 // Try to create target specific intrinsics to replace the store and shuffle. 511 if (!TLI->lowerInterleavedStore(SI, SVI, Factor)) 512 return false; 513 514 // Already have a new target specific interleaved store. Erase the old store. 515 DeadInsts.push_back(SI); 516 DeadInsts.push_back(SVI); 517 return true; 518 } 519 520 bool InterleavedAccess::runOnFunction(Function &F) { 521 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>(); 522 if (!TPC || !LowerInterleavedAccesses) 523 return false; 524 525 LLVM_DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName() << "\n"); 526 527 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 528 auto &TM = TPC->getTM<TargetMachine>(); 529 TLI = TM.getSubtargetImpl(F)->getTargetLowering(); 530 MaxFactor = TLI->getMaxSupportedInterleaveFactor(); 531 532 // Holds dead instructions that will be erased later. 533 SmallVector<Instruction *, 32> DeadInsts; 534 bool Changed = false; 535 536 for (auto &I : instructions(F)) { 537 if (auto *LI = dyn_cast<LoadInst>(&I)) 538 Changed |= lowerInterleavedLoad(LI, DeadInsts); 539 540 if (auto *SI = dyn_cast<StoreInst>(&I)) 541 Changed |= lowerInterleavedStore(SI, DeadInsts); 542 } 543 544 for (auto I : DeadInsts) 545 I->eraseFromParent(); 546 547 return Changed; 548 } 549