HardwareLoops.cpp 16 KB

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