HardwareLoops.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 (!HWLoopInfo.canAnalyze(*LI))
  166. return false;
  167. if (TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo) ||
  168. ForceHardwareLoops) {
  169. // Allow overriding of the counter width and loop decrement value.
  170. if (CounterBitWidth.getNumOccurrences())
  171. HWLoopInfo.CountType =
  172. IntegerType::get(M->getContext(), CounterBitWidth);
  173. if (LoopDecrement.getNumOccurrences())
  174. HWLoopInfo.LoopDecrement =
  175. ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
  176. MadeChange |= TryConvertLoop(HWLoopInfo);
  177. return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
  178. }
  179. return false;
  180. }
  181. bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
  182. Loop *L = HWLoopInfo.L;
  183. LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
  184. if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop,
  185. ForceHardwareLoopPHI))
  186. return false;
  187. assert(
  188. (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) &&
  189. "Hardware Loop must have set exit info.");
  190. BasicBlock *Preheader = L->getLoopPreheader();
  191. // If we don't have a preheader, then insert one.
  192. if (!Preheader)
  193. Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
  194. if (!Preheader)
  195. return false;
  196. HardwareLoop HWLoop(HWLoopInfo, *SE, *DL);
  197. HWLoop.Create();
  198. ++NumHWLoops;
  199. return true;
  200. }
  201. void HardwareLoop::Create() {
  202. LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
  203. BasicBlock *BeginBB = L->getLoopPreheader();
  204. Value *LoopCountInit = InitLoopCount(BeginBB);
  205. if (!LoopCountInit)
  206. return;
  207. InsertIterationSetup(LoopCountInit, BeginBB);
  208. if (UsePHICounter || ForceHardwareLoopPHI) {
  209. Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
  210. Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec);
  211. LoopDec->setOperand(0, EltsRem);
  212. UpdateBranch(LoopDec);
  213. } else
  214. InsertLoopDec();
  215. // Run through the basic blocks of the loop and see if any of them have dead
  216. // PHIs that can be removed.
  217. for (auto I : L->blocks())
  218. DeleteDeadPHIs(I);
  219. }
  220. Value *HardwareLoop::InitLoopCount(BasicBlock *BB) {
  221. SCEVExpander SCEVE(SE, DL, "loopcnt");
  222. if (!ExitCount->getType()->isPointerTy() &&
  223. ExitCount->getType() != CountType)
  224. ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
  225. ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
  226. if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) {
  227. LLVM_DEBUG(dbgs() << "HWLoops: Bailing, unsafe to expand ExitCount "
  228. << *ExitCount << "\n");
  229. return nullptr;
  230. }
  231. Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
  232. BB->getTerminator());
  233. LLVM_DEBUG(dbgs() << "HWLoops: Loop Count: " << *Count << "\n");
  234. return Count;
  235. }
  236. void HardwareLoop::InsertIterationSetup(Value *LoopCountInit,
  237. BasicBlock *BB) {
  238. IRBuilder<> Builder(BB->getTerminator());
  239. Type *Ty = LoopCountInit->getType();
  240. Function *LoopIter =
  241. Intrinsic::getDeclaration(M, Intrinsic::set_loop_iterations, Ty);
  242. Builder.CreateCall(LoopIter, LoopCountInit);
  243. }
  244. void HardwareLoop::InsertLoopDec() {
  245. IRBuilder<> CondBuilder(ExitBranch);
  246. Function *DecFunc =
  247. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
  248. LoopDecrement->getType());
  249. Value *Ops[] = { LoopDecrement };
  250. Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
  251. Value *OldCond = ExitBranch->getCondition();
  252. ExitBranch->setCondition(NewCond);
  253. // The false branch must exit the loop.
  254. if (!L->contains(ExitBranch->getSuccessor(0)))
  255. ExitBranch->swapSuccessors();
  256. // The old condition may be dead now, and may have even created a dead PHI
  257. // (the original induction variable).
  258. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  259. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
  260. }
  261. Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
  262. IRBuilder<> CondBuilder(ExitBranch);
  263. Function *DecFunc =
  264. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
  265. { EltsRem->getType(), EltsRem->getType(),
  266. LoopDecrement->getType()
  267. });
  268. Value *Ops[] = { EltsRem, LoopDecrement };
  269. Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
  270. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
  271. return cast<Instruction>(Call);
  272. }
  273. PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
  274. BasicBlock *Preheader = L->getLoopPreheader();
  275. BasicBlock *Header = L->getHeader();
  276. BasicBlock *Latch = ExitBranch->getParent();
  277. IRBuilder<> Builder(Header->getFirstNonPHI());
  278. PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
  279. Index->addIncoming(NumElts, Preheader);
  280. Index->addIncoming(EltsRem, Latch);
  281. LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
  282. return Index;
  283. }
  284. void HardwareLoop::UpdateBranch(Value *EltsRem) {
  285. IRBuilder<> CondBuilder(ExitBranch);
  286. Value *NewCond =
  287. CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
  288. Value *OldCond = ExitBranch->getCondition();
  289. ExitBranch->setCondition(NewCond);
  290. // The false branch must exit the loop.
  291. if (!L->contains(ExitBranch->getSuccessor(0)))
  292. ExitBranch->swapSuccessors();
  293. // The old condition may be dead now, and may have even created a dead PHI
  294. // (the original induction variable).
  295. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  296. }
  297. INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  298. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  299. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  300. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  301. INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  302. FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }