HardwareLoops.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. #include "llvm/Pass.h"
  18. #include "llvm/PassRegistry.h"
  19. #include "llvm/PassSupport.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/AssumptionCache.h"
  22. #include "llvm/Analysis/CFG.h"
  23. #include "llvm/Analysis/LoopInfo.h"
  24. #include "llvm/Analysis/LoopIterator.h"
  25. #include "llvm/Analysis/ScalarEvolution.h"
  26. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  27. #include "llvm/Analysis/TargetTransformInfo.h"
  28. #include "llvm/CodeGen/Passes.h"
  29. #include "llvm/CodeGen/TargetPassConfig.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/Dominators.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/IRBuilder.h"
  35. #include "llvm/IR/Instructions.h"
  36. #include "llvm/IR/IntrinsicInst.h"
  37. #include "llvm/IR/Value.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Transforms/Scalar.h"
  40. #include "llvm/Transforms/Utils.h"
  41. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  42. #include "llvm/Transforms/Utils/Local.h"
  43. #include "llvm/Transforms/Utils/LoopUtils.h"
  44. #define DEBUG_TYPE "hardware-loops"
  45. #define HW_LOOPS_NAME "Hardware Loop Insertion"
  46. using namespace llvm;
  47. static cl::opt<bool>
  48. ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
  49. cl::desc("Force hardware loops intrinsics to be inserted"));
  50. static cl::opt<bool>
  51. ForceHardwareLoopPHI(
  52. "force-hardware-loop-phi", cl::Hidden, cl::init(false),
  53. cl::desc("Force hardware loop counter to be updated through a phi"));
  54. static cl::opt<bool>
  55. ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
  56. cl::desc("Force allowance of nested hardware loops"));
  57. static cl::opt<unsigned>
  58. LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
  59. cl::desc("Set the loop decrement value"));
  60. static cl::opt<unsigned>
  61. CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
  62. cl::desc("Set the loop counter bitwidth"));
  63. STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
  64. namespace {
  65. using TTI = TargetTransformInfo;
  66. class HardwareLoops : public FunctionPass {
  67. public:
  68. static char ID;
  69. HardwareLoops() : FunctionPass(ID) {
  70. initializeHardwareLoopsPass(*PassRegistry::getPassRegistry());
  71. }
  72. bool runOnFunction(Function &F) override;
  73. void getAnalysisUsage(AnalysisUsage &AU) const override {
  74. AU.addRequired<LoopInfoWrapperPass>();
  75. AU.addPreserved<LoopInfoWrapperPass>();
  76. AU.addRequired<DominatorTreeWrapperPass>();
  77. AU.addPreserved<DominatorTreeWrapperPass>();
  78. AU.addRequired<ScalarEvolutionWrapperPass>();
  79. AU.addRequired<AssumptionCacheTracker>();
  80. AU.addRequired<TargetTransformInfoWrapperPass>();
  81. }
  82. // Try to convert the given Loop into a hardware loop.
  83. bool TryConvertLoop(Loop *L);
  84. // Given that the target believes the loop to be profitable, try to
  85. // convert it.
  86. bool TryConvertLoop(TTI::HardwareLoopInfo &HWLoopInfo);
  87. private:
  88. ScalarEvolution *SE = nullptr;
  89. LoopInfo *LI = nullptr;
  90. const DataLayout *DL = nullptr;
  91. const TargetTransformInfo *TTI = nullptr;
  92. DominatorTree *DT = nullptr;
  93. bool PreserveLCSSA = false;
  94. AssumptionCache *AC = nullptr;
  95. TargetLibraryInfo *LibInfo = nullptr;
  96. Module *M = nullptr;
  97. bool MadeChange = false;
  98. };
  99. class HardwareLoop {
  100. // Expand the trip count scev into a value that we can use.
  101. Value *InitLoopCount(BasicBlock *BB);
  102. // Insert the set_loop_iteration intrinsic.
  103. void InsertIterationSetup(Value *LoopCountInit, BasicBlock *BB);
  104. // Insert the loop_decrement intrinsic.
  105. void InsertLoopDec();
  106. // Insert the loop_decrement_reg intrinsic.
  107. Instruction *InsertLoopRegDec(Value *EltsRem);
  108. // If the target requires the counter value to be updated in the loop,
  109. // insert a phi to hold the value. The intended purpose is for use by
  110. // loop_decrement_reg.
  111. PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
  112. // Create a new cmp, that checks the returned value of loop_decrement*,
  113. // and update the exit branch to use it.
  114. void UpdateBranch(Value *EltsRem);
  115. public:
  116. HardwareLoop(TTI::HardwareLoopInfo &Info, ScalarEvolution &SE,
  117. const DataLayout &DL) :
  118. SE(SE), DL(DL), L(Info.L), M(L->getHeader()->getModule()),
  119. ExitCount(Info.ExitCount),
  120. CountType(Info.CountType),
  121. ExitBranch(Info.ExitBranch),
  122. LoopDecrement(Info.LoopDecrement),
  123. UsePHICounter(Info.CounterInReg) { }
  124. void Create();
  125. private:
  126. ScalarEvolution &SE;
  127. const DataLayout &DL;
  128. Loop *L = nullptr;
  129. Module *M = nullptr;
  130. const SCEV *ExitCount = nullptr;
  131. Type *CountType = nullptr;
  132. BranchInst *ExitBranch = nullptr;
  133. Value *LoopDecrement = nullptr;
  134. bool UsePHICounter = false;
  135. };
  136. }
  137. char HardwareLoops::ID = 0;
  138. bool HardwareLoops::runOnFunction(Function &F) {
  139. if (skipFunction(F))
  140. return false;
  141. LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
  142. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  143. SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  144. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  145. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  146. DL = &F.getParent()->getDataLayout();
  147. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  148. LibInfo = TLIP ? &TLIP->getTLI() : nullptr;
  149. PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
  150. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  151. M = F.getParent();
  152. for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
  153. Loop *L = *I;
  154. if (!L->getParentLoop())
  155. TryConvertLoop(L);
  156. }
  157. return MadeChange;
  158. }
  159. // Return true if the search should stop, which will be when an inner loop is
  160. // converted and the parent loop doesn't support containing a hardware loop.
  161. bool HardwareLoops::TryConvertLoop(Loop *L) {
  162. // Process nested loops first.
  163. for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
  164. if (TryConvertLoop(*I))
  165. return true; // Stop search.
  166. // Bail out if the loop has irreducible control flow.
  167. LoopBlocksRPO RPOT(L);
  168. RPOT.perform(LI);
  169. if (containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI))
  170. return false;
  171. TTI::HardwareLoopInfo HWLoopInfo(L);
  172. if (TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo) ||
  173. ForceHardwareLoops) {
  174. // Allow overriding of the counter width and loop decrement value.
  175. if (CounterBitWidth.getNumOccurrences())
  176. HWLoopInfo.CountType =
  177. IntegerType::get(M->getContext(), CounterBitWidth);
  178. if (LoopDecrement.getNumOccurrences())
  179. HWLoopInfo.LoopDecrement =
  180. ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
  181. MadeChange |= TryConvertLoop(HWLoopInfo);
  182. return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
  183. }
  184. return false;
  185. }
  186. bool HardwareLoops::TryConvertLoop(TTI::HardwareLoopInfo &HWLoopInfo) {
  187. Loop *L = HWLoopInfo.L;
  188. LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
  189. SmallVector<BasicBlock*, 4> ExitingBlocks;
  190. L->getExitingBlocks(ExitingBlocks);
  191. for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
  192. IE = ExitingBlocks.end(); I != IE; ++I) {
  193. BasicBlock *BB = *I;
  194. // If we pass the updated counter back through a phi, we need to know
  195. // which latch the updated value will be coming from.
  196. if (!L->isLoopLatch(BB)) {
  197. if ((ForceHardwareLoopPHI.getNumOccurrences() && ForceHardwareLoopPHI) ||
  198. HWLoopInfo.CounterInReg)
  199. continue;
  200. }
  201. const SCEV *EC = SE->getExitCount(L, BB);
  202. if (isa<SCEVCouldNotCompute>(EC))
  203. continue;
  204. if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
  205. if (ConstEC->getValue()->isZero())
  206. continue;
  207. } else if (!SE->isLoopInvariant(EC, L))
  208. continue;
  209. if (SE->getTypeSizeInBits(EC->getType()) >
  210. HWLoopInfo.CountType->getBitWidth())
  211. continue;
  212. // If this exiting block is contained in a nested loop, it is not eligible
  213. // for insertion of the branch-and-decrement since the inner loop would
  214. // end up messing up the value in the CTR.
  215. if (!HWLoopInfo.IsNestingLegal && LI->getLoopFor(BB) != L &&
  216. !ForceNestedLoop)
  217. continue;
  218. // We now have a loop-invariant count of loop iterations (which is not the
  219. // constant zero) for which we know that this loop will not exit via this
  220. // existing block.
  221. // We need to make sure that this block will run on every loop iteration.
  222. // For this to be true, we must dominate all blocks with backedges. Such
  223. // blocks are in-loop predecessors to the header block.
  224. bool NotAlways = false;
  225. for (pred_iterator PI = pred_begin(L->getHeader()),
  226. PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
  227. if (!L->contains(*PI))
  228. continue;
  229. if (!DT->dominates(*I, *PI)) {
  230. NotAlways = true;
  231. break;
  232. }
  233. }
  234. if (NotAlways)
  235. continue;
  236. // Make sure this blocks ends with a conditional branch.
  237. Instruction *TI = BB->getTerminator();
  238. if (!TI)
  239. continue;
  240. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  241. if (!BI->isConditional())
  242. continue;
  243. HWLoopInfo.ExitBranch = BI;
  244. } else
  245. continue;
  246. // Note that this block may not be the loop latch block, even if the loop
  247. // has a latch block.
  248. HWLoopInfo.ExitBlock = *I;
  249. HWLoopInfo.ExitCount = EC;
  250. break;
  251. }
  252. if (!HWLoopInfo.ExitBlock)
  253. return false;
  254. BasicBlock *Preheader = L->getLoopPreheader();
  255. // If we don't have a preheader, then insert one.
  256. if (!Preheader)
  257. Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
  258. if (!Preheader)
  259. return false;
  260. HardwareLoop HWLoop(HWLoopInfo, *SE, *DL);
  261. HWLoop.Create();
  262. ++NumHWLoops;
  263. return true;
  264. }
  265. void HardwareLoop::Create() {
  266. LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
  267. BasicBlock *BeginBB = L->getLoopPreheader();
  268. Value *LoopCountInit = InitLoopCount(BeginBB);
  269. if (!LoopCountInit)
  270. return;
  271. InsertIterationSetup(LoopCountInit, BeginBB);
  272. if (UsePHICounter || ForceHardwareLoopPHI) {
  273. Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
  274. Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec);
  275. LoopDec->setOperand(0, EltsRem);
  276. UpdateBranch(LoopDec);
  277. } else
  278. InsertLoopDec();
  279. // Run through the basic blocks of the loop and see if any of them have dead
  280. // PHIs that can be removed.
  281. for (auto I : L->blocks())
  282. DeleteDeadPHIs(I);
  283. }
  284. Value *HardwareLoop::InitLoopCount(BasicBlock *BB) {
  285. SCEVExpander SCEVE(SE, DL, "loopcnt");
  286. if (!ExitCount->getType()->isPointerTy() &&
  287. ExitCount->getType() != CountType)
  288. ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
  289. ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
  290. if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) {
  291. LLVM_DEBUG(dbgs() << "HWLoops: Bailing, unsafe to expand ExitCount "
  292. << *ExitCount << "\n");
  293. return nullptr;
  294. }
  295. Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
  296. BB->getTerminator());
  297. LLVM_DEBUG(dbgs() << "HWLoops: Loop Count: " << *Count << "\n");
  298. return Count;
  299. }
  300. void HardwareLoop::InsertIterationSetup(Value *LoopCountInit,
  301. BasicBlock *BB) {
  302. IRBuilder<> Builder(BB->getTerminator());
  303. Type *Ty = LoopCountInit->getType();
  304. Function *LoopIter =
  305. Intrinsic::getDeclaration(M, Intrinsic::set_loop_iterations, Ty);
  306. Builder.CreateCall(LoopIter, LoopCountInit);
  307. }
  308. void HardwareLoop::InsertLoopDec() {
  309. IRBuilder<> CondBuilder(ExitBranch);
  310. Function *DecFunc =
  311. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
  312. LoopDecrement->getType());
  313. Value *Ops[] = { LoopDecrement };
  314. Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
  315. Value *OldCond = ExitBranch->getCondition();
  316. ExitBranch->setCondition(NewCond);
  317. // The false branch must exit the loop.
  318. if (!L->contains(ExitBranch->getSuccessor(0)))
  319. ExitBranch->swapSuccessors();
  320. // The old condition may be dead now, and may have even created a dead PHI
  321. // (the original induction variable).
  322. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  323. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
  324. }
  325. Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
  326. IRBuilder<> CondBuilder(ExitBranch);
  327. Function *DecFunc =
  328. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
  329. { EltsRem->getType(), EltsRem->getType(),
  330. LoopDecrement->getType()
  331. });
  332. Value *Ops[] = { EltsRem, LoopDecrement };
  333. Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
  334. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
  335. return cast<Instruction>(Call);
  336. }
  337. PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
  338. BasicBlock *Preheader = L->getLoopPreheader();
  339. BasicBlock *Header = L->getHeader();
  340. BasicBlock *Latch = ExitBranch->getParent();
  341. IRBuilder<> Builder(Header->getFirstNonPHI());
  342. PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
  343. Index->addIncoming(NumElts, Preheader);
  344. Index->addIncoming(EltsRem, Latch);
  345. LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
  346. return Index;
  347. }
  348. void HardwareLoop::UpdateBranch(Value *EltsRem) {
  349. IRBuilder<> CondBuilder(ExitBranch);
  350. Value *NewCond =
  351. CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
  352. Value *OldCond = ExitBranch->getCondition();
  353. ExitBranch->setCondition(NewCond);
  354. // The false branch must exit the loop.
  355. if (!L->contains(ExitBranch->getSuccessor(0)))
  356. ExitBranch->swapSuccessors();
  357. // The old condition may be dead now, and may have even created a dead PHI
  358. // (the original induction variable).
  359. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  360. }
  361. INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  362. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  363. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  364. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  365. INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  366. FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }