HardwareLoops.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
  62. namespace {
  63. using TTI = TargetTransformInfo;
  64. class HardwareLoops : public FunctionPass {
  65. public:
  66. static char ID;
  67. HardwareLoops() : FunctionPass(ID) {
  68. initializeHardwareLoopsPass(*PassRegistry::getPassRegistry());
  69. }
  70. bool runOnFunction(Function &F) override;
  71. void getAnalysisUsage(AnalysisUsage &AU) const override {
  72. AU.addRequired<LoopInfoWrapperPass>();
  73. AU.addPreserved<LoopInfoWrapperPass>();
  74. AU.addRequired<DominatorTreeWrapperPass>();
  75. AU.addPreserved<DominatorTreeWrapperPass>();
  76. AU.addRequired<ScalarEvolutionWrapperPass>();
  77. AU.addRequired<AssumptionCacheTracker>();
  78. AU.addRequired<TargetTransformInfoWrapperPass>();
  79. }
  80. // Try to convert the given Loop into a hardware loop.
  81. bool TryConvertLoop(Loop *L);
  82. // Given that the target believes the loop to be profitable, try to
  83. // convert it.
  84. bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo);
  85. private:
  86. ScalarEvolution *SE = nullptr;
  87. LoopInfo *LI = nullptr;
  88. const DataLayout *DL = nullptr;
  89. const TargetTransformInfo *TTI = nullptr;
  90. DominatorTree *DT = nullptr;
  91. bool PreserveLCSSA = false;
  92. AssumptionCache *AC = nullptr;
  93. TargetLibraryInfo *LibInfo = nullptr;
  94. Module *M = nullptr;
  95. bool MadeChange = false;
  96. };
  97. class HardwareLoop {
  98. // Expand the trip count scev into a value that we can use.
  99. Value *InitLoopCount(BasicBlock *BB);
  100. // Insert the set_loop_iteration intrinsic.
  101. void InsertIterationSetup(Value *LoopCountInit, BasicBlock *BB);
  102. // Insert the loop_decrement intrinsic.
  103. void InsertLoopDec();
  104. // Insert the loop_decrement_reg intrinsic.
  105. Instruction *InsertLoopRegDec(Value *EltsRem);
  106. // If the target requires the counter value to be updated in the loop,
  107. // insert a phi to hold the value. The intended purpose is for use by
  108. // loop_decrement_reg.
  109. PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
  110. // Create a new cmp, that checks the returned value of loop_decrement*,
  111. // and update the exit branch to use it.
  112. void UpdateBranch(Value *EltsRem);
  113. public:
  114. HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE,
  115. const DataLayout &DL) :
  116. SE(SE), DL(DL), L(Info.L), M(L->getHeader()->getModule()),
  117. ExitCount(Info.ExitCount),
  118. CountType(Info.CountType),
  119. ExitBranch(Info.ExitBranch),
  120. LoopDecrement(Info.LoopDecrement),
  121. UsePHICounter(Info.CounterInReg) { }
  122. void Create();
  123. private:
  124. ScalarEvolution &SE;
  125. const DataLayout &DL;
  126. Loop *L = nullptr;
  127. Module *M = nullptr;
  128. const SCEV *ExitCount = nullptr;
  129. Type *CountType = nullptr;
  130. BranchInst *ExitBranch = nullptr;
  131. Value *LoopDecrement = nullptr;
  132. bool UsePHICounter = false;
  133. };
  134. }
  135. char HardwareLoops::ID = 0;
  136. bool HardwareLoops::runOnFunction(Function &F) {
  137. if (skipFunction(F))
  138. return false;
  139. LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
  140. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  141. SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  142. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  143. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  144. DL = &F.getParent()->getDataLayout();
  145. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  146. LibInfo = TLIP ? &TLIP->getTLI() : nullptr;
  147. PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
  148. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  149. M = F.getParent();
  150. for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
  151. Loop *L = *I;
  152. if (!L->getParentLoop())
  153. TryConvertLoop(L);
  154. }
  155. return MadeChange;
  156. }
  157. // Return true if the search should stop, which will be when an inner loop is
  158. // converted and the parent loop doesn't support containing a hardware loop.
  159. bool HardwareLoops::TryConvertLoop(Loop *L) {
  160. // Process nested loops first.
  161. for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
  162. if (TryConvertLoop(*I))
  163. return true; // Stop search.
  164. HardwareLoopInfo HWLoopInfo(L);
  165. if (TTI->isHardwareLoopProfitable(L, *LI, *SE, *AC, LibInfo, HWLoopInfo) ||
  166. ForceHardwareLoops) {
  167. // Allow overriding of the counter width and loop decrement value.
  168. if (CounterBitWidth.getNumOccurrences())
  169. HWLoopInfo.CountType =
  170. IntegerType::get(M->getContext(), CounterBitWidth);
  171. if (LoopDecrement.getNumOccurrences())
  172. HWLoopInfo.LoopDecrement =
  173. ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
  174. MadeChange |= TryConvertLoop(HWLoopInfo);
  175. return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
  176. }
  177. return false;
  178. }
  179. bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
  180. Loop *L = HWLoopInfo.L;
  181. LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
  182. if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop,
  183. ForceHardwareLoopPHI))
  184. return false;
  185. assert(
  186. (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) &&
  187. "Hardware Loop must have set exit info.");
  188. BasicBlock *Preheader = L->getLoopPreheader();
  189. // If we don't have a preheader, then insert one.
  190. if (!Preheader)
  191. Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
  192. if (!Preheader)
  193. return false;
  194. HardwareLoop HWLoop(HWLoopInfo, *SE, *DL);
  195. HWLoop.Create();
  196. ++NumHWLoops;
  197. return true;
  198. }
  199. void HardwareLoop::Create() {
  200. LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
  201. BasicBlock *BeginBB = L->getLoopPreheader();
  202. Value *LoopCountInit = InitLoopCount(BeginBB);
  203. if (!LoopCountInit)
  204. return;
  205. InsertIterationSetup(LoopCountInit, BeginBB);
  206. if (UsePHICounter || ForceHardwareLoopPHI) {
  207. Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
  208. Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec);
  209. LoopDec->setOperand(0, EltsRem);
  210. UpdateBranch(LoopDec);
  211. } else
  212. InsertLoopDec();
  213. // Run through the basic blocks of the loop and see if any of them have dead
  214. // PHIs that can be removed.
  215. for (auto I : L->blocks())
  216. DeleteDeadPHIs(I);
  217. }
  218. Value *HardwareLoop::InitLoopCount(BasicBlock *BB) {
  219. SCEVExpander SCEVE(SE, DL, "loopcnt");
  220. if (!ExitCount->getType()->isPointerTy() &&
  221. ExitCount->getType() != CountType)
  222. ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
  223. ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
  224. if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) {
  225. LLVM_DEBUG(dbgs() << "HWLoops: Bailing, unsafe to expand ExitCount "
  226. << *ExitCount << "\n");
  227. return nullptr;
  228. }
  229. Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
  230. BB->getTerminator());
  231. LLVM_DEBUG(dbgs() << "HWLoops: Loop Count: " << *Count << "\n");
  232. return Count;
  233. }
  234. void HardwareLoop::InsertIterationSetup(Value *LoopCountInit,
  235. BasicBlock *BB) {
  236. IRBuilder<> Builder(BB->getTerminator());
  237. Type *Ty = LoopCountInit->getType();
  238. Function *LoopIter =
  239. Intrinsic::getDeclaration(M, Intrinsic::set_loop_iterations, Ty);
  240. Builder.CreateCall(LoopIter, LoopCountInit);
  241. }
  242. void HardwareLoop::InsertLoopDec() {
  243. IRBuilder<> CondBuilder(ExitBranch);
  244. Function *DecFunc =
  245. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
  246. LoopDecrement->getType());
  247. Value *Ops[] = { LoopDecrement };
  248. Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
  249. Value *OldCond = ExitBranch->getCondition();
  250. ExitBranch->setCondition(NewCond);
  251. // The false branch must exit the loop.
  252. if (!L->contains(ExitBranch->getSuccessor(0)))
  253. ExitBranch->swapSuccessors();
  254. // The old condition may be dead now, and may have even created a dead PHI
  255. // (the original induction variable).
  256. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  257. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
  258. }
  259. Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
  260. IRBuilder<> CondBuilder(ExitBranch);
  261. Function *DecFunc =
  262. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
  263. { EltsRem->getType(), EltsRem->getType(),
  264. LoopDecrement->getType()
  265. });
  266. Value *Ops[] = { EltsRem, LoopDecrement };
  267. Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
  268. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
  269. return cast<Instruction>(Call);
  270. }
  271. PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
  272. BasicBlock *Preheader = L->getLoopPreheader();
  273. BasicBlock *Header = L->getHeader();
  274. BasicBlock *Latch = ExitBranch->getParent();
  275. IRBuilder<> Builder(Header->getFirstNonPHI());
  276. PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
  277. Index->addIncoming(NumElts, Preheader);
  278. Index->addIncoming(EltsRem, Latch);
  279. LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
  280. return Index;
  281. }
  282. void HardwareLoop::UpdateBranch(Value *EltsRem) {
  283. IRBuilder<> CondBuilder(ExitBranch);
  284. Value *NewCond =
  285. CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
  286. Value *OldCond = ExitBranch->getCondition();
  287. ExitBranch->setCondition(NewCond);
  288. // The false branch must exit the loop.
  289. if (!L->contains(ExitBranch->getSuccessor(0)))
  290. ExitBranch->swapSuccessors();
  291. // The old condition may be dead now, and may have even created a dead PHI
  292. // (the original induction variable).
  293. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  294. }
  295. INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  296. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  297. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  298. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  299. INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  300. FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }