IntegerDivision.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. //===-- IntegerDivision.cpp - Expand integer division ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains an implementation of 32bit and 64bit scalar integer
  11. // division for targets that don't have native support. It's largely derived
  12. // from compiler-rt's implementations of __udivsi3 and __udivmoddi4,
  13. // but hand-tuned for targets that prefer less control flow.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Transforms/Utils/IntegerDivision.h"
  17. #include "llvm/IR/Function.h"
  18. #include "llvm/IR/IRBuilder.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/Intrinsics.h"
  21. #include <utility>
  22. using namespace llvm;
  23. #define DEBUG_TYPE "integer-division"
  24. /// Generate code to compute the remainder of two signed integers. Returns the
  25. /// remainder, which will have the sign of the dividend. Builder's insert point
  26. /// should be pointing where the caller wants code generated, e.g. at the srem
  27. /// instruction. This will generate a urem in the process, and Builder's insert
  28. /// point will be pointing at the uren (if present, i.e. not folded), ready to
  29. /// be expanded if the user wishes
  30. static Value *generateSignedRemainderCode(Value *Dividend, Value *Divisor,
  31. IRBuilder<> &Builder) {
  32. unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();
  33. ConstantInt *Shift;
  34. if (BitWidth == 64) {
  35. Shift = Builder.getInt64(63);
  36. } else {
  37. assert(BitWidth == 32 && "Unexpected bit width");
  38. Shift = Builder.getInt32(31);
  39. }
  40. // Following instructions are generated for both i32 (shift 31) and
  41. // i64 (shift 63).
  42. // ; %dividend_sgn = ashr i32 %dividend, 31
  43. // ; %divisor_sgn = ashr i32 %divisor, 31
  44. // ; %dvd_xor = xor i32 %dividend, %dividend_sgn
  45. // ; %dvs_xor = xor i32 %divisor, %divisor_sgn
  46. // ; %u_dividend = sub i32 %dvd_xor, %dividend_sgn
  47. // ; %u_divisor = sub i32 %dvs_xor, %divisor_sgn
  48. // ; %urem = urem i32 %dividend, %divisor
  49. // ; %xored = xor i32 %urem, %dividend_sgn
  50. // ; %srem = sub i32 %xored, %dividend_sgn
  51. Value *DividendSign = Builder.CreateAShr(Dividend, Shift);
  52. Value *DivisorSign = Builder.CreateAShr(Divisor, Shift);
  53. Value *DvdXor = Builder.CreateXor(Dividend, DividendSign);
  54. Value *DvsXor = Builder.CreateXor(Divisor, DivisorSign);
  55. Value *UDividend = Builder.CreateSub(DvdXor, DividendSign);
  56. Value *UDivisor = Builder.CreateSub(DvsXor, DivisorSign);
  57. Value *URem = Builder.CreateURem(UDividend, UDivisor);
  58. Value *Xored = Builder.CreateXor(URem, DividendSign);
  59. Value *SRem = Builder.CreateSub(Xored, DividendSign);
  60. if (Instruction *URemInst = dyn_cast<Instruction>(URem))
  61. Builder.SetInsertPoint(URemInst);
  62. return SRem;
  63. }
  64. /// Generate code to compute the remainder of two unsigned integers. Returns the
  65. /// remainder. Builder's insert point should be pointing where the caller wants
  66. /// code generated, e.g. at the urem instruction. This will generate a udiv in
  67. /// the process, and Builder's insert point will be pointing at the udiv (if
  68. /// present, i.e. not folded), ready to be expanded if the user wishes
  69. static Value *generatedUnsignedRemainderCode(Value *Dividend, Value *Divisor,
  70. IRBuilder<> &Builder) {
  71. // Remainder = Dividend - Quotient*Divisor
  72. // Following instructions are generated for both i32 and i64
  73. // ; %quotient = udiv i32 %dividend, %divisor
  74. // ; %product = mul i32 %divisor, %quotient
  75. // ; %remainder = sub i32 %dividend, %product
  76. Value *Quotient = Builder.CreateUDiv(Dividend, Divisor);
  77. Value *Product = Builder.CreateMul(Divisor, Quotient);
  78. Value *Remainder = Builder.CreateSub(Dividend, Product);
  79. if (Instruction *UDiv = dyn_cast<Instruction>(Quotient))
  80. Builder.SetInsertPoint(UDiv);
  81. return Remainder;
  82. }
  83. /// Generate code to divide two signed integers. Returns the quotient, rounded
  84. /// towards 0. Builder's insert point should be pointing where the caller wants
  85. /// code generated, e.g. at the sdiv instruction. This will generate a udiv in
  86. /// the process, and Builder's insert point will be pointing at the udiv (if
  87. /// present, i.e. not folded), ready to be expanded if the user wishes.
  88. static Value *generateSignedDivisionCode(Value *Dividend, Value *Divisor,
  89. IRBuilder<> &Builder) {
  90. // Implementation taken from compiler-rt's __divsi3 and __divdi3
  91. unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();
  92. ConstantInt *Shift;
  93. if (BitWidth == 64) {
  94. Shift = Builder.getInt64(63);
  95. } else {
  96. assert(BitWidth == 32 && "Unexpected bit width");
  97. Shift = Builder.getInt32(31);
  98. }
  99. // Following instructions are generated for both i32 (shift 31) and
  100. // i64 (shift 63).
  101. // ; %tmp = ashr i32 %dividend, 31
  102. // ; %tmp1 = ashr i32 %divisor, 31
  103. // ; %tmp2 = xor i32 %tmp, %dividend
  104. // ; %u_dvnd = sub nsw i32 %tmp2, %tmp
  105. // ; %tmp3 = xor i32 %tmp1, %divisor
  106. // ; %u_dvsr = sub nsw i32 %tmp3, %tmp1
  107. // ; %q_sgn = xor i32 %tmp1, %tmp
  108. // ; %q_mag = udiv i32 %u_dvnd, %u_dvsr
  109. // ; %tmp4 = xor i32 %q_mag, %q_sgn
  110. // ; %q = sub i32 %tmp4, %q_sgn
  111. Value *Tmp = Builder.CreateAShr(Dividend, Shift);
  112. Value *Tmp1 = Builder.CreateAShr(Divisor, Shift);
  113. Value *Tmp2 = Builder.CreateXor(Tmp, Dividend);
  114. Value *U_Dvnd = Builder.CreateSub(Tmp2, Tmp);
  115. Value *Tmp3 = Builder.CreateXor(Tmp1, Divisor);
  116. Value *U_Dvsr = Builder.CreateSub(Tmp3, Tmp1);
  117. Value *Q_Sgn = Builder.CreateXor(Tmp1, Tmp);
  118. Value *Q_Mag = Builder.CreateUDiv(U_Dvnd, U_Dvsr);
  119. Value *Tmp4 = Builder.CreateXor(Q_Mag, Q_Sgn);
  120. Value *Q = Builder.CreateSub(Tmp4, Q_Sgn);
  121. if (Instruction *UDiv = dyn_cast<Instruction>(Q_Mag))
  122. Builder.SetInsertPoint(UDiv);
  123. return Q;
  124. }
  125. /// Generates code to divide two unsigned scalar 32-bit or 64-bit integers.
  126. /// Returns the quotient, rounded towards 0. Builder's insert point should
  127. /// point where the caller wants code generated, e.g. at the udiv instruction.
  128. static Value *generateUnsignedDivisionCode(Value *Dividend, Value *Divisor,
  129. IRBuilder<> &Builder) {
  130. // The basic algorithm can be found in the compiler-rt project's
  131. // implementation of __udivsi3.c. Here, we do a lower-level IR based approach
  132. // that's been hand-tuned to lessen the amount of control flow involved.
  133. // Some helper values
  134. IntegerType *DivTy = cast<IntegerType>(Dividend->getType());
  135. unsigned BitWidth = DivTy->getBitWidth();
  136. ConstantInt *Zero;
  137. ConstantInt *One;
  138. ConstantInt *NegOne;
  139. ConstantInt *MSB;
  140. if (BitWidth == 64) {
  141. Zero = Builder.getInt64(0);
  142. One = Builder.getInt64(1);
  143. NegOne = ConstantInt::getSigned(DivTy, -1);
  144. MSB = Builder.getInt64(63);
  145. } else {
  146. assert(BitWidth == 32 && "Unexpected bit width");
  147. Zero = Builder.getInt32(0);
  148. One = Builder.getInt32(1);
  149. NegOne = ConstantInt::getSigned(DivTy, -1);
  150. MSB = Builder.getInt32(31);
  151. }
  152. ConstantInt *True = Builder.getTrue();
  153. BasicBlock *IBB = Builder.GetInsertBlock();
  154. Function *F = IBB->getParent();
  155. Function *CTLZ = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
  156. DivTy);
  157. // Our CFG is going to look like:
  158. // +---------------------+
  159. // | special-cases |
  160. // | ... |
  161. // +---------------------+
  162. // | |
  163. // | +----------+
  164. // | | bb1 |
  165. // | | ... |
  166. // | +----------+
  167. // | | |
  168. // | | +------------+
  169. // | | | preheader |
  170. // | | | ... |
  171. // | | +------------+
  172. // | | |
  173. // | | | +---+
  174. // | | | | |
  175. // | | +------------+ |
  176. // | | | do-while | |
  177. // | | | ... | |
  178. // | | +------------+ |
  179. // | | | | |
  180. // | +-----------+ +---+
  181. // | | loop-exit |
  182. // | | ... |
  183. // | +-----------+
  184. // | |
  185. // +-------+
  186. // | ... |
  187. // | end |
  188. // +-------+
  189. BasicBlock *SpecialCases = Builder.GetInsertBlock();
  190. SpecialCases->setName(Twine(SpecialCases->getName(), "_udiv-special-cases"));
  191. BasicBlock *End = SpecialCases->splitBasicBlock(Builder.GetInsertPoint(),
  192. "udiv-end");
  193. BasicBlock *LoopExit = BasicBlock::Create(Builder.getContext(),
  194. "udiv-loop-exit", F, End);
  195. BasicBlock *DoWhile = BasicBlock::Create(Builder.getContext(),
  196. "udiv-do-while", F, End);
  197. BasicBlock *Preheader = BasicBlock::Create(Builder.getContext(),
  198. "udiv-preheader", F, End);
  199. BasicBlock *BB1 = BasicBlock::Create(Builder.getContext(),
  200. "udiv-bb1", F, End);
  201. // We'll be overwriting the terminator to insert our extra blocks
  202. SpecialCases->getTerminator()->eraseFromParent();
  203. // Same instructions are generated for both i32 (msb 31) and i64 (msb 63).
  204. // First off, check for special cases: dividend or divisor is zero, divisor
  205. // is greater than dividend, and divisor is 1.
  206. // ; special-cases:
  207. // ; %ret0_1 = icmp eq i32 %divisor, 0
  208. // ; %ret0_2 = icmp eq i32 %dividend, 0
  209. // ; %ret0_3 = or i1 %ret0_1, %ret0_2
  210. // ; %tmp0 = tail call i32 @llvm.ctlz.i32(i32 %divisor, i1 true)
  211. // ; %tmp1 = tail call i32 @llvm.ctlz.i32(i32 %dividend, i1 true)
  212. // ; %sr = sub nsw i32 %tmp0, %tmp1
  213. // ; %ret0_4 = icmp ugt i32 %sr, 31
  214. // ; %ret0 = or i1 %ret0_3, %ret0_4
  215. // ; %retDividend = icmp eq i32 %sr, 31
  216. // ; %retVal = select i1 %ret0, i32 0, i32 %dividend
  217. // ; %earlyRet = or i1 %ret0, %retDividend
  218. // ; br i1 %earlyRet, label %end, label %bb1
  219. Builder.SetInsertPoint(SpecialCases);
  220. Value *Ret0_1 = Builder.CreateICmpEQ(Divisor, Zero);
  221. Value *Ret0_2 = Builder.CreateICmpEQ(Dividend, Zero);
  222. Value *Ret0_3 = Builder.CreateOr(Ret0_1, Ret0_2);
  223. Value *Tmp0 = Builder.CreateCall(CTLZ, {Divisor, True});
  224. Value *Tmp1 = Builder.CreateCall(CTLZ, {Dividend, True});
  225. Value *SR = Builder.CreateSub(Tmp0, Tmp1);
  226. Value *Ret0_4 = Builder.CreateICmpUGT(SR, MSB);
  227. Value *Ret0 = Builder.CreateOr(Ret0_3, Ret0_4);
  228. Value *RetDividend = Builder.CreateICmpEQ(SR, MSB);
  229. Value *RetVal = Builder.CreateSelect(Ret0, Zero, Dividend);
  230. Value *EarlyRet = Builder.CreateOr(Ret0, RetDividend);
  231. Builder.CreateCondBr(EarlyRet, End, BB1);
  232. // ; bb1: ; preds = %special-cases
  233. // ; %sr_1 = add i32 %sr, 1
  234. // ; %tmp2 = sub i32 31, %sr
  235. // ; %q = shl i32 %dividend, %tmp2
  236. // ; %skipLoop = icmp eq i32 %sr_1, 0
  237. // ; br i1 %skipLoop, label %loop-exit, label %preheader
  238. Builder.SetInsertPoint(BB1);
  239. Value *SR_1 = Builder.CreateAdd(SR, One);
  240. Value *Tmp2 = Builder.CreateSub(MSB, SR);
  241. Value *Q = Builder.CreateShl(Dividend, Tmp2);
  242. Value *SkipLoop = Builder.CreateICmpEQ(SR_1, Zero);
  243. Builder.CreateCondBr(SkipLoop, LoopExit, Preheader);
  244. // ; preheader: ; preds = %bb1
  245. // ; %tmp3 = lshr i32 %dividend, %sr_1
  246. // ; %tmp4 = add i32 %divisor, -1
  247. // ; br label %do-while
  248. Builder.SetInsertPoint(Preheader);
  249. Value *Tmp3 = Builder.CreateLShr(Dividend, SR_1);
  250. Value *Tmp4 = Builder.CreateAdd(Divisor, NegOne);
  251. Builder.CreateBr(DoWhile);
  252. // ; do-while: ; preds = %do-while, %preheader
  253. // ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
  254. // ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
  255. // ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
  256. // ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
  257. // ; %tmp5 = shl i32 %r_1, 1
  258. // ; %tmp6 = lshr i32 %q_2, 31
  259. // ; %tmp7 = or i32 %tmp5, %tmp6
  260. // ; %tmp8 = shl i32 %q_2, 1
  261. // ; %q_1 = or i32 %carry_1, %tmp8
  262. // ; %tmp9 = sub i32 %tmp4, %tmp7
  263. // ; %tmp10 = ashr i32 %tmp9, 31
  264. // ; %carry = and i32 %tmp10, 1
  265. // ; %tmp11 = and i32 %tmp10, %divisor
  266. // ; %r = sub i32 %tmp7, %tmp11
  267. // ; %sr_2 = add i32 %sr_3, -1
  268. // ; %tmp12 = icmp eq i32 %sr_2, 0
  269. // ; br i1 %tmp12, label %loop-exit, label %do-while
  270. Builder.SetInsertPoint(DoWhile);
  271. PHINode *Carry_1 = Builder.CreatePHI(DivTy, 2);
  272. PHINode *SR_3 = Builder.CreatePHI(DivTy, 2);
  273. PHINode *R_1 = Builder.CreatePHI(DivTy, 2);
  274. PHINode *Q_2 = Builder.CreatePHI(DivTy, 2);
  275. Value *Tmp5 = Builder.CreateShl(R_1, One);
  276. Value *Tmp6 = Builder.CreateLShr(Q_2, MSB);
  277. Value *Tmp7 = Builder.CreateOr(Tmp5, Tmp6);
  278. Value *Tmp8 = Builder.CreateShl(Q_2, One);
  279. Value *Q_1 = Builder.CreateOr(Carry_1, Tmp8);
  280. Value *Tmp9 = Builder.CreateSub(Tmp4, Tmp7);
  281. Value *Tmp10 = Builder.CreateAShr(Tmp9, MSB);
  282. Value *Carry = Builder.CreateAnd(Tmp10, One);
  283. Value *Tmp11 = Builder.CreateAnd(Tmp10, Divisor);
  284. Value *R = Builder.CreateSub(Tmp7, Tmp11);
  285. Value *SR_2 = Builder.CreateAdd(SR_3, NegOne);
  286. Value *Tmp12 = Builder.CreateICmpEQ(SR_2, Zero);
  287. Builder.CreateCondBr(Tmp12, LoopExit, DoWhile);
  288. // ; loop-exit: ; preds = %do-while, %bb1
  289. // ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
  290. // ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
  291. // ; %tmp13 = shl i32 %q_3, 1
  292. // ; %q_4 = or i32 %carry_2, %tmp13
  293. // ; br label %end
  294. Builder.SetInsertPoint(LoopExit);
  295. PHINode *Carry_2 = Builder.CreatePHI(DivTy, 2);
  296. PHINode *Q_3 = Builder.CreatePHI(DivTy, 2);
  297. Value *Tmp13 = Builder.CreateShl(Q_3, One);
  298. Value *Q_4 = Builder.CreateOr(Carry_2, Tmp13);
  299. Builder.CreateBr(End);
  300. // ; end: ; preds = %loop-exit, %special-cases
  301. // ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
  302. // ; ret i32 %q_5
  303. Builder.SetInsertPoint(End, End->begin());
  304. PHINode *Q_5 = Builder.CreatePHI(DivTy, 2);
  305. // Populate the Phis, since all values have now been created. Our Phis were:
  306. // ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
  307. Carry_1->addIncoming(Zero, Preheader);
  308. Carry_1->addIncoming(Carry, DoWhile);
  309. // ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
  310. SR_3->addIncoming(SR_1, Preheader);
  311. SR_3->addIncoming(SR_2, DoWhile);
  312. // ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
  313. R_1->addIncoming(Tmp3, Preheader);
  314. R_1->addIncoming(R, DoWhile);
  315. // ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
  316. Q_2->addIncoming(Q, Preheader);
  317. Q_2->addIncoming(Q_1, DoWhile);
  318. // ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
  319. Carry_2->addIncoming(Zero, BB1);
  320. Carry_2->addIncoming(Carry, DoWhile);
  321. // ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
  322. Q_3->addIncoming(Q, BB1);
  323. Q_3->addIncoming(Q_1, DoWhile);
  324. // ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
  325. Q_5->addIncoming(Q_4, LoopExit);
  326. Q_5->addIncoming(RetVal, SpecialCases);
  327. return Q_5;
  328. }
  329. /// Generate code to calculate the remainder of two integers, replacing Rem with
  330. /// the generated code. This currently generates code using the udiv expansion,
  331. /// but future work includes generating more specialized code, e.g. when more
  332. /// information about the operands are known. Implements both 32bit and 64bit
  333. /// scalar division.
  334. ///
  335. /// @brief Replace Rem with generated code.
  336. bool llvm::expandRemainder(BinaryOperator *Rem) {
  337. assert((Rem->getOpcode() == Instruction::SRem ||
  338. Rem->getOpcode() == Instruction::URem) &&
  339. "Trying to expand remainder from a non-remainder function");
  340. IRBuilder<> Builder(Rem);
  341. Type *RemTy = Rem->getType();
  342. if (RemTy->isVectorTy())
  343. llvm_unreachable("Div over vectors not supported");
  344. unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
  345. if (RemTyBitWidth != 32 && RemTyBitWidth != 64)
  346. llvm_unreachable("Div of bitwidth other than 32 or 64 not supported");
  347. // First prepare the sign if it's a signed remainder
  348. if (Rem->getOpcode() == Instruction::SRem) {
  349. Value *Remainder = generateSignedRemainderCode(Rem->getOperand(0),
  350. Rem->getOperand(1), Builder);
  351. Rem->replaceAllUsesWith(Remainder);
  352. Rem->dropAllReferences();
  353. Rem->eraseFromParent();
  354. // If we didn't actually generate an urem instruction, we're done
  355. // This happens for example if the input were constant. In this case the
  356. // Builder insertion point was unchanged
  357. if (Rem == Builder.GetInsertPoint())
  358. return true;
  359. BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
  360. Rem = BO;
  361. }
  362. Value *Remainder = generatedUnsignedRemainderCode(Rem->getOperand(0),
  363. Rem->getOperand(1),
  364. Builder);
  365. Rem->replaceAllUsesWith(Remainder);
  366. Rem->dropAllReferences();
  367. Rem->eraseFromParent();
  368. // Expand the udiv
  369. if (BinaryOperator *UDiv = dyn_cast<BinaryOperator>(Builder.GetInsertPoint())) {
  370. assert(UDiv->getOpcode() == Instruction::UDiv && "Non-udiv in expansion?");
  371. expandDivision(UDiv);
  372. }
  373. return true;
  374. }
  375. /// Generate code to divide two integers, replacing Div with the generated
  376. /// code. This currently generates code similarly to compiler-rt's
  377. /// implementations, but future work includes generating more specialized code
  378. /// when more information about the operands are known. Implements both
  379. /// 32bit and 64bit scalar division.
  380. ///
  381. /// @brief Replace Div with generated code.
  382. bool llvm::expandDivision(BinaryOperator *Div) {
  383. assert((Div->getOpcode() == Instruction::SDiv ||
  384. Div->getOpcode() == Instruction::UDiv) &&
  385. "Trying to expand division from a non-division function");
  386. IRBuilder<> Builder(Div);
  387. Type *DivTy = Div->getType();
  388. if (DivTy->isVectorTy())
  389. llvm_unreachable("Div over vectors not supported");
  390. unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
  391. if (DivTyBitWidth != 32 && DivTyBitWidth != 64)
  392. llvm_unreachable("Div of bitwidth other than 32 or 64 not supported");
  393. // First prepare the sign if it's a signed division
  394. if (Div->getOpcode() == Instruction::SDiv) {
  395. // Lower the code to unsigned division, and reset Div to point to the udiv.
  396. Value *Quotient = generateSignedDivisionCode(Div->getOperand(0),
  397. Div->getOperand(1), Builder);
  398. Div->replaceAllUsesWith(Quotient);
  399. Div->dropAllReferences();
  400. Div->eraseFromParent();
  401. // If we didn't actually generate an udiv instruction, we're done
  402. // This happens for example if the input were constant. In this case the
  403. // Builder insertion point was unchanged
  404. if (Div == Builder.GetInsertPoint())
  405. return true;
  406. BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
  407. Div = BO;
  408. }
  409. // Insert the unsigned division code
  410. Value *Quotient = generateUnsignedDivisionCode(Div->getOperand(0),
  411. Div->getOperand(1),
  412. Builder);
  413. Div->replaceAllUsesWith(Quotient);
  414. Div->dropAllReferences();
  415. Div->eraseFromParent();
  416. return true;
  417. }
  418. /// Generate code to compute the remainder of two integers of bitwidth up to
  419. /// 32 bits. Uses the above routines and extends the inputs/truncates the
  420. /// outputs to operate in 32 bits; that is, these routines are good for targets
  421. /// that have no or very little suppport for smaller than 32 bit integer
  422. /// arithmetic.
  423. ///
  424. /// @brief Replace Rem with emulation code.
  425. bool llvm::expandRemainderUpTo32Bits(BinaryOperator *Rem) {
  426. assert((Rem->getOpcode() == Instruction::SRem ||
  427. Rem->getOpcode() == Instruction::URem) &&
  428. "Trying to expand remainder from a non-remainder function");
  429. Type *RemTy = Rem->getType();
  430. if (RemTy->isVectorTy())
  431. llvm_unreachable("Div over vectors not supported");
  432. unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
  433. if (RemTyBitWidth > 32)
  434. llvm_unreachable("Div of bitwidth greater than 32 not supported");
  435. if (RemTyBitWidth == 32)
  436. return expandRemainder(Rem);
  437. // If bitwidth smaller than 32 extend inputs, extend output and proceed
  438. // with 32 bit division.
  439. IRBuilder<> Builder(Rem);
  440. Value *ExtDividend;
  441. Value *ExtDivisor;
  442. Value *ExtRem;
  443. Value *Trunc;
  444. Type *Int32Ty = Builder.getInt32Ty();
  445. if (Rem->getOpcode() == Instruction::SRem) {
  446. ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int32Ty);
  447. ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int32Ty);
  448. ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
  449. } else {
  450. ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int32Ty);
  451. ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int32Ty);
  452. ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
  453. }
  454. Trunc = Builder.CreateTrunc(ExtRem, RemTy);
  455. Rem->replaceAllUsesWith(Trunc);
  456. Rem->dropAllReferences();
  457. Rem->eraseFromParent();
  458. return expandRemainder(cast<BinaryOperator>(ExtRem));
  459. }
  460. /// Generate code to compute the remainder of two integers of bitwidth up to
  461. /// 64 bits. Uses the above routines and extends the inputs/truncates the
  462. /// outputs to operate in 64 bits.
  463. ///
  464. /// @brief Replace Rem with emulation code.
  465. bool llvm::expandRemainderUpTo64Bits(BinaryOperator *Rem) {
  466. assert((Rem->getOpcode() == Instruction::SRem ||
  467. Rem->getOpcode() == Instruction::URem) &&
  468. "Trying to expand remainder from a non-remainder function");
  469. Type *RemTy = Rem->getType();
  470. if (RemTy->isVectorTy())
  471. llvm_unreachable("Div over vectors not supported");
  472. unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
  473. if (RemTyBitWidth > 64)
  474. llvm_unreachable("Div of bitwidth greater than 64 not supported");
  475. if (RemTyBitWidth == 64)
  476. return expandRemainder(Rem);
  477. // If bitwidth smaller than 64 extend inputs, extend output and proceed
  478. // with 64 bit division.
  479. IRBuilder<> Builder(Rem);
  480. Value *ExtDividend;
  481. Value *ExtDivisor;
  482. Value *ExtRem;
  483. Value *Trunc;
  484. Type *Int64Ty = Builder.getInt64Ty();
  485. if (Rem->getOpcode() == Instruction::SRem) {
  486. ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int64Ty);
  487. ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int64Ty);
  488. ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
  489. } else {
  490. ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int64Ty);
  491. ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int64Ty);
  492. ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
  493. }
  494. Trunc = Builder.CreateTrunc(ExtRem, RemTy);
  495. Rem->replaceAllUsesWith(Trunc);
  496. Rem->dropAllReferences();
  497. Rem->eraseFromParent();
  498. return expandRemainder(cast<BinaryOperator>(ExtRem));
  499. }
  500. /// Generate code to divide two integers of bitwidth up to 32 bits. Uses the
  501. /// above routines and extends the inputs/truncates the outputs to operate
  502. /// in 32 bits; that is, these routines are good for targets that have no
  503. /// or very little support for smaller than 32 bit integer arithmetic.
  504. ///
  505. /// @brief Replace Div with emulation code.
  506. bool llvm::expandDivisionUpTo32Bits(BinaryOperator *Div) {
  507. assert((Div->getOpcode() == Instruction::SDiv ||
  508. Div->getOpcode() == Instruction::UDiv) &&
  509. "Trying to expand division from a non-division function");
  510. Type *DivTy = Div->getType();
  511. if (DivTy->isVectorTy())
  512. llvm_unreachable("Div over vectors not supported");
  513. unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
  514. if (DivTyBitWidth > 32)
  515. llvm_unreachable("Div of bitwidth greater than 32 not supported");
  516. if (DivTyBitWidth == 32)
  517. return expandDivision(Div);
  518. // If bitwidth smaller than 32 extend inputs, extend output and proceed
  519. // with 32 bit division.
  520. IRBuilder<> Builder(Div);
  521. Value *ExtDividend;
  522. Value *ExtDivisor;
  523. Value *ExtDiv;
  524. Value *Trunc;
  525. Type *Int32Ty = Builder.getInt32Ty();
  526. if (Div->getOpcode() == Instruction::SDiv) {
  527. ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int32Ty);
  528. ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int32Ty);
  529. ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
  530. } else {
  531. ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int32Ty);
  532. ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int32Ty);
  533. ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);
  534. }
  535. Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
  536. Div->replaceAllUsesWith(Trunc);
  537. Div->dropAllReferences();
  538. Div->eraseFromParent();
  539. return expandDivision(cast<BinaryOperator>(ExtDiv));
  540. }
  541. /// Generate code to divide two integers of bitwidth up to 64 bits. Uses the
  542. /// above routines and extends the inputs/truncates the outputs to operate
  543. /// in 64 bits.
  544. ///
  545. /// @brief Replace Div with emulation code.
  546. bool llvm::expandDivisionUpTo64Bits(BinaryOperator *Div) {
  547. assert((Div->getOpcode() == Instruction::SDiv ||
  548. Div->getOpcode() == Instruction::UDiv) &&
  549. "Trying to expand division from a non-division function");
  550. Type *DivTy = Div->getType();
  551. if (DivTy->isVectorTy())
  552. llvm_unreachable("Div over vectors not supported");
  553. unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
  554. if (DivTyBitWidth > 64)
  555. llvm_unreachable("Div of bitwidth greater than 64 not supported");
  556. if (DivTyBitWidth == 64)
  557. return expandDivision(Div);
  558. // If bitwidth smaller than 64 extend inputs, extend output and proceed
  559. // with 64 bit division.
  560. IRBuilder<> Builder(Div);
  561. Value *ExtDividend;
  562. Value *ExtDivisor;
  563. Value *ExtDiv;
  564. Value *Trunc;
  565. Type *Int64Ty = Builder.getInt64Ty();
  566. if (Div->getOpcode() == Instruction::SDiv) {
  567. ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int64Ty);
  568. ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int64Ty);
  569. ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
  570. } else {
  571. ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int64Ty);
  572. ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int64Ty);
  573. ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);
  574. }
  575. Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
  576. Div->replaceAllUsesWith(Trunc);
  577. Div->dropAllReferences();
  578. Div->eraseFromParent();
  579. return expandDivision(cast<BinaryOperator>(ExtDiv));
  580. }