DivRemPairs.cpp 17 KB

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