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