LLVM 23.0.0git
IntegerDivision.cpp
Go to the documentation of this file.
1//===-- IntegerDivision.cpp - Expand integer division ---------------------===//
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 file contains an implementation of 32bit and 64bit scalar integer
10// division for targets that don't have native support. It's largely derived
11// from compiler-rt's implementations of __udivsi3 and __udivmoddi4,
12// but hand-tuned for targets that prefer less control flow.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/IR/Function.h"
18#include "llvm/IR/IRBuilder.h"
19#include "llvm/IR/Instruction.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/MDBuilder.h"
25#include "llvm/IR/Value.h"
27
28using namespace llvm;
29
30#define DEBUG_TYPE "integer-division"
31
32/// Generate code to compute the remainder of two signed integers. Returns the
33/// remainder, which will have the sign of the dividend. Builder's insert point
34/// should be pointing where the caller wants code generated, e.g. at the srem
35/// instruction. This will generate a urem in the process, and Builder's insert
36/// point will be pointing at the uren (if present, i.e. not folded), ready to
37/// be expanded if the user wishes
38static Value *generateSignedRemainderCode(Value *Dividend, Value *Divisor,
39 IRBuilder<> &Builder) {
40 unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();
41 ConstantInt *Shift = Builder.getIntN(BitWidth, BitWidth - 1);
42
43 // Following instructions are generated for both i32 (shift 31) and
44 // i64 (shift 63).
45
46 // ; %dividend_sgn = ashr i32 %dividend, 31
47 // ; %divisor_sgn = ashr i32 %divisor, 31
48 // ; %dvd_xor = xor i32 %dividend, %dividend_sgn
49 // ; %dvs_xor = xor i32 %divisor, %divisor_sgn
50 // ; %u_dividend = sub i32 %dvd_xor, %dividend_sgn
51 // ; %u_divisor = sub i32 %dvs_xor, %divisor_sgn
52 // ; %urem = urem i32 %dividend, %divisor
53 // ; %xored = xor i32 %urem, %dividend_sgn
54 // ; %srem = sub i32 %xored, %dividend_sgn
55 Dividend = Builder.CreateFreeze(Dividend);
56 Divisor = Builder.CreateFreeze(Divisor);
57 Value *DividendSign = Builder.CreateAShr(Dividend, Shift);
58 Value *DivisorSign = Builder.CreateAShr(Divisor, Shift);
59 Value *DvdXor = Builder.CreateXor(Dividend, DividendSign);
60 Value *DvsXor = Builder.CreateXor(Divisor, DivisorSign);
61 Value *UDividend = Builder.CreateSub(DvdXor, DividendSign);
62 Value *UDivisor = Builder.CreateSub(DvsXor, DivisorSign);
63 Value *URem = Builder.CreateURem(UDividend, UDivisor);
64 Value *Xored = Builder.CreateXor(URem, DividendSign);
65 Value *SRem = Builder.CreateSub(Xored, DividendSign);
66
67 if (Instruction *URemInst = dyn_cast<Instruction>(URem))
68 Builder.SetInsertPoint(URemInst);
69
70 return SRem;
71}
72
73
74/// Generate code to compute the remainder of two unsigned integers. Returns the
75/// remainder. Builder's insert point should be pointing where the caller wants
76/// code generated, e.g. at the urem instruction. This will generate a udiv in
77/// the process, and Builder's insert point will be pointing at the udiv (if
78/// present, i.e. not folded), ready to be expanded if the user wishes
79static Value *generateUnsignedRemainderCode(Value *Dividend, Value *Divisor,
80 IRBuilder<> &Builder) {
81 // Remainder = Dividend - Quotient*Divisor
82
83 // Following instructions are generated for both i32 and i64
84
85 // ; %quotient = udiv i32 %dividend, %divisor
86 // ; %product = mul i32 %divisor, %quotient
87 // ; %remainder = sub i32 %dividend, %product
88 Dividend = Builder.CreateFreeze(Dividend);
89 Divisor = Builder.CreateFreeze(Divisor);
90 Value *Quotient = Builder.CreateUDiv(Dividend, Divisor);
91 Value *Product = Builder.CreateMul(Divisor, Quotient);
92 Value *Remainder = Builder.CreateSub(Dividend, Product);
93
94 if (Instruction *UDiv = dyn_cast<Instruction>(Quotient))
95 Builder.SetInsertPoint(UDiv);
96
97 return Remainder;
98}
99
100/// Generate code to divide two signed integers. Returns the quotient, rounded
101/// towards 0. Builder's insert point should be pointing where the caller wants
102/// code generated, e.g. at the sdiv instruction. This will generate a udiv in
103/// the process, and Builder's insert point will be pointing at the udiv (if
104/// present, i.e. not folded), ready to be expanded if the user wishes.
105static Value *generateSignedDivisionCode(Value *Dividend, Value *Divisor,
106 IRBuilder<> &Builder) {
107 // Implementation taken from compiler-rt's __divsi3 and __divdi3
108
109 unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();
110 ConstantInt *Shift = Builder.getIntN(BitWidth, BitWidth - 1);
111
112 // Following instructions are generated for both i32 (shift 31) and
113 // i64 (shift 63).
114
115 // ; %tmp = ashr i32 %dividend, 31
116 // ; %tmp1 = ashr i32 %divisor, 31
117 // ; %tmp2 = xor i32 %tmp, %dividend
118 // ; %u_dvnd = sub nsw i32 %tmp2, %tmp
119 // ; %tmp3 = xor i32 %tmp1, %divisor
120 // ; %u_dvsr = sub nsw i32 %tmp3, %tmp1
121 // ; %q_sgn = xor i32 %tmp1, %tmp
122 // ; %q_mag = udiv i32 %u_dvnd, %u_dvsr
123 // ; %tmp4 = xor i32 %q_mag, %q_sgn
124 // ; %q = sub i32 %tmp4, %q_sgn
125 Dividend = Builder.CreateFreeze(Dividend);
126 Divisor = Builder.CreateFreeze(Divisor);
127 Value *Tmp = Builder.CreateAShr(Dividend, Shift);
128 Value *Tmp1 = Builder.CreateAShr(Divisor, Shift);
129 Value *Tmp2 = Builder.CreateXor(Tmp, Dividend);
130 Value *U_Dvnd = Builder.CreateSub(Tmp2, Tmp);
131 Value *Tmp3 = Builder.CreateXor(Tmp1, Divisor);
132 Value *U_Dvsr = Builder.CreateSub(Tmp3, Tmp1);
133 Value *Q_Sgn = Builder.CreateXor(Tmp1, Tmp);
134 Value *Q_Mag = Builder.CreateUDiv(U_Dvnd, U_Dvsr);
135 Value *Tmp4 = Builder.CreateXor(Q_Mag, Q_Sgn);
136 Value *Q = Builder.CreateSub(Tmp4, Q_Sgn);
137
138 if (Instruction *UDiv = dyn_cast<Instruction>(Q_Mag))
139 Builder.SetInsertPoint(UDiv);
140
141 return Q;
142}
143
144/// Generates code to divide two unsigned scalar 32-bit or 64-bit integers.
145/// Returns the quotient, rounded towards 0. Builder's insert point should
146/// point where the caller wants code generated, e.g. at the udiv instruction.
147static Value *generateUnsignedDivisionCode(Value *Dividend, Value *Divisor,
148 IRBuilder<> &Builder) {
149 // The basic algorithm can be found in the compiler-rt project's
150 // implementation of __udivsi3.c. Here, we do a lower-level IR based approach
151 // that's been hand-tuned to lessen the amount of control flow involved.
152
153 // Some helper values
154 IntegerType *DivTy = cast<IntegerType>(Dividend->getType());
155 unsigned BitWidth = DivTy->getBitWidth();
156
157 ConstantInt *Zero = ConstantInt::get(DivTy, 0);
158 ConstantInt *One = ConstantInt::get(DivTy, 1);
159 ConstantInt *NegOne = ConstantInt::getSigned(DivTy, -1);
160 ConstantInt *MSB = ConstantInt::get(DivTy, BitWidth - 1);
161
162 ConstantInt *True = Builder.getTrue();
163
164 BasicBlock *IBB = Builder.GetInsertBlock();
165 Function *F = IBB->getParent();
166 Function *CTLZ =
167 Intrinsic::getOrInsertDeclaration(F->getParent(), Intrinsic::ctlz, DivTy);
168
169 // Our CFG is going to look like:
170 // +---------------------+
171 // | special-cases |
172 // | ... |
173 // +---------------------+
174 // | |
175 // | +----------+
176 // | | bb1 |
177 // | | ... |
178 // | +----------+
179 // | | |
180 // | | +------------+
181 // | | | preheader |
182 // | | | ... |
183 // | | +------------+
184 // | | |
185 // | | | +---+
186 // | | | | |
187 // | | +------------+ |
188 // | | | do-while | |
189 // | | | ... | |
190 // | | +------------+ |
191 // | | | | |
192 // | +-----------+ +---+
193 // | | loop-exit |
194 // | | ... |
195 // | +-----------+
196 // | |
197 // +-------+
198 // | ... |
199 // | end |
200 // +-------+
201 BasicBlock *SpecialCases = Builder.GetInsertBlock();
202 SpecialCases->setName(Twine(SpecialCases->getName(), "_udiv-special-cases"));
203 BasicBlock *End = SpecialCases->splitBasicBlock(Builder.GetInsertPoint(),
204 "udiv-end");
205 BasicBlock *LoopExit = BasicBlock::Create(Builder.getContext(),
206 "udiv-loop-exit", F, End);
207 BasicBlock *DoWhile = BasicBlock::Create(Builder.getContext(),
208 "udiv-do-while", F, End);
209 BasicBlock *Preheader = BasicBlock::Create(Builder.getContext(),
210 "udiv-preheader", F, End);
211 BasicBlock *BB1 = BasicBlock::Create(Builder.getContext(),
212 "udiv-bb1", F, End);
213
214 // We'll be overwriting the terminator to insert our extra blocks
215 SpecialCases->getTerminator()->eraseFromParent();
216
217 // Same instructions are generated for both i32 (msb 31) and i64 (msb 63).
218
219 // First off, check for special cases: dividend or divisor is zero, divisor
220 // is greater than dividend, and divisor is 1.
221 // ; special-cases:
222 // ; %ret0_1 = icmp eq i32 %divisor, 0
223 // ; %ret0_2 = icmp eq i32 %dividend, 0
224 // ; %ret0_3 = or i1 %ret0_1, %ret0_2
225 // ; %tmp0 = tail call i32 @llvm.ctlz.i32(i32 %divisor, i1 true)
226 // ; %tmp1 = tail call i32 @llvm.ctlz.i32(i32 %dividend, i1 true)
227 // ; %sr = sub nsw i32 %tmp0, %tmp1
228 // ; %ret0_4 = icmp ugt i32 %sr, 31
229 // ; %ret0 = select i1 %ret0_3, i1 true, i1 %ret0_4
230 // ; %retDividend = icmp eq i32 %sr, 31
231 // ; %retVal = select i1 %ret0, i32 0, i32 %dividend
232 // ; %earlyRet = select i1 %ret0, i1 true, %retDividend
233 // ; br i1 %earlyRet, label %end, label %bb1
234 Builder.SetInsertPoint(SpecialCases);
235 Divisor = Builder.CreateFreeze(Divisor);
236 Dividend = Builder.CreateFreeze(Dividend);
237 Value *Ret0_1 = Builder.CreateICmpEQ(Divisor, Zero);
238 Value *Ret0_2 = Builder.CreateICmpEQ(Dividend, Zero);
239 Value *Ret0_3 = Builder.CreateOr(Ret0_1, Ret0_2);
240 Value *Tmp0 = Builder.CreateCall(CTLZ, {Divisor, True});
241 Value *Tmp1 = Builder.CreateCall(CTLZ, {Dividend, True});
242 Value *SR = Builder.CreateSub(Tmp0, Tmp1);
243 Value *Ret0_4 = Builder.CreateICmpUGT(SR, MSB);
244
245 // Add 'unlikely' branch weights. We mark the case where either the divisor
246 // or the dividend is equal to zero as unlikely.
247 Value *Ret0 = Builder.CreateLogicalOr(Ret0_3, Ret0_4);
248 applyProfMetadataIfEnabled(Ret0, [&](Instruction *Inst) {
249 Inst->setMetadata(
250 LLVMContext::MD_prof,
252 });
253 Value *RetDividend = Builder.CreateICmpEQ(SR, MSB);
254
255 // Conservatively, we treat the case |divisor| > |dividend| as unknown
256 Value *RetVal = Builder.CreateSelect(Ret0, Zero, Dividend);
257 applyProfMetadataIfEnabled(RetVal, [&](Instruction *Inst) {
259 });
260 Value *EarlyRet = Builder.CreateLogicalOr(Ret0, RetDividend);
261 applyProfMetadataIfEnabled(EarlyRet, [&](Instruction *Inst) {
263 });
264
265 // The condition of this branch is based on `EarlyRet`. `EarlyRet` is true
266 // only for special cases like dividend or divisor being zero, or the divisor
267 // being greater than the dividend. Thus, the branch to `End` is unlikely,
268 // and we expect to more frequently enter `BB1`.
269 Value *ConBrSpecialCases = Builder.CreateCondBr(EarlyRet, End, BB1);
270 applyProfMetadataIfEnabled(ConBrSpecialCases, [&](Instruction *Inst) {
271 Inst->setMetadata(
272 LLVMContext::MD_prof,
274 });
275
276 // ; bb1: ; preds = %special-cases
277 // ; %sr_1 = add i32 %sr, 1
278 // ; %tmp2 = sub i32 31, %sr
279 // ; %q = shl i32 %dividend, %tmp2
280 // ; %skipLoop = icmp eq i32 %sr_1, 0
281 // ; br i1 %skipLoop, label %loop-exit, label %preheader
282 Builder.SetInsertPoint(BB1);
283 Value *SR_1 = Builder.CreateAdd(SR, One);
284 Value *Tmp2 = Builder.CreateSub(MSB, SR);
285 Value *Q = Builder.CreateShl(Dividend, Tmp2);
286 // We assume that in the common case, the dividend's magnitude is larger than
287 // the divisor's magnitude such that the loop counter (SR) is non-zero.
288 // Specifically, if |dividend| >= 2 * |divisor|, then SR >= 1, ensuring SR_1
289 // >= 2. The case where SR_1 == 0 is thus considered unlikely.
290 Value *SkipLoop = Builder.CreateICmpEQ(SR_1, Zero);
291 Value *ConBrBB1 = Builder.CreateCondBr(SkipLoop, LoopExit, Preheader);
292 applyProfMetadataIfEnabled(ConBrBB1, [&](Instruction *Inst) {
293 Inst->setMetadata(
294 LLVMContext::MD_prof,
296 });
297
298 // ; preheader: ; preds = %bb1
299 // ; %tmp3 = lshr i32 %dividend, %sr_1
300 // ; %tmp4 = add i32 %divisor, -1
301 // ; br label %do-while
302 Builder.SetInsertPoint(Preheader);
303 Value *Tmp3 = Builder.CreateLShr(Dividend, SR_1);
304 Value *Tmp4 = Builder.CreateAdd(Divisor, NegOne);
305 Builder.CreateBr(DoWhile);
306
307 // ; do-while: ; preds = %do-while, %preheader
308 // ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
309 // ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
310 // ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
311 // ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
312 // ; %tmp5 = shl i32 %r_1, 1
313 // ; %tmp6 = lshr i32 %q_2, 31
314 // ; %tmp7 = or i32 %tmp5, %tmp6
315 // ; %tmp8 = shl i32 %q_2, 1
316 // ; %q_1 = or i32 %carry_1, %tmp8
317 // ; %tmp9 = sub i32 %tmp4, %tmp7
318 // ; %tmp10 = ashr i32 %tmp9, 31
319 // ; %carry = and i32 %tmp10, 1
320 // ; %tmp11 = and i32 %tmp10, %divisor
321 // ; %r = sub i32 %tmp7, %tmp11
322 // ; %sr_2 = add i32 %sr_3, -1
323 // ; %tmp12 = icmp eq i32 %sr_2, 0
324 // ; br i1 %tmp12, label %loop-exit, label %do-while
325 Builder.SetInsertPoint(DoWhile);
326 PHINode *Carry_1 = Builder.CreatePHI(DivTy, 2);
327 PHINode *SR_3 = Builder.CreatePHI(DivTy, 2);
328 PHINode *R_1 = Builder.CreatePHI(DivTy, 2);
329 PHINode *Q_2 = Builder.CreatePHI(DivTy, 2);
330 Value *Tmp5 = Builder.CreateShl(R_1, One);
331 Value *Tmp6 = Builder.CreateLShr(Q_2, MSB);
332 Value *Tmp7 = Builder.CreateOr(Tmp5, Tmp6);
333 Value *Tmp8 = Builder.CreateShl(Q_2, One);
334 Value *Q_1 = Builder.CreateOr(Carry_1, Tmp8);
335 Value *Tmp9 = Builder.CreateSub(Tmp4, Tmp7);
336 Value *Tmp10 = Builder.CreateAShr(Tmp9, MSB);
337 Value *Carry = Builder.CreateAnd(Tmp10, One);
338 Value *Tmp11 = Builder.CreateAnd(Tmp10, Divisor);
339 Value *R = Builder.CreateSub(Tmp7, Tmp11);
340 Value *SR_2 = Builder.CreateAdd(SR_3, NegOne);
341 Value *Tmp12 = Builder.CreateICmpEQ(SR_2, Zero);
342 // The loop implements the core bit-by-bit binary long division algorithm.
343 // The branch is unlikely to exit the loop early until it has processed all
344 // significant bits.
345 Value *ConBrDoWhile = Builder.CreateCondBr(Tmp12, LoopExit, DoWhile);
346 applyProfMetadataIfEnabled(ConBrDoWhile, [&](Instruction *Inst) {
347 Inst->setMetadata(
348 LLVMContext::MD_prof,
350 });
351
352 // ; loop-exit: ; preds = %do-while, %bb1
353 // ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
354 // ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
355 // ; %tmp13 = shl i32 %q_3, 1
356 // ; %q_4 = or i32 %carry_2, %tmp13
357 // ; br label %end
358 Builder.SetInsertPoint(LoopExit);
359 PHINode *Carry_2 = Builder.CreatePHI(DivTy, 2);
360 PHINode *Q_3 = Builder.CreatePHI(DivTy, 2);
361 Value *Tmp13 = Builder.CreateShl(Q_3, One);
362 Value *Q_4 = Builder.CreateOr(Carry_2, Tmp13);
363 Builder.CreateBr(End);
364
365 // ; end: ; preds = %loop-exit, %special-cases
366 // ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
367 // ; ret i32 %q_5
368 Builder.SetInsertPoint(End, End->begin());
369 PHINode *Q_5 = Builder.CreatePHI(DivTy, 2);
370
371 // Populate the Phis, since all values have now been created. Our Phis were:
372 // ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
373 Carry_1->addIncoming(Zero, Preheader);
374 Carry_1->addIncoming(Carry, DoWhile);
375 // ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
376 SR_3->addIncoming(SR_1, Preheader);
377 SR_3->addIncoming(SR_2, DoWhile);
378 // ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
379 R_1->addIncoming(Tmp3, Preheader);
380 R_1->addIncoming(R, DoWhile);
381 // ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
382 Q_2->addIncoming(Q, Preheader);
383 Q_2->addIncoming(Q_1, DoWhile);
384 // ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
385 Carry_2->addIncoming(Zero, BB1);
386 Carry_2->addIncoming(Carry, DoWhile);
387 // ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
388 Q_3->addIncoming(Q, BB1);
389 Q_3->addIncoming(Q_1, DoWhile);
390 // ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
391 Q_5->addIncoming(Q_4, LoopExit);
392 Q_5->addIncoming(RetVal, SpecialCases);
393
394 return Q_5;
395}
396
397/// Generate code to calculate the remainder of two integers, replacing Rem with
398/// the generated code. This currently generates code using the udiv expansion,
399/// but future work includes generating more specialized code, e.g. when more
400/// information about the operands are known.
401///
402/// Replace Rem with generated code.
404 assert((Rem->getOpcode() == Instruction::SRem ||
405 Rem->getOpcode() == Instruction::URem) &&
406 "Trying to expand remainder from a non-remainder function");
407
408 IRBuilder<> Builder(Rem);
409
410 assert(!Rem->getType()->isVectorTy() && "Div over vectors not supported");
411
412 // First prepare the sign if it's a signed remainder
413 if (Rem->getOpcode() == Instruction::SRem) {
414 Value *Remainder = generateSignedRemainderCode(Rem->getOperand(0),
415 Rem->getOperand(1), Builder);
416
417 // Check whether this is the insert point while Rem is still valid.
418 bool IsInsertPoint = Rem->getIterator() == Builder.GetInsertPoint();
419 Rem->replaceAllUsesWith(Remainder);
420 Rem->dropAllReferences();
421 Rem->eraseFromParent();
422
423 // If we didn't actually generate an urem instruction, we're done
424 // This happens for example if the input were constant. In this case the
425 // Builder insertion point was unchanged
426 if (IsInsertPoint)
427 return true;
428
429 BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
430 Rem = BO;
431 }
432
434 Rem->getOperand(1), Builder);
435
436 Rem->replaceAllUsesWith(Remainder);
437 Rem->dropAllReferences();
438 Rem->eraseFromParent();
439
440 // Expand the udiv
441 if (BinaryOperator *UDiv = dyn_cast<BinaryOperator>(Builder.GetInsertPoint())) {
442 assert(UDiv->getOpcode() == Instruction::UDiv && "Non-udiv in expansion?");
443 expandDivision(UDiv);
444 }
445
446 return true;
447}
448
449/// Generate code to divide two integers, replacing Div with the generated
450/// code. This currently generates code similarly to compiler-rt's
451/// implementations, but future work includes generating more specialized code
452/// when more information about the operands are known.
453///
454/// Replace Div with generated code.
456 assert((Div->getOpcode() == Instruction::SDiv ||
457 Div->getOpcode() == Instruction::UDiv) &&
458 "Trying to expand division from a non-division function");
459
460 IRBuilder<> Builder(Div);
461
462 assert(!Div->getType()->isVectorTy() && "Div over vectors not supported");
463
464 // First prepare the sign if it's a signed division
465 if (Div->getOpcode() == Instruction::SDiv) {
466 // Lower the code to unsigned division, and reset Div to point to the udiv.
467 Value *Quotient = generateSignedDivisionCode(Div->getOperand(0),
468 Div->getOperand(1), Builder);
469
470 // Check whether this is the insert point while Div is still valid.
471 bool IsInsertPoint = Div->getIterator() == Builder.GetInsertPoint();
472 Div->replaceAllUsesWith(Quotient);
473 Div->dropAllReferences();
474 Div->eraseFromParent();
475
476 // If we didn't actually generate an udiv instruction, we're done
477 // This happens for example if the input were constant. In this case the
478 // Builder insertion point was unchanged
479 if (IsInsertPoint)
480 return true;
481
482 BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
483 Div = BO;
484 }
485
486 // Insert the unsigned division code
488 Div->getOperand(1),
489 Builder);
490 Div->replaceAllUsesWith(Quotient);
491 Div->dropAllReferences();
492 Div->eraseFromParent();
493
494 return true;
495}
496
497/// Generate code to compute the remainder of two integers of bitwidth up to
498/// 32 bits. Uses the above routines and extends the inputs/truncates the
499/// outputs to operate in 32 bits; that is, these routines are good for targets
500/// that have no or very little suppport for smaller than 32 bit integer
501/// arithmetic.
502///
503/// Replace Rem with emulation code.
505 assert((Rem->getOpcode() == Instruction::SRem ||
506 Rem->getOpcode() == Instruction::URem) &&
507 "Trying to expand remainder from a non-remainder function");
508
509 Type *RemTy = Rem->getType();
510 assert(!RemTy->isVectorTy() && "Div over vectors not supported");
511
512 unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
513
514 assert(RemTyBitWidth <= 32 &&
515 "Div of bitwidth greater than 32 not supported");
516
517 if (RemTyBitWidth == 32)
518 return expandRemainder(Rem);
519
520 // If bitwidth smaller than 32 extend inputs, extend output and proceed
521 // with 32 bit division.
522 IRBuilder<> Builder(Rem);
523
524 Value *ExtDividend;
525 Value *ExtDivisor;
526 Value *ExtRem;
527 Value *Trunc;
528 Type *Int32Ty = Builder.getInt32Ty();
529
530 if (Rem->getOpcode() == Instruction::SRem) {
531 ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int32Ty);
532 ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int32Ty);
533 ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
534 } else {
535 ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int32Ty);
536 ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int32Ty);
537 ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
538 }
539 Trunc = Builder.CreateTrunc(ExtRem, RemTy);
540
541 Rem->replaceAllUsesWith(Trunc);
542 Rem->dropAllReferences();
543 Rem->eraseFromParent();
544
546}
547
548/// Generate code to compute the remainder of two integers of bitwidth up to
549/// 64 bits. Uses the above routines and extends the inputs/truncates the
550/// outputs to operate in 64 bits.
551///
552/// Replace Rem with emulation code.
554 assert((Rem->getOpcode() == Instruction::SRem ||
555 Rem->getOpcode() == Instruction::URem) &&
556 "Trying to expand remainder from a non-remainder function");
557
558 Type *RemTy = Rem->getType();
559 assert(!RemTy->isVectorTy() && "Div over vectors not supported");
560
561 unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
562
563 if (RemTyBitWidth >= 64)
564 return expandRemainder(Rem);
565
566 // If bitwidth smaller than 64 extend inputs, extend output and proceed
567 // with 64 bit division.
568 IRBuilder<> Builder(Rem);
569
570 Value *ExtDividend;
571 Value *ExtDivisor;
572 Value *ExtRem;
573 Value *Trunc;
574 Type *Int64Ty = Builder.getInt64Ty();
575
576 if (Rem->getOpcode() == Instruction::SRem) {
577 ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int64Ty);
578 ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int64Ty);
579 ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
580 } else {
581 ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int64Ty);
582 ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int64Ty);
583 ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
584 }
585 Trunc = Builder.CreateTrunc(ExtRem, RemTy);
586
587 Rem->replaceAllUsesWith(Trunc);
588 Rem->dropAllReferences();
589 Rem->eraseFromParent();
590
592}
593
594/// Generate code to divide two integers of bitwidth up to 32 bits. Uses the
595/// above routines and extends the inputs/truncates the outputs to operate
596/// in 32 bits; that is, these routines are good for targets that have no
597/// or very little support for smaller than 32 bit integer arithmetic.
598///
599/// Replace Div with emulation code.
601 assert((Div->getOpcode() == Instruction::SDiv ||
602 Div->getOpcode() == Instruction::UDiv) &&
603 "Trying to expand division from a non-division function");
604
605 Type *DivTy = Div->getType();
606 assert(!DivTy->isVectorTy() && "Div over vectors not supported");
607
608 unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
609
610 assert(DivTyBitWidth <= 32 && "Div of bitwidth greater than 32 not supported");
611
612 if (DivTyBitWidth == 32)
613 return expandDivision(Div);
614
615 // If bitwidth smaller than 32 extend inputs, extend output and proceed
616 // with 32 bit division.
617 IRBuilder<> Builder(Div);
618
619 Value *ExtDividend;
620 Value *ExtDivisor;
621 Value *ExtDiv;
622 Value *Trunc;
623 Type *Int32Ty = Builder.getInt32Ty();
624
625 if (Div->getOpcode() == Instruction::SDiv) {
626 ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int32Ty);
627 ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int32Ty);
628 ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
629 } else {
630 ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int32Ty);
631 ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int32Ty);
632 ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);
633 }
634 Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
635
636 Div->replaceAllUsesWith(Trunc);
637 Div->dropAllReferences();
638 Div->eraseFromParent();
639
640 return expandDivision(cast<BinaryOperator>(ExtDiv));
641}
642
643/// Generate code to divide two integers of bitwidth up to 64 bits. Uses the
644/// above routines and extends the inputs/truncates the outputs to operate
645/// in 64 bits.
646///
647/// Replace Div with emulation code.
649 assert((Div->getOpcode() == Instruction::SDiv ||
650 Div->getOpcode() == Instruction::UDiv) &&
651 "Trying to expand division from a non-division function");
652
653 Type *DivTy = Div->getType();
654 assert(!DivTy->isVectorTy() && "Div over vectors not supported");
655
656 unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
657
658 if (DivTyBitWidth >= 64)
659 return expandDivision(Div);
660
661 // If bitwidth smaller than 64 extend inputs, extend output and proceed
662 // with 64 bit division.
663 IRBuilder<> Builder(Div);
664
665 Value *ExtDividend;
666 Value *ExtDivisor;
667 Value *ExtDiv;
668 Value *Trunc;
669 Type *Int64Ty = Builder.getInt64Ty();
670
671 if (Div->getOpcode() == Instruction::SDiv) {
672 ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int64Ty);
673 ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int64Ty);
674 ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
675 } else {
676 ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int64Ty);
677 ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int64Ty);
678 ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);
679 }
680 Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
681
682 Div->replaceAllUsesWith(Trunc);
683 Div->dropAllReferences();
684 Div->eraseFromParent();
685
686 return expandDivision(cast<BinaryOperator>(ExtDiv));
687}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define DEBUG_TYPE
static Value * generateSignedDivisionCode(Value *Dividend, Value *Divisor, IRBuilder<> &Builder)
Generate code to divide two signed integers.
static Value * generateUnsignedRemainderCode(Value *Dividend, Value *Divisor, IRBuilder<> &Builder)
Generate code to compute the remainder of two unsigned integers.
static Value * generateSignedRemainderCode(Value *Dividend, Value *Divisor, IRBuilder<> &Builder)
Generate code to compute the remainder of two signed integers.
static Value * generateUnsignedDivisionCode(Value *Dividend, Value *Divisor, IRBuilder<> &Builder)
Generates code to divide two unsigned scalar 32-bit or 64-bit integers.
#define F(x, y, z)
Definition MD5.cpp:54
This file contains the declarations for profiling metadata utility functions.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:470
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
BinaryOps getOpcode() const
Definition InstrTypes.h:374
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2776
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Class to represent integer types.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
void dropAllReferences()
Drop all references to operands.
Definition User.h:324
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
self_iterator getIterator()
Definition ilist_node.h:123
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI bool expandDivision(BinaryOperator *Div)
Generate code to divide two integers, replacing Div with the generated code.
LLVM_ABI bool expandRemainderUpTo32Bits(BinaryOperator *Rem)
Generate code to calculate the remainder of two integers, replacing Rem with the generated code.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:296
LLVM_ABI bool expandRemainderUpTo64Bits(BinaryOperator *Rem)
Generate code to calculate the remainder of two integers, replacing Rem with the generated code.
LLVM_ABI void applyProfMetadataIfEnabled(Value *V, llvm::function_ref< void(Instruction *)> setMetadataCallback)
LLVM_ABI bool expandDivisionUpTo64Bits(BinaryOperator *Div)
Generate code to divide two integers, replacing Div with the generated code.
LLVM_ABI bool expandDivisionUpTo32Bits(BinaryOperator *Div)
Generate code to divide two integers, replacing Div with the generated code.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool expandRemainder(BinaryOperator *Rem)
Generate code to calculate the remainder of two integers, replacing Rem with the generated code.