1 //===- MVETailPredication.cpp - MVE Tail Predication ----------------------===// 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 /// \file 10 /// Armv8.1m introduced MVE, M-Profile Vector Extension, and low-overhead 11 /// branches to help accelerate DSP applications. These two extensions, 12 /// combined with a new form of predication called tail-predication, can be used 13 /// to provide implicit vector predication within a low-overhead loop. 14 /// This is implicit because the predicate of active/inactive lanes is 15 /// calculated by hardware, and thus does not need to be explicitly passed 16 /// to vector instructions. The instructions responsible for this are the 17 /// DLSTP and WLSTP instructions, which setup a tail-predicated loop and the 18 /// the total number of data elements processed by the loop. The loop-end 19 /// LETP instruction is responsible for decrementing and setting the remaining 20 /// elements to be processed and generating the mask of active lanes. 21 /// 22 /// The HardwareLoops pass inserts intrinsics identifying loops that the 23 /// backend will attempt to convert into a low-overhead loop. The vectorizer is 24 /// responsible for generating a vectorized loop in which the lanes are 25 /// predicated upon the iteration counter. This pass looks at these predicated 26 /// vector loops, that are targets for low-overhead loops, and prepares it for 27 /// code generation. Once the vectorizer has produced a masked loop, there's a 28 /// couple of final forms: 29 /// - A tail-predicated loop, with implicit predication. 30 /// - A loop containing multiple VCPT instructions, predicating multiple VPT 31 /// blocks of instructions operating on different vector types. 32 /// 33 /// This pass: 34 /// 1) Pattern matches the scalar iteration count produced by the vectoriser. 35 /// The scalar loop iteration count represents the number of elements to be 36 /// processed. 37 /// TODO: this could be emitted using an intrinsic, similar to the hardware 38 /// loop intrinsics, so that we don't need to pattern match this here. 39 /// 2) Inserts the VCTP intrinsic to represent the effect of 40 /// tail predication. This will be picked up by the ARM Low-overhead loop 41 /// pass, which performs the final transformation to a DLSTP or WLSTP 42 /// tail-predicated loop. 43 44 #include "ARM.h" 45 #include "ARMSubtarget.h" 46 #include "llvm/Analysis/LoopInfo.h" 47 #include "llvm/Analysis/LoopPass.h" 48 #include "llvm/Analysis/ScalarEvolution.h" 49 #include "llvm/Analysis/ScalarEvolutionExpander.h" 50 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 51 #include "llvm/Analysis/TargetTransformInfo.h" 52 #include "llvm/CodeGen/TargetPassConfig.h" 53 #include "llvm/InitializePasses.h" 54 #include "llvm/IR/IRBuilder.h" 55 #include "llvm/IR/Instructions.h" 56 #include "llvm/IR/IntrinsicsARM.h" 57 #include "llvm/IR/PatternMatch.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 60 #include "llvm/Transforms/Utils/LoopUtils.h" 61 62 using namespace llvm; 63 64 #define DEBUG_TYPE "mve-tail-predication" 65 #define DESC "Transform predicated vector loops to use MVE tail predication" 66 67 cl::opt<bool> 68 DisableTailPredication("disable-mve-tail-predication", cl::Hidden, 69 cl::init(true), 70 cl::desc("Disable MVE Tail Predication")); 71 namespace { 72 73 // Bookkeeping for pattern matching the loop trip count and the number of 74 // elements processed by the loop. 75 struct TripCountPattern { 76 // An icmp instruction that calculates a predicate of active/inactive lanes 77 // used by the masked loads/stores. 78 Instruction *Predicate = nullptr; 79 80 // The add instruction that increments the IV. 81 Value *TripCount = nullptr; 82 83 // The number of elements processed by the vector loop. 84 Value *NumElements = nullptr; 85 86 // Other instructions in the icmp chain that calculate the predicate. 87 VectorType *VecTy = nullptr; 88 Instruction *Shuffle = nullptr; 89 Instruction *Induction = nullptr; 90 91 TripCountPattern(Instruction *P, Value *TC, VectorType *VT) 92 : Predicate(P), TripCount(TC), VecTy(VT){}; 93 }; 94 95 class MVETailPredication : public LoopPass { 96 SmallVector<IntrinsicInst*, 4> MaskedInsts; 97 Loop *L = nullptr; 98 LoopInfo *LI = nullptr; 99 const DataLayout *DL; 100 DominatorTree *DT = nullptr; 101 ScalarEvolution *SE = nullptr; 102 TargetTransformInfo *TTI = nullptr; 103 TargetLibraryInfo *TLI = nullptr; 104 bool ClonedVCTPInExitBlock = false; 105 106 public: 107 static char ID; 108 109 MVETailPredication() : LoopPass(ID) { } 110 111 void getAnalysisUsage(AnalysisUsage &AU) const override { 112 AU.addRequired<ScalarEvolutionWrapperPass>(); 113 AU.addRequired<LoopInfoWrapperPass>(); 114 AU.addRequired<TargetPassConfig>(); 115 AU.addRequired<TargetTransformInfoWrapperPass>(); 116 AU.addRequired<DominatorTreeWrapperPass>(); 117 AU.addRequired<TargetLibraryInfoWrapperPass>(); 118 AU.addPreserved<LoopInfoWrapperPass>(); 119 AU.setPreservesCFG(); 120 } 121 122 bool runOnLoop(Loop *L, LPPassManager&) override; 123 124 private: 125 /// Perform the relevant checks on the loop and convert if possible. 126 bool TryConvert(Value *TripCount); 127 128 /// Return whether this is a vectorized loop, that contains masked 129 /// load/stores. 130 bool IsPredicatedVectorLoop(); 131 132 /// Compute a value for the total number of elements that the predicated 133 /// loop will process if it is a runtime value. 134 bool ComputeRuntimeElements(TripCountPattern &TCP); 135 136 /// Return whether this is the icmp that generates an i1 vector, based 137 /// upon a loop counter and a limit that is defined outside the loop, 138 /// that generates the active/inactive lanes required for tail-predication. 139 bool isTailPredicate(TripCountPattern &TCP); 140 141 /// Insert the intrinsic to represent the effect of tail predication. 142 void InsertVCTPIntrinsic(TripCountPattern &TCP, 143 DenseMap<Instruction *, Instruction *> &NewPredicates); 144 145 /// Rematerialize the iteration count in exit blocks, which enables 146 /// ARMLowOverheadLoops to better optimise away loop update statements inside 147 /// hardware-loops. 148 void RematerializeIterCount(); 149 }; 150 151 } // end namespace 152 153 static bool IsDecrement(Instruction &I) { 154 auto *Call = dyn_cast<IntrinsicInst>(&I); 155 if (!Call) 156 return false; 157 158 Intrinsic::ID ID = Call->getIntrinsicID(); 159 return ID == Intrinsic::loop_decrement_reg; 160 } 161 162 static bool IsMasked(Instruction *I) { 163 auto *Call = dyn_cast<IntrinsicInst>(I); 164 if (!Call) 165 return false; 166 167 Intrinsic::ID ID = Call->getIntrinsicID(); 168 // TODO: Support gather/scatter expand/compress operations. 169 return ID == Intrinsic::masked_store || ID == Intrinsic::masked_load; 170 } 171 172 void MVETailPredication::RematerializeIterCount() { 173 SmallVector<WeakTrackingVH, 16> DeadInsts; 174 SCEVExpander Rewriter(*SE, *DL, "mvetp"); 175 ReplaceExitVal ReplaceExitValue = AlwaysRepl; 176 177 formLCSSARecursively(*L, *DT, LI, SE); 178 rewriteLoopExitValues(L, LI, TLI, SE, TTI, Rewriter, DT, ReplaceExitValue, 179 DeadInsts); 180 } 181 182 bool MVETailPredication::runOnLoop(Loop *L, LPPassManager&) { 183 if (skipLoop(L) || DisableTailPredication) 184 return false; 185 186 MaskedInsts.clear(); 187 Function &F = *L->getHeader()->getParent(); 188 auto &TPC = getAnalysis<TargetPassConfig>(); 189 auto &TM = TPC.getTM<TargetMachine>(); 190 auto *ST = &TM.getSubtarget<ARMSubtarget>(F); 191 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 192 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 193 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 194 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 195 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 196 TLI = TLIP ? &TLIP->getTLI(*L->getHeader()->getParent()) : nullptr; 197 DL = &L->getHeader()->getModule()->getDataLayout(); 198 this->L = L; 199 200 // The MVE and LOB extensions are combined to enable tail-predication, but 201 // there's nothing preventing us from generating VCTP instructions for v8.1m. 202 if (!ST->hasMVEIntegerOps() || !ST->hasV8_1MMainlineOps()) { 203 LLVM_DEBUG(dbgs() << "ARM TP: Not a v8.1m.main+mve target.\n"); 204 return false; 205 } 206 207 BasicBlock *Preheader = L->getLoopPreheader(); 208 if (!Preheader) 209 return false; 210 211 auto FindLoopIterations = [](BasicBlock *BB) -> IntrinsicInst* { 212 for (auto &I : *BB) { 213 auto *Call = dyn_cast<IntrinsicInst>(&I); 214 if (!Call) 215 continue; 216 217 Intrinsic::ID ID = Call->getIntrinsicID(); 218 if (ID == Intrinsic::set_loop_iterations || 219 ID == Intrinsic::test_set_loop_iterations) 220 return cast<IntrinsicInst>(&I); 221 } 222 return nullptr; 223 }; 224 225 // Look for the hardware loop intrinsic that sets the iteration count. 226 IntrinsicInst *Setup = FindLoopIterations(Preheader); 227 228 // The test.set iteration could live in the pre-preheader. 229 if (!Setup) { 230 if (!Preheader->getSinglePredecessor()) 231 return false; 232 Setup = FindLoopIterations(Preheader->getSinglePredecessor()); 233 if (!Setup) 234 return false; 235 } 236 237 // Search for the hardware loop intrinic that decrements the loop counter. 238 IntrinsicInst *Decrement = nullptr; 239 for (auto *BB : L->getBlocks()) { 240 for (auto &I : *BB) { 241 if (IsDecrement(I)) { 242 Decrement = cast<IntrinsicInst>(&I); 243 break; 244 } 245 } 246 } 247 248 if (!Decrement) 249 return false; 250 251 ClonedVCTPInExitBlock = false; 252 LLVM_DEBUG(dbgs() << "ARM TP: Running on Loop: " << *L << *Setup << "\n" 253 << *Decrement << "\n"); 254 255 if (TryConvert(Setup->getArgOperand(0))) { 256 if (ClonedVCTPInExitBlock) 257 RematerializeIterCount(); 258 return true; 259 } 260 261 LLVM_DEBUG(dbgs() << "ARM TP: Can't tail-predicate this loop.\n"); 262 return false; 263 } 264 265 // Pattern match predicates/masks and determine if they use the loop induction 266 // variable to control the number of elements processed by the loop. If so, 267 // the loop is a candidate for tail-predication. 268 bool MVETailPredication::isTailPredicate(TripCountPattern &TCP) { 269 using namespace PatternMatch; 270 271 // Pattern match the loop body and find the add with takes the index iv 272 // and adds a constant vector to it: 273 // 274 // vector.body: 275 // .. 276 // %index = phi i32 277 // %broadcast.splatinsert = insertelement <4 x i32> undef, i32 %index, i32 0 278 // %broadcast.splat = shufflevector <4 x i32> %broadcast.splatinsert, 279 // <4 x i32> undef, 280 // <4 x i32> zeroinitializer 281 // %induction = [add|or] <4 x i32> %broadcast.splat, <i32 0, i32 1, i32 2, i32 3> 282 // %pred = icmp ule <4 x i32> %induction, %broadcast.splat11 283 // 284 // Please note that the 'or' is equivalent to the 'and' here, this relies on 285 // BroadcastSplat being the IV which we know is a phi with 0 start and Lanes 286 // increment, which is all being checked below. 287 Instruction *BroadcastSplat = nullptr; 288 Constant *Const = nullptr; 289 if (!match(TCP.Induction, 290 m_Add(m_Instruction(BroadcastSplat), m_Constant(Const))) && 291 !match(TCP.Induction, 292 m_Or(m_Instruction(BroadcastSplat), m_Constant(Const)))) 293 return false; 294 295 // Check that we're adding <0, 1, 2, 3... 296 if (auto *CDS = dyn_cast<ConstantDataSequential>(Const)) { 297 for (unsigned i = 0; i < CDS->getNumElements(); ++i) { 298 if (CDS->getElementAsInteger(i) != i) 299 return false; 300 } 301 } else 302 return false; 303 304 Instruction *Insert = nullptr; 305 // The shuffle which broadcasts the index iv into a vector. 306 if (!match(BroadcastSplat, 307 m_ShuffleVector(m_Instruction(Insert), m_Undef(), m_ZeroMask()))) 308 return false; 309 310 // The insert element which initialises a vector with the index iv. 311 Instruction *IV = nullptr; 312 if (!match(Insert, m_InsertElement(m_Undef(), m_Instruction(IV), m_Zero()))) 313 return false; 314 315 // The index iv. 316 auto *Phi = dyn_cast<PHINode>(IV); 317 if (!Phi) 318 return false; 319 320 // TODO: Don't think we need to check the entry value. 321 Value *OnEntry = Phi->getIncomingValueForBlock(L->getLoopPreheader()); 322 if (!match(OnEntry, m_Zero())) 323 return false; 324 325 Value *InLoop = Phi->getIncomingValueForBlock(L->getLoopLatch()); 326 unsigned Lanes = cast<VectorType>(Insert->getType())->getNumElements(); 327 328 Instruction *LHS = nullptr; 329 if (!match(InLoop, m_Add(m_Instruction(LHS), m_SpecificInt(Lanes)))) 330 return false; 331 332 return LHS == Phi; 333 } 334 335 static VectorType *getVectorType(IntrinsicInst *I) { 336 unsigned TypeOp = I->getIntrinsicID() == Intrinsic::masked_load ? 0 : 1; 337 auto *PtrTy = cast<PointerType>(I->getOperand(TypeOp)->getType()); 338 return cast<VectorType>(PtrTy->getElementType()); 339 } 340 341 bool MVETailPredication::IsPredicatedVectorLoop() { 342 // Check that the loop contains at least one masked load/store intrinsic. 343 // We only support 'normal' vector instructions - other than masked 344 // load/stores. 345 for (auto *BB : L->getBlocks()) { 346 for (auto &I : *BB) { 347 if (IsMasked(&I)) { 348 VectorType *VecTy = getVectorType(cast<IntrinsicInst>(&I)); 349 unsigned Lanes = VecTy->getNumElements(); 350 unsigned ElementWidth = VecTy->getScalarSizeInBits(); 351 // MVE vectors are 128-bit, but don't support 128 x i1. 352 // TODO: Can we support vectors larger than 128-bits? 353 unsigned MaxWidth = TTI->getRegisterBitWidth(true); 354 if (Lanes * ElementWidth > MaxWidth || Lanes == MaxWidth) 355 return false; 356 MaskedInsts.push_back(cast<IntrinsicInst>(&I)); 357 } else if (auto *Int = dyn_cast<IntrinsicInst>(&I)) { 358 for (auto &U : Int->args()) { 359 if (isa<VectorType>(U->getType())) 360 return false; 361 } 362 } 363 } 364 } 365 366 return !MaskedInsts.empty(); 367 } 368 369 // Pattern match the predicate, which is an icmp with a constant vector of this 370 // form: 371 // 372 // icmp ult <4 x i32> %induction, <i32 32002, i32 32002, i32 32002, i32 32002> 373 // 374 // and return the constant, i.e. 32002 in this example. This is assumed to be 375 // the scalar loop iteration count: the number of loop elements by the 376 // the vector loop. Further checks are performed in function isTailPredicate(), 377 // to verify 'induction' behaves as an induction variable. 378 // 379 static bool ComputeConstElements(TripCountPattern &TCP) { 380 if (!dyn_cast<ConstantInt>(TCP.TripCount)) 381 return false; 382 383 ConstantInt *VF = ConstantInt::get( 384 cast<IntegerType>(TCP.TripCount->getType()), TCP.VecTy->getNumElements()); 385 using namespace PatternMatch; 386 CmpInst::Predicate CC; 387 388 if (!match(TCP.Predicate, m_ICmp(CC, m_Instruction(TCP.Induction), 389 m_AnyIntegralConstant())) || 390 CC != ICmpInst::ICMP_ULT) 391 return false; 392 393 LLVM_DEBUG(dbgs() << "ARM TP: icmp with constants: "; TCP.Predicate->dump();); 394 Value *ConstVec = TCP.Predicate->getOperand(1); 395 396 auto *CDS = dyn_cast<ConstantDataSequential>(ConstVec); 397 if (!CDS || CDS->getNumElements() != VF->getSExtValue()) 398 return false; 399 400 if ((TCP.NumElements = CDS->getSplatValue())) { 401 assert(dyn_cast<ConstantInt>(TCP.NumElements)->getSExtValue() % 402 VF->getSExtValue() != 403 0 && 404 "tail-predication: trip count should not be a multiple of the VF"); 405 LLVM_DEBUG(dbgs() << "ARM TP: Found const elem count: " << *TCP.NumElements 406 << "\n"); 407 return true; 408 } 409 return false; 410 } 411 412 // Pattern match the loop iteration count setup: 413 // 414 // %trip.count.minus.1 = add i32 %N, -1 415 // %broadcast.splatinsert10 = insertelement <4 x i32> undef, 416 // i32 %trip.count.minus.1, i32 0 417 // %broadcast.splat11 = shufflevector <4 x i32> %broadcast.splatinsert10, 418 // <4 x i32> undef, 419 // <4 x i32> zeroinitializer 420 // .. 421 // vector.body: 422 // .. 423 // 424 static bool MatchElemCountLoopSetup(Loop *L, Instruction *Shuffle, 425 Value *NumElements) { 426 using namespace PatternMatch; 427 Instruction *Insert = nullptr; 428 429 if (!match(Shuffle, 430 m_ShuffleVector(m_Instruction(Insert), m_Undef(), m_ZeroMask()))) 431 return false; 432 433 // Insert the limit into a vector. 434 Instruction *BECount = nullptr; 435 if (!match(Insert, 436 m_InsertElement(m_Undef(), m_Instruction(BECount), m_Zero()))) 437 return false; 438 439 // The limit calculation, backedge count. 440 Value *TripCount = nullptr; 441 if (!match(BECount, m_Add(m_Value(TripCount), m_AllOnes()))) 442 return false; 443 444 if (TripCount != NumElements || !L->isLoopInvariant(BECount)) 445 return false; 446 447 return true; 448 } 449 450 bool MVETailPredication::ComputeRuntimeElements(TripCountPattern &TCP) { 451 using namespace PatternMatch; 452 const SCEV *TripCountSE = SE->getSCEV(TCP.TripCount); 453 ConstantInt *VF = ConstantInt::get( 454 cast<IntegerType>(TCP.TripCount->getType()), TCP.VecTy->getNumElements()); 455 456 if (VF->equalsInt(1)) 457 return false; 458 459 CmpInst::Predicate Pred; 460 if (!match(TCP.Predicate, m_ICmp(Pred, m_Instruction(TCP.Induction), 461 m_Instruction(TCP.Shuffle))) || 462 Pred != ICmpInst::ICMP_ULE) 463 return false; 464 465 LLVM_DEBUG(dbgs() << "Computing number of elements for vector trip count: "; 466 TCP.TripCount->dump()); 467 468 // Otherwise, continue and try to pattern match the vector iteration 469 // count expression 470 auto VisitAdd = [&](const SCEVAddExpr *S) -> const SCEVMulExpr * { 471 if (auto *Const = dyn_cast<SCEVConstant>(S->getOperand(0))) { 472 if (Const->getAPInt() != -VF->getValue()) 473 return nullptr; 474 } else 475 return nullptr; 476 return dyn_cast<SCEVMulExpr>(S->getOperand(1)); 477 }; 478 479 auto VisitMul = [&](const SCEVMulExpr *S) -> const SCEVUDivExpr * { 480 if (auto *Const = dyn_cast<SCEVConstant>(S->getOperand(0))) { 481 if (Const->getValue() != VF) 482 return nullptr; 483 } else 484 return nullptr; 485 return dyn_cast<SCEVUDivExpr>(S->getOperand(1)); 486 }; 487 488 auto VisitDiv = [&](const SCEVUDivExpr *S) -> const SCEV * { 489 if (auto *Const = dyn_cast<SCEVConstant>(S->getRHS())) { 490 if (Const->getValue() != VF) 491 return nullptr; 492 } else 493 return nullptr; 494 495 if (auto *RoundUp = dyn_cast<SCEVAddExpr>(S->getLHS())) { 496 if (auto *Const = dyn_cast<SCEVConstant>(RoundUp->getOperand(0))) { 497 if (Const->getAPInt() != (VF->getValue() - 1)) 498 return nullptr; 499 } else 500 return nullptr; 501 502 return RoundUp->getOperand(1); 503 } 504 return nullptr; 505 }; 506 507 // TODO: Can we use SCEV helpers, such as findArrayDimensions, and friends to 508 // determine the numbers of elements instead? Looks like this is what is used 509 // for delinearization, but I'm not sure if it can be applied to the 510 // vectorized form - at least not without a bit more work than I feel 511 // comfortable with. 512 513 // Search for Elems in the following SCEV: 514 // (1 + ((-VF + (VF * (((VF - 1) + %Elems) /u VF))<nuw>) /u VF))<nuw><nsw> 515 const SCEV *Elems = nullptr; 516 if (auto *TC = dyn_cast<SCEVAddExpr>(TripCountSE)) 517 if (auto *Div = dyn_cast<SCEVUDivExpr>(TC->getOperand(1))) 518 if (auto *Add = dyn_cast<SCEVAddExpr>(Div->getLHS())) 519 if (auto *Mul = VisitAdd(Add)) 520 if (auto *Div = VisitMul(Mul)) 521 if (auto *Res = VisitDiv(Div)) 522 Elems = Res; 523 524 if (!Elems) 525 return false; 526 527 Instruction *InsertPt = L->getLoopPreheader()->getTerminator(); 528 if (!isSafeToExpandAt(Elems, InsertPt, *SE)) 529 return false; 530 531 auto DL = L->getHeader()->getModule()->getDataLayout(); 532 SCEVExpander Expander(*SE, DL, "elements"); 533 TCP.NumElements = Expander.expandCodeFor(Elems, Elems->getType(), InsertPt); 534 535 if (!MatchElemCountLoopSetup(L, TCP.Shuffle, TCP.NumElements)) 536 return false; 537 538 return true; 539 } 540 541 // Look through the exit block to see whether there's a duplicate predicate 542 // instruction. This can happen when we need to perform a select on values 543 // from the last and previous iteration. Instead of doing a straight 544 // replacement of that predicate with the vctp, clone the vctp and place it 545 // in the block. This means that the VPR doesn't have to be live into the 546 // exit block which should make it easier to convert this loop into a proper 547 // tail predicated loop. 548 static bool Cleanup(DenseMap<Instruction*, Instruction*> &NewPredicates, 549 SetVector<Instruction*> &MaybeDead, Loop *L) { 550 BasicBlock *Exit = L->getUniqueExitBlock(); 551 if (!Exit) { 552 LLVM_DEBUG(dbgs() << "ARM TP: can't find loop exit block\n"); 553 return false; 554 } 555 556 bool ClonedVCTPInExitBlock = false; 557 558 for (auto &Pair : NewPredicates) { 559 Instruction *OldPred = Pair.first; 560 Instruction *NewPred = Pair.second; 561 562 for (auto &I : *Exit) { 563 if (I.isSameOperationAs(OldPred)) { 564 Instruction *PredClone = NewPred->clone(); 565 PredClone->insertBefore(&I); 566 I.replaceAllUsesWith(PredClone); 567 MaybeDead.insert(&I); 568 ClonedVCTPInExitBlock = true; 569 LLVM_DEBUG(dbgs() << "ARM TP: replacing: "; I.dump(); 570 dbgs() << "ARM TP: with: "; PredClone->dump()); 571 break; 572 } 573 } 574 } 575 576 // Drop references and add operands to check for dead. 577 SmallPtrSet<Instruction*, 4> Dead; 578 while (!MaybeDead.empty()) { 579 auto *I = MaybeDead.front(); 580 MaybeDead.remove(I); 581 if (I->hasNUsesOrMore(1)) 582 continue; 583 584 for (auto &U : I->operands()) 585 if (auto *OpI = dyn_cast<Instruction>(U)) 586 MaybeDead.insert(OpI); 587 588 I->dropAllReferences(); 589 Dead.insert(I); 590 } 591 592 for (auto *I : Dead) { 593 LLVM_DEBUG(dbgs() << "ARM TP: removing dead insn: "; I->dump()); 594 I->eraseFromParent(); 595 } 596 597 for (auto I : L->blocks()) 598 DeleteDeadPHIs(I); 599 600 return ClonedVCTPInExitBlock; 601 } 602 603 void MVETailPredication::InsertVCTPIntrinsic(TripCountPattern &TCP, 604 DenseMap<Instruction*, Instruction*> &NewPredicates) { 605 IRBuilder<> Builder(L->getHeader()->getFirstNonPHI()); 606 Module *M = L->getHeader()->getModule(); 607 Type *Ty = IntegerType::get(M->getContext(), 32); 608 609 // Insert a phi to count the number of elements processed by the loop. 610 PHINode *Processed = Builder.CreatePHI(Ty, 2); 611 Processed->addIncoming(TCP.NumElements, L->getLoopPreheader()); 612 613 // Insert the intrinsic to represent the effect of tail predication. 614 Builder.SetInsertPoint(cast<Instruction>(TCP.Predicate)); 615 ConstantInt *Factor = 616 ConstantInt::get(cast<IntegerType>(Ty), TCP.VecTy->getNumElements()); 617 618 Intrinsic::ID VCTPID; 619 switch (TCP.VecTy->getNumElements()) { 620 default: 621 llvm_unreachable("unexpected number of lanes"); 622 case 4: VCTPID = Intrinsic::arm_mve_vctp32; break; 623 case 8: VCTPID = Intrinsic::arm_mve_vctp16; break; 624 case 16: VCTPID = Intrinsic::arm_mve_vctp8; break; 625 626 // FIXME: vctp64 currently not supported because the predicate 627 // vector wants to be <2 x i1>, but v2i1 is not a legal MVE 628 // type, so problems happen at isel time. 629 // Intrinsic::arm_mve_vctp64 exists for ACLE intrinsics 630 // purposes, but takes a v4i1 instead of a v2i1. 631 } 632 Function *VCTP = Intrinsic::getDeclaration(M, VCTPID); 633 Value *TailPredicate = Builder.CreateCall(VCTP, Processed); 634 TCP.Predicate->replaceAllUsesWith(TailPredicate); 635 NewPredicates[TCP.Predicate] = cast<Instruction>(TailPredicate); 636 637 // Add the incoming value to the new phi. 638 // TODO: This add likely already exists in the loop. 639 Value *Remaining = Builder.CreateSub(Processed, Factor); 640 Processed->addIncoming(Remaining, L->getLoopLatch()); 641 LLVM_DEBUG(dbgs() << "ARM TP: Insert processed elements phi: " 642 << *Processed << "\n" 643 << "ARM TP: Inserted VCTP: " << *TailPredicate << "\n"); 644 } 645 646 bool MVETailPredication::TryConvert(Value *TripCount) { 647 if (!IsPredicatedVectorLoop()) { 648 LLVM_DEBUG(dbgs() << "ARM TP: no masked instructions in loop.\n"); 649 return false; 650 } 651 652 LLVM_DEBUG(dbgs() << "ARM TP: Found predicated vector loop.\n"); 653 654 // Walk through the masked intrinsics and try to find whether the predicate 655 // operand is generated from an induction variable. 656 SetVector<Instruction*> Predicates; 657 DenseMap<Instruction*, Instruction*> NewPredicates; 658 659 #ifndef NDEBUG 660 // For debugging purposes, use this to indicate we have been able to 661 // pattern match the scalar loop trip count. 662 bool FoundScalarTC = false; 663 #endif 664 665 for (auto *I : MaskedInsts) { 666 Intrinsic::ID ID = I->getIntrinsicID(); 667 // First, find the icmp used by this masked load/store. 668 unsigned PredOp = ID == Intrinsic::masked_load ? 2 : 3; 669 auto *Predicate = dyn_cast<Instruction>(I->getArgOperand(PredOp)); 670 if (!Predicate || Predicates.count(Predicate)) 671 continue; 672 673 // Step 1: using this icmp, now calculate the number of elements 674 // processed by this loop. 675 TripCountPattern TCP(Predicate, TripCount, getVectorType(I)); 676 if (!(ComputeConstElements(TCP) || ComputeRuntimeElements(TCP))) 677 continue; 678 679 LLVM_DEBUG(FoundScalarTC = true); 680 681 if (!isTailPredicate(TCP)) { 682 LLVM_DEBUG(dbgs() << "ARM TP: Not an icmp that generates tail predicate: " 683 << *Predicate << "\n"); 684 continue; 685 } 686 687 LLVM_DEBUG(dbgs() << "ARM TP: Found icmp generating tail predicate: " 688 << *Predicate << "\n"); 689 Predicates.insert(Predicate); 690 691 // Step 2: emit the VCTP intrinsic representing the effect of TP. 692 InsertVCTPIntrinsic(TCP, NewPredicates); 693 } 694 695 if (!NewPredicates.size()) { 696 LLVM_DEBUG(if (!FoundScalarTC) 697 dbgs() << "ARM TP: Can't determine loop itertion count\n"); 698 return false; 699 } 700 701 // Now clean up. 702 ClonedVCTPInExitBlock = Cleanup(NewPredicates, Predicates, L); 703 return true; 704 } 705 706 Pass *llvm::createMVETailPredicationPass() { 707 return new MVETailPredication(); 708 } 709 710 char MVETailPredication::ID = 0; 711 712 INITIALIZE_PASS_BEGIN(MVETailPredication, DEBUG_TYPE, DESC, false, false) 713 INITIALIZE_PASS_END(MVETailPredication, DEBUG_TYPE, DESC, false, false) 714