1 //===-- HardwareLoops.cpp - Target Independent Hardware Loops --*- C++ -*-===// 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 /// \file 9 /// Insert hardware loop intrinsics into loops which are deemed profitable by 10 /// the target, by querying TargetTransformInfo. A hardware loop comprises of 11 /// two intrinsics: one, outside the loop, to set the loop iteration count and 12 /// another, in the exit block, to decrement the counter. The decremented value 13 /// can either be carried through the loop via a phi or handled in some opaque 14 /// way by the target. 15 /// 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/AssumptionCache.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 22 #include "llvm/Analysis/ScalarEvolution.h" 23 #include "llvm/Analysis/ScalarEvolutionExpander.h" 24 #include "llvm/Analysis/TargetTransformInfo.h" 25 #include "llvm/CodeGen/Passes.h" 26 #include "llvm/CodeGen/TargetPassConfig.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/IRBuilder.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/InitializePasses.h" 36 #include "llvm/Pass.h" 37 #include "llvm/PassRegistry.h" 38 #include "llvm/PassSupport.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Transforms/Scalar.h" 41 #include "llvm/Transforms/Utils.h" 42 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43 #include "llvm/Transforms/Utils/Local.h" 44 #include "llvm/Transforms/Utils/LoopUtils.h" 45 46 #define DEBUG_TYPE "hardware-loops" 47 48 #define HW_LOOPS_NAME "Hardware Loop Insertion" 49 50 using namespace llvm; 51 52 static cl::opt<bool> 53 ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false), 54 cl::desc("Force hardware loops intrinsics to be inserted")); 55 56 static cl::opt<bool> 57 ForceHardwareLoopPHI( 58 "force-hardware-loop-phi", cl::Hidden, cl::init(false), 59 cl::desc("Force hardware loop counter to be updated through a phi")); 60 61 static cl::opt<bool> 62 ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false), 63 cl::desc("Force allowance of nested hardware loops")); 64 65 static cl::opt<unsigned> 66 LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1), 67 cl::desc("Set the loop decrement value")); 68 69 static cl::opt<unsigned> 70 CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32), 71 cl::desc("Set the loop counter bitwidth")); 72 73 static cl::opt<bool> 74 ForceGuardLoopEntry( 75 "force-hardware-loop-guard", cl::Hidden, cl::init(false), 76 cl::desc("Force generation of loop guard intrinsic")); 77 78 STATISTIC(NumHWLoops, "Number of loops converted to hardware loops"); 79 80 #ifndef NDEBUG 81 static void debugHWLoopFailure(const StringRef DebugMsg, 82 Instruction *I) { 83 dbgs() << "HWLoops: " << DebugMsg; 84 if (I) 85 dbgs() << ' ' << *I; 86 else 87 dbgs() << '.'; 88 dbgs() << '\n'; 89 } 90 #endif 91 92 static OptimizationRemarkAnalysis 93 createHWLoopAnalysis(StringRef RemarkName, Loop *L, Instruction *I) { 94 Value *CodeRegion = L->getHeader(); 95 DebugLoc DL = L->getStartLoc(); 96 97 if (I) { 98 CodeRegion = I->getParent(); 99 // If there is no debug location attached to the instruction, revert back to 100 // using the loop's. 101 if (I->getDebugLoc()) 102 DL = I->getDebugLoc(); 103 } 104 105 OptimizationRemarkAnalysis R(DEBUG_TYPE, RemarkName, DL, CodeRegion); 106 R << "hardware-loop not created: "; 107 return R; 108 } 109 110 namespace { 111 112 void reportHWLoopFailure(const StringRef Msg, const StringRef ORETag, 113 OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I = nullptr) { 114 LLVM_DEBUG(debugHWLoopFailure(Msg, I)); 115 ORE->emit(createHWLoopAnalysis(ORETag, TheLoop, I) << Msg); 116 } 117 118 using TTI = TargetTransformInfo; 119 120 class HardwareLoops : public FunctionPass { 121 public: 122 static char ID; 123 124 HardwareLoops() : FunctionPass(ID) { 125 initializeHardwareLoopsPass(*PassRegistry::getPassRegistry()); 126 } 127 128 bool runOnFunction(Function &F) override; 129 130 void getAnalysisUsage(AnalysisUsage &AU) const override { 131 AU.addRequired<LoopInfoWrapperPass>(); 132 AU.addPreserved<LoopInfoWrapperPass>(); 133 AU.addRequired<DominatorTreeWrapperPass>(); 134 AU.addPreserved<DominatorTreeWrapperPass>(); 135 AU.addRequired<ScalarEvolutionWrapperPass>(); 136 AU.addRequired<AssumptionCacheTracker>(); 137 AU.addRequired<TargetTransformInfoWrapperPass>(); 138 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 139 } 140 141 // Try to convert the given Loop into a hardware loop. 142 bool TryConvertLoop(Loop *L); 143 144 // Given that the target believes the loop to be profitable, try to 145 // convert it. 146 bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo); 147 148 private: 149 ScalarEvolution *SE = nullptr; 150 LoopInfo *LI = nullptr; 151 const DataLayout *DL = nullptr; 152 OptimizationRemarkEmitter *ORE = nullptr; 153 const TargetTransformInfo *TTI = nullptr; 154 DominatorTree *DT = nullptr; 155 bool PreserveLCSSA = false; 156 AssumptionCache *AC = nullptr; 157 TargetLibraryInfo *LibInfo = nullptr; 158 Module *M = nullptr; 159 bool MadeChange = false; 160 }; 161 162 class HardwareLoop { 163 // Expand the trip count scev into a value that we can use. 164 Value *InitLoopCount(); 165 166 // Insert the set_loop_iteration intrinsic. 167 void InsertIterationSetup(Value *LoopCountInit); 168 169 // Insert the loop_decrement intrinsic. 170 void InsertLoopDec(); 171 172 // Insert the loop_decrement_reg intrinsic. 173 Instruction *InsertLoopRegDec(Value *EltsRem); 174 175 // If the target requires the counter value to be updated in the loop, 176 // insert a phi to hold the value. The intended purpose is for use by 177 // loop_decrement_reg. 178 PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem); 179 180 // Create a new cmp, that checks the returned value of loop_decrement*, 181 // and update the exit branch to use it. 182 void UpdateBranch(Value *EltsRem); 183 184 public: 185 HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE, 186 const DataLayout &DL, 187 OptimizationRemarkEmitter *ORE) : 188 SE(SE), DL(DL), ORE(ORE), L(Info.L), M(L->getHeader()->getModule()), 189 ExitCount(Info.ExitCount), 190 CountType(Info.CountType), 191 ExitBranch(Info.ExitBranch), 192 LoopDecrement(Info.LoopDecrement), 193 UsePHICounter(Info.CounterInReg), 194 UseLoopGuard(Info.PerformEntryTest) { } 195 196 void Create(); 197 198 private: 199 ScalarEvolution &SE; 200 const DataLayout &DL; 201 OptimizationRemarkEmitter *ORE = nullptr; 202 Loop *L = nullptr; 203 Module *M = nullptr; 204 const SCEV *ExitCount = nullptr; 205 Type *CountType = nullptr; 206 BranchInst *ExitBranch = nullptr; 207 Value *LoopDecrement = nullptr; 208 bool UsePHICounter = false; 209 bool UseLoopGuard = false; 210 BasicBlock *BeginBB = nullptr; 211 }; 212 } 213 214 char HardwareLoops::ID = 0; 215 216 bool HardwareLoops::runOnFunction(Function &F) { 217 if (skipFunction(F)) 218 return false; 219 220 LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n"); 221 222 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 223 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 224 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 225 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 226 DL = &F.getParent()->getDataLayout(); 227 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 228 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 229 LibInfo = TLIP ? &TLIP->getTLI(F) : nullptr; 230 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 231 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 232 M = F.getParent(); 233 234 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) { 235 Loop *L = *I; 236 if (!L->getParentLoop()) 237 TryConvertLoop(L); 238 } 239 240 return MadeChange; 241 } 242 243 // Return true if the search should stop, which will be when an inner loop is 244 // converted and the parent loop doesn't support containing a hardware loop. 245 bool HardwareLoops::TryConvertLoop(Loop *L) { 246 // Process nested loops first. 247 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) { 248 if (TryConvertLoop(*I)) { 249 reportHWLoopFailure("nested hardware-loops not supported", "HWLoopNested", 250 ORE, L); 251 return true; // Stop search. 252 } 253 } 254 255 HardwareLoopInfo HWLoopInfo(L); 256 if (!HWLoopInfo.canAnalyze(*LI)) { 257 reportHWLoopFailure("cannot analyze loop, irreducible control flow", 258 "HWLoopCannotAnalyze", ORE, L); 259 return false; 260 } 261 262 if (!ForceHardwareLoops && 263 !TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo)) { 264 reportHWLoopFailure("it's not profitable to create a hardware-loop", 265 "HWLoopNotProfitable", ORE, L); 266 return false; 267 } 268 269 // Allow overriding of the counter width and loop decrement value. 270 if (CounterBitWidth.getNumOccurrences()) 271 HWLoopInfo.CountType = 272 IntegerType::get(M->getContext(), CounterBitWidth); 273 274 if (LoopDecrement.getNumOccurrences()) 275 HWLoopInfo.LoopDecrement = 276 ConstantInt::get(HWLoopInfo.CountType, LoopDecrement); 277 278 MadeChange |= TryConvertLoop(HWLoopInfo); 279 return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop); 280 } 281 282 bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) { 283 284 Loop *L = HWLoopInfo.L; 285 LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L); 286 287 if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop, 288 ForceHardwareLoopPHI)) { 289 // TODO: there can be many reasons a loop is not considered a 290 // candidate, so we should let isHardwareLoopCandidate fill in the 291 // reason and then report a better message here. 292 reportHWLoopFailure("loop is not a candidate", "HWLoopNoCandidate", ORE, L); 293 return false; 294 } 295 296 assert( 297 (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) && 298 "Hardware Loop must have set exit info."); 299 300 BasicBlock *Preheader = L->getLoopPreheader(); 301 302 // If we don't have a preheader, then insert one. 303 if (!Preheader) 304 Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA); 305 if (!Preheader) 306 return false; 307 308 HardwareLoop HWLoop(HWLoopInfo, *SE, *DL, ORE); 309 HWLoop.Create(); 310 ++NumHWLoops; 311 return true; 312 } 313 314 void HardwareLoop::Create() { 315 LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n"); 316 317 Value *LoopCountInit = InitLoopCount(); 318 if (!LoopCountInit) { 319 reportHWLoopFailure("could not safely create a loop count expression", 320 "HWLoopNotSafe", ORE, L); 321 return; 322 } 323 324 InsertIterationSetup(LoopCountInit); 325 326 if (UsePHICounter || ForceHardwareLoopPHI) { 327 Instruction *LoopDec = InsertLoopRegDec(LoopCountInit); 328 Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec); 329 LoopDec->setOperand(0, EltsRem); 330 UpdateBranch(LoopDec); 331 } else 332 InsertLoopDec(); 333 334 // Run through the basic blocks of the loop and see if any of them have dead 335 // PHIs that can be removed. 336 for (auto I : L->blocks()) 337 DeleteDeadPHIs(I); 338 } 339 340 static bool CanGenerateTest(Loop *L, Value *Count) { 341 BasicBlock *Preheader = L->getLoopPreheader(); 342 if (!Preheader->getSinglePredecessor()) 343 return false; 344 345 BasicBlock *Pred = Preheader->getSinglePredecessor(); 346 if (!isa<BranchInst>(Pred->getTerminator())) 347 return false; 348 349 auto *BI = cast<BranchInst>(Pred->getTerminator()); 350 if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition())) 351 return false; 352 353 // Check that the icmp is checking for equality of Count and zero and that 354 // a non-zero value results in entering the loop. 355 auto ICmp = cast<ICmpInst>(BI->getCondition()); 356 LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n"); 357 if (!ICmp->isEquality()) 358 return false; 359 360 auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) { 361 if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx))) 362 return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count; 363 return false; 364 }; 365 366 if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1)) 367 return false; 368 369 unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1; 370 if (BI->getSuccessor(SuccIdx) != Preheader) 371 return false; 372 373 return true; 374 } 375 376 Value *HardwareLoop::InitLoopCount() { 377 LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n"); 378 // Can we replace a conditional branch with an intrinsic that sets the 379 // loop counter and tests that is not zero? 380 381 SCEVExpander SCEVE(SE, DL, "loopcnt"); 382 if (!ExitCount->getType()->isPointerTy() && 383 ExitCount->getType() != CountType) 384 ExitCount = SE.getZeroExtendExpr(ExitCount, CountType); 385 386 ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType)); 387 388 // If we're trying to use the 'test and set' form of the intrinsic, we need 389 // to replace a conditional branch that is controlling entry to the loop. It 390 // is likely (guaranteed?) that the preheader has an unconditional branch to 391 // the loop header, so also check if it has a single predecessor. 392 if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount, 393 SE.getZero(ExitCount->getType()))) { 394 LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n"); 395 UseLoopGuard |= ForceGuardLoopEntry; 396 } else 397 UseLoopGuard = false; 398 399 BasicBlock *BB = L->getLoopPreheader(); 400 if (UseLoopGuard && BB->getSinglePredecessor() && 401 cast<BranchInst>(BB->getTerminator())->isUnconditional()) 402 BB = BB->getSinglePredecessor(); 403 404 if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) { 405 LLVM_DEBUG(dbgs() << "- Bailing, unsafe to expand ExitCount " 406 << *ExitCount << "\n"); 407 return nullptr; 408 } 409 410 Value *Count = SCEVE.expandCodeFor(ExitCount, CountType, 411 BB->getTerminator()); 412 413 // FIXME: We've expanded Count where we hope to insert the counter setting 414 // intrinsic. But, in the case of the 'test and set' form, we may fallback to 415 // the just 'set' form and in which case the insertion block is most likely 416 // different. It means there will be instruction(s) in a block that possibly 417 // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue, 418 // but it's doesn't appear to work in all cases. 419 420 UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count); 421 BeginBB = UseLoopGuard ? BB : L->getLoopPreheader(); 422 LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n" 423 << " - Expanded Count in " << BB->getName() << "\n" 424 << " - Will insert set counter intrinsic into: " 425 << BeginBB->getName() << "\n"); 426 return Count; 427 } 428 429 void HardwareLoop::InsertIterationSetup(Value *LoopCountInit) { 430 IRBuilder<> Builder(BeginBB->getTerminator()); 431 Type *Ty = LoopCountInit->getType(); 432 Intrinsic::ID ID = UseLoopGuard ? 433 Intrinsic::test_set_loop_iterations : Intrinsic::set_loop_iterations; 434 Function *LoopIter = Intrinsic::getDeclaration(M, ID, Ty); 435 Value *SetCount = Builder.CreateCall(LoopIter, LoopCountInit); 436 437 // Use the return value of the intrinsic to control the entry of the loop. 438 if (UseLoopGuard) { 439 assert((isa<BranchInst>(BeginBB->getTerminator()) && 440 cast<BranchInst>(BeginBB->getTerminator())->isConditional()) && 441 "Expected conditional branch"); 442 auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator()); 443 LoopGuard->setCondition(SetCount); 444 if (LoopGuard->getSuccessor(0) != L->getLoopPreheader()) 445 LoopGuard->swapSuccessors(); 446 } 447 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: " 448 << *SetCount << "\n"); 449 } 450 451 void HardwareLoop::InsertLoopDec() { 452 IRBuilder<> CondBuilder(ExitBranch); 453 454 Function *DecFunc = 455 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement, 456 LoopDecrement->getType()); 457 Value *Ops[] = { LoopDecrement }; 458 Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops); 459 Value *OldCond = ExitBranch->getCondition(); 460 ExitBranch->setCondition(NewCond); 461 462 // The false branch must exit the loop. 463 if (!L->contains(ExitBranch->getSuccessor(0))) 464 ExitBranch->swapSuccessors(); 465 466 // The old condition may be dead now, and may have even created a dead PHI 467 // (the original induction variable). 468 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 469 470 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n"); 471 } 472 473 Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) { 474 IRBuilder<> CondBuilder(ExitBranch); 475 476 Function *DecFunc = 477 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg, 478 { EltsRem->getType(), EltsRem->getType(), 479 LoopDecrement->getType() 480 }); 481 Value *Ops[] = { EltsRem, LoopDecrement }; 482 Value *Call = CondBuilder.CreateCall(DecFunc, Ops); 483 484 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n"); 485 return cast<Instruction>(Call); 486 } 487 488 PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) { 489 BasicBlock *Preheader = L->getLoopPreheader(); 490 BasicBlock *Header = L->getHeader(); 491 BasicBlock *Latch = ExitBranch->getParent(); 492 IRBuilder<> Builder(Header->getFirstNonPHI()); 493 PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2); 494 Index->addIncoming(NumElts, Preheader); 495 Index->addIncoming(EltsRem, Latch); 496 LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n"); 497 return Index; 498 } 499 500 void HardwareLoop::UpdateBranch(Value *EltsRem) { 501 IRBuilder<> CondBuilder(ExitBranch); 502 Value *NewCond = 503 CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0)); 504 Value *OldCond = ExitBranch->getCondition(); 505 ExitBranch->setCondition(NewCond); 506 507 // The false branch must exit the loop. 508 if (!L->contains(ExitBranch->getSuccessor(0))) 509 ExitBranch->swapSuccessors(); 510 511 // The old condition may be dead now, and may have even created a dead PHI 512 // (the original induction variable). 513 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 514 } 515 516 INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false) 517 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 518 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 519 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 520 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 521 INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false) 522 523 FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); } 524