DivRemPairs.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. //===- DivRemPairs.cpp - Hoist/[dr]ecompose division and remainder --------===//
  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. //
  9. // This pass hoists and/or decomposes/recomposes integer division and remainder
  10. // instructions to enable CFG improvements and better codegen.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar/DivRemPairs.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/MapVector.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/Analysis/GlobalsModRef.h"
  18. #include "llvm/Analysis/TargetTransformInfo.h"
  19. #include "llvm/Analysis/ValueTracking.h"
  20. #include "llvm/IR/Dominators.h"
  21. #include "llvm/IR/Function.h"
  22. #include "llvm/IR/PatternMatch.h"
  23. #include "llvm/InitializePasses.h"
  24. #include "llvm/Pass.h"
  25. #include "llvm/Support/DebugCounter.h"
  26. #include "llvm/Transforms/Scalar.h"
  27. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  28. #include <optional>
  29. using namespace llvm;
  30. using namespace llvm::PatternMatch;
  31. #define DEBUG_TYPE "div-rem-pairs"
  32. STATISTIC(NumPairs, "Number of div/rem pairs");
  33. STATISTIC(NumRecomposed, "Number of instructions recomposed");
  34. STATISTIC(NumHoisted, "Number of instructions hoisted");
  35. STATISTIC(NumDecomposed, "Number of instructions decomposed");
  36. DEBUG_COUNTER(DRPCounter, "div-rem-pairs-transform",
  37. "Controls transformations in div-rem-pairs pass");
  38. namespace {
  39. struct ExpandedMatch {
  40. DivRemMapKey Key;
  41. Instruction *Value;
  42. };
  43. } // namespace
  44. /// See if we can match: (which is the form we expand into)
  45. /// X - ((X ?/ Y) * Y)
  46. /// which is equivalent to:
  47. /// X ?% Y
  48. static std::optional<ExpandedMatch> matchExpandedRem(Instruction &I) {
  49. Value *Dividend, *XroundedDownToMultipleOfY;
  50. if (!match(&I, m_Sub(m_Value(Dividend), m_Value(XroundedDownToMultipleOfY))))
  51. return std::nullopt;
  52. Value *Divisor;
  53. Instruction *Div;
  54. // Look for ((X / Y) * Y)
  55. if (!match(
  56. XroundedDownToMultipleOfY,
  57. m_c_Mul(m_CombineAnd(m_IDiv(m_Specific(Dividend), m_Value(Divisor)),
  58. m_Instruction(Div)),
  59. m_Deferred(Divisor))))
  60. return std::nullopt;
  61. ExpandedMatch M;
  62. M.Key.SignedOp = Div->getOpcode() == Instruction::SDiv;
  63. M.Key.Dividend = Dividend;
  64. M.Key.Divisor = Divisor;
  65. M.Value = &I;
  66. return M;
  67. }
  68. namespace {
  69. /// A thin wrapper to store two values that we matched as div-rem pair.
  70. /// We want this extra indirection to avoid dealing with RAUW'ing the map keys.
  71. struct DivRemPairWorklistEntry {
  72. /// The actual udiv/sdiv instruction. Source of truth.
  73. AssertingVH<Instruction> DivInst;
  74. /// The instruction that we have matched as a remainder instruction.
  75. /// Should only be used as Value, don't introspect it.
  76. AssertingVH<Instruction> RemInst;
  77. DivRemPairWorklistEntry(Instruction *DivInst_, Instruction *RemInst_)
  78. : DivInst(DivInst_), RemInst(RemInst_) {
  79. assert((DivInst->getOpcode() == Instruction::UDiv ||
  80. DivInst->getOpcode() == Instruction::SDiv) &&
  81. "Not a division.");
  82. assert(DivInst->getType() == RemInst->getType() && "Types should match.");
  83. // We can't check anything else about remainder instruction,
  84. // it's not strictly required to be a urem/srem.
  85. }
  86. /// The type for this pair, identical for both the div and rem.
  87. Type *getType() const { return DivInst->getType(); }
  88. /// Is this pair signed or unsigned?
  89. bool isSigned() const { return DivInst->getOpcode() == Instruction::SDiv; }
  90. /// In this pair, what are the divident and divisor?
  91. Value *getDividend() const { return DivInst->getOperand(0); }
  92. Value *getDivisor() const { return DivInst->getOperand(1); }
  93. bool isRemExpanded() const {
  94. switch (RemInst->getOpcode()) {
  95. case Instruction::SRem:
  96. case Instruction::URem:
  97. return false; // single 'rem' instruction - unexpanded form.
  98. default:
  99. return true; // anything else means we have remainder in expanded form.
  100. }
  101. }
  102. };
  103. } // namespace
  104. using DivRemWorklistTy = SmallVector<DivRemPairWorklistEntry, 4>;
  105. /// Find matching pairs of integer div/rem ops (they have the same numerator,
  106. /// denominator, and signedness). Place those pairs into a worklist for further
  107. /// processing. This indirection is needed because we have to use TrackingVH<>
  108. /// because we will be doing RAUW, and if one of the rem instructions we change
  109. /// happens to be an input to another div/rem in the maps, we'd have problems.
  110. static DivRemWorklistTy getWorklist(Function &F) {
  111. // Insert all divide and remainder instructions into maps keyed by their
  112. // operands and opcode (signed or unsigned).
  113. DenseMap<DivRemMapKey, Instruction *> DivMap;
  114. // Use a MapVector for RemMap so that instructions are moved/inserted in a
  115. // deterministic order.
  116. MapVector<DivRemMapKey, Instruction *> RemMap;
  117. for (auto &BB : F) {
  118. for (auto &I : BB) {
  119. if (I.getOpcode() == Instruction::SDiv)
  120. DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I;
  121. else if (I.getOpcode() == Instruction::UDiv)
  122. DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I;
  123. else if (I.getOpcode() == Instruction::SRem)
  124. RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I;
  125. else if (I.getOpcode() == Instruction::URem)
  126. RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I;
  127. else if (auto Match = matchExpandedRem(I))
  128. RemMap[Match->Key] = Match->Value;
  129. }
  130. }
  131. // We'll accumulate the matching pairs of div-rem instructions here.
  132. DivRemWorklistTy Worklist;
  133. // We can iterate over either map because we are only looking for matched
  134. // pairs. Choose remainders for efficiency because they are usually even more
  135. // rare than division.
  136. for (auto &RemPair : RemMap) {
  137. // Find the matching division instruction from the division map.
  138. auto It = DivMap.find(RemPair.first);
  139. if (It == DivMap.end())
  140. continue;
  141. // We have a matching pair of div/rem instructions.
  142. NumPairs++;
  143. Instruction *RemInst = RemPair.second;
  144. // Place it in the worklist.
  145. Worklist.emplace_back(It->second, RemInst);
  146. }
  147. return Worklist;
  148. }
  149. /// Find matching pairs of integer div/rem ops (they have the same numerator,
  150. /// denominator, and signedness). If they exist in different basic blocks, bring
  151. /// them together by hoisting or replace the common division operation that is
  152. /// implicit in the remainder:
  153. /// X % Y <--> X - ((X / Y) * Y).
  154. ///
  155. /// We can largely ignore the normal safety and cost constraints on speculation
  156. /// of these ops when we find a matching pair. This is because we are already
  157. /// guaranteed that any exceptions and most cost are already incurred by the
  158. /// first member of the pair.
  159. ///
  160. /// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or
  161. /// SimplifyCFG, but it's split off on its own because it's different enough
  162. /// that it doesn't quite match the stated objectives of those passes.
  163. static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI,
  164. const DominatorTree &DT) {
  165. bool Changed = false;
  166. // Get the matching pairs of div-rem instructions. We want this extra
  167. // indirection to avoid dealing with having to RAUW the keys of the maps.
  168. DivRemWorklistTy Worklist = getWorklist(F);
  169. // Process each entry in the worklist.
  170. for (DivRemPairWorklistEntry &E : Worklist) {
  171. if (!DebugCounter::shouldExecute(DRPCounter))
  172. continue;
  173. bool HasDivRemOp = TTI.hasDivRemOp(E.getType(), E.isSigned());
  174. auto &DivInst = E.DivInst;
  175. auto &RemInst = E.RemInst;
  176. const bool RemOriginallyWasInExpandedForm = E.isRemExpanded();
  177. (void)RemOriginallyWasInExpandedForm; // suppress unused variable warning
  178. if (HasDivRemOp && E.isRemExpanded()) {
  179. // The target supports div+rem but the rem is expanded.
  180. // We should recompose it first.
  181. Value *X = E.getDividend();
  182. Value *Y = E.getDivisor();
  183. Instruction *RealRem = E.isSigned() ? BinaryOperator::CreateSRem(X, Y)
  184. : BinaryOperator::CreateURem(X, Y);
  185. // Note that we place it right next to the original expanded instruction,
  186. // and letting further handling to move it if needed.
  187. RealRem->setName(RemInst->getName() + ".recomposed");
  188. RealRem->insertAfter(RemInst);
  189. Instruction *OrigRemInst = RemInst;
  190. // Update AssertingVH<> with new instruction so it doesn't assert.
  191. RemInst = RealRem;
  192. // And replace the original instruction with the new one.
  193. OrigRemInst->replaceAllUsesWith(RealRem);
  194. OrigRemInst->eraseFromParent();
  195. NumRecomposed++;
  196. // Note that we have left ((X / Y) * Y) around.
  197. // If it had other uses we could rewrite it as X - X % Y
  198. Changed = true;
  199. }
  200. assert((!E.isRemExpanded() || !HasDivRemOp) &&
  201. "*If* the target supports div-rem, then by now the RemInst *is* "
  202. "Instruction::[US]Rem.");
  203. // If the target supports div+rem and the instructions are in the same block
  204. // already, there's nothing to do. The backend should handle this. If the
  205. // target does not support div+rem, then we will decompose the rem.
  206. if (HasDivRemOp && RemInst->getParent() == DivInst->getParent())
  207. continue;
  208. bool DivDominates = DT.dominates(DivInst, RemInst);
  209. if (!DivDominates && !DT.dominates(RemInst, DivInst)) {
  210. // We have matching div-rem pair, but they are in two different blocks,
  211. // neither of which dominates one another.
  212. BasicBlock *PredBB = nullptr;
  213. BasicBlock *DivBB = DivInst->getParent();
  214. BasicBlock *RemBB = RemInst->getParent();
  215. // It's only safe to hoist if every instruction before the Div/Rem in the
  216. // basic block is guaranteed to transfer execution.
  217. auto IsSafeToHoist = [](Instruction *DivOrRem, BasicBlock *ParentBB) {
  218. for (auto I = ParentBB->begin(), E = DivOrRem->getIterator(); I != E;
  219. ++I)
  220. if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
  221. return false;
  222. return true;
  223. };
  224. // Look for something like this
  225. // PredBB
  226. // | \
  227. // | Rem
  228. // | /
  229. // Div
  230. //
  231. // If the Rem block has a single predecessor and successor, and all paths
  232. // from PredBB go to either RemBB or DivBB, and execution of RemBB and
  233. // DivBB will always reach the Div/Rem, we can hoist Div to PredBB. If
  234. // we have a DivRem operation we can also hoist Rem. Otherwise we'll leave
  235. // Rem where it is and rewrite it to mul/sub.
  236. if (RemBB->getSingleSuccessor() == DivBB) {
  237. PredBB = RemBB->getUniquePredecessor();
  238. // Look for something like this
  239. // PredBB
  240. // / \
  241. // Div Rem
  242. //
  243. // If the Rem and Din blocks share a unique predecessor, and all
  244. // paths from PredBB go to either RemBB or DivBB, and execution of RemBB
  245. // and DivBB will always reach the Div/Rem, we can hoist Div to PredBB.
  246. // If we have a DivRem operation we can also hoist Rem. By hoisting both
  247. // ops to the same block, we reduce code size and allow the DivRem to
  248. // issue sooner. Without a DivRem op, this transformation is
  249. // unprofitable because we would end up performing an extra Mul+Sub on
  250. // the Rem path.
  251. } else if (BasicBlock *RemPredBB = RemBB->getUniquePredecessor()) {
  252. // This hoist is only profitable when the target has a DivRem op.
  253. if (HasDivRemOp && RemPredBB == DivBB->getUniquePredecessor())
  254. PredBB = RemPredBB;
  255. }
  256. // FIXME: We could handle more hoisting cases.
  257. if (PredBB && !isa<CatchSwitchInst>(PredBB->getTerminator()) &&
  258. isGuaranteedToTransferExecutionToSuccessor(PredBB->getTerminator()) &&
  259. IsSafeToHoist(RemInst, RemBB) && IsSafeToHoist(DivInst, DivBB) &&
  260. all_of(successors(PredBB),
  261. [&](BasicBlock *BB) { return BB == DivBB || BB == RemBB; }) &&
  262. all_of(predecessors(DivBB),
  263. [&](BasicBlock *BB) { return BB == RemBB || BB == PredBB; })) {
  264. DivDominates = true;
  265. DivInst->moveBefore(PredBB->getTerminator());
  266. Changed = true;
  267. if (HasDivRemOp) {
  268. RemInst->moveBefore(PredBB->getTerminator());
  269. continue;
  270. }
  271. } else
  272. continue;
  273. }
  274. // The target does not have a single div/rem operation,
  275. // and the rem is already in expanded form. Nothing to do.
  276. if (!HasDivRemOp && E.isRemExpanded())
  277. continue;
  278. if (HasDivRemOp) {
  279. // The target has a single div/rem operation. Hoist the lower instruction
  280. // to make the matched pair visible to the backend.
  281. if (DivDominates)
  282. RemInst->moveAfter(DivInst);
  283. else
  284. DivInst->moveAfter(RemInst);
  285. NumHoisted++;
  286. } else {
  287. // The target does not have a single div/rem operation,
  288. // and the rem is *not* in a already-expanded form.
  289. // Decompose the remainder calculation as:
  290. // X % Y --> X - ((X / Y) * Y).
  291. assert(!RemOriginallyWasInExpandedForm &&
  292. "We should not be expanding if the rem was in expanded form to "
  293. "begin with.");
  294. Value *X = E.getDividend();
  295. Value *Y = E.getDivisor();
  296. Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y);
  297. Instruction *Sub = BinaryOperator::CreateSub(X, Mul);
  298. // If the remainder dominates, then hoist the division up to that block:
  299. //
  300. // bb1:
  301. // %rem = srem %x, %y
  302. // bb2:
  303. // %div = sdiv %x, %y
  304. // -->
  305. // bb1:
  306. // %div = sdiv %x, %y
  307. // %mul = mul %div, %y
  308. // %rem = sub %x, %mul
  309. //
  310. // If the division dominates, it's already in the right place. The mul+sub
  311. // will be in a different block because we don't assume that they are
  312. // cheap to speculatively execute:
  313. //
  314. // bb1:
  315. // %div = sdiv %x, %y
  316. // bb2:
  317. // %rem = srem %x, %y
  318. // -->
  319. // bb1:
  320. // %div = sdiv %x, %y
  321. // bb2:
  322. // %mul = mul %div, %y
  323. // %rem = sub %x, %mul
  324. //
  325. // If the div and rem are in the same block, we do the same transform,
  326. // but any code movement would be within the same block.
  327. if (!DivDominates)
  328. DivInst->moveBefore(RemInst);
  329. Mul->insertAfter(RemInst);
  330. Sub->insertAfter(Mul);
  331. // If X can be undef, X should be frozen first.
  332. // For example, let's assume that Y = 1 & X = undef:
  333. // %div = sdiv undef, 1 // %div = undef
  334. // %rem = srem undef, 1 // %rem = 0
  335. // =>
  336. // %div = sdiv undef, 1 // %div = undef
  337. // %mul = mul %div, 1 // %mul = undef
  338. // %rem = sub %x, %mul // %rem = undef - undef = undef
  339. // If X is not frozen, %rem becomes undef after transformation.
  340. // TODO: We need a undef-specific checking function in ValueTracking
  341. if (!isGuaranteedNotToBeUndefOrPoison(X, nullptr, DivInst, &DT)) {
  342. auto *FrX = new FreezeInst(X, X->getName() + ".frozen", DivInst);
  343. DivInst->setOperand(0, FrX);
  344. Sub->setOperand(0, FrX);
  345. }
  346. // Same for Y. If X = 1 and Y = (undef | 1), %rem in src is either 1 or 0,
  347. // but %rem in tgt can be one of many integer values.
  348. if (!isGuaranteedNotToBeUndefOrPoison(Y, nullptr, DivInst, &DT)) {
  349. auto *FrY = new FreezeInst(Y, Y->getName() + ".frozen", DivInst);
  350. DivInst->setOperand(1, FrY);
  351. Mul->setOperand(1, FrY);
  352. }
  353. // Now kill the explicit remainder. We have replaced it with:
  354. // (sub X, (mul (div X, Y), Y)
  355. Sub->setName(RemInst->getName() + ".decomposed");
  356. Instruction *OrigRemInst = RemInst;
  357. // Update AssertingVH<> with new instruction so it doesn't assert.
  358. RemInst = Sub;
  359. // And replace the original instruction with the new one.
  360. OrigRemInst->replaceAllUsesWith(Sub);
  361. OrigRemInst->eraseFromParent();
  362. NumDecomposed++;
  363. }
  364. Changed = true;
  365. }
  366. return Changed;
  367. }
  368. // Pass manager boilerplate below here.
  369. namespace {
  370. struct DivRemPairsLegacyPass : public FunctionPass {
  371. static char ID;
  372. DivRemPairsLegacyPass() : FunctionPass(ID) {
  373. initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry());
  374. }
  375. void getAnalysisUsage(AnalysisUsage &AU) const override {
  376. AU.addRequired<DominatorTreeWrapperPass>();
  377. AU.addRequired<TargetTransformInfoWrapperPass>();
  378. AU.setPreservesCFG();
  379. AU.addPreserved<DominatorTreeWrapperPass>();
  380. AU.addPreserved<GlobalsAAWrapperPass>();
  381. FunctionPass::getAnalysisUsage(AU);
  382. }
  383. bool runOnFunction(Function &F) override {
  384. if (skipFunction(F))
  385. return false;
  386. auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  387. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  388. return optimizeDivRem(F, TTI, DT);
  389. }
  390. };
  391. } // namespace
  392. char DivRemPairsLegacyPass::ID = 0;
  393. INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs",
  394. "Hoist/decompose integer division and remainder", false,
  395. false)
  396. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  397. INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs",
  398. "Hoist/decompose integer division and remainder", false,
  399. false)
  400. FunctionPass *llvm::createDivRemPairsPass() {
  401. return new DivRemPairsLegacyPass();
  402. }
  403. PreservedAnalyses DivRemPairsPass::run(Function &F,
  404. FunctionAnalysisManager &FAM) {
  405. TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
  406. DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
  407. if (!optimizeDivRem(F, TTI, DT))
  408. return PreservedAnalyses::all();
  409. // TODO: This pass just hoists/replaces math ops - all analyses are preserved?
  410. PreservedAnalyses PA;
  411. PA.preserveSet<CFGAnalyses>();
  412. return PA;
  413. }