LLVM 24.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 if (auto *Inst = dyn_cast<Instruction>(Ret0))
249 Inst->setMetadata(
250 LLVMContext::MD_prof,
251 MDBuilder(Inst->getContext()).createUnlikelyBranchWeights());
252 Value *RetDividend = Builder.CreateICmpEQ(SR, MSB);
253
254 // Conservatively, we treat the case |divisor| > |dividend| as unknown
255 Value *RetVal = Builder.CreateSelect(Ret0, Zero, Dividend);
256 if (auto *Inst = dyn_cast<Instruction>(RetVal))
258 Value *EarlyRet = Builder.CreateLogicalOr(Ret0, RetDividend);
259 if (auto *Inst = dyn_cast<Instruction>(EarlyRet))
261
262 // The condition of this branch is based on `EarlyRet`. `EarlyRet` is true
263 // only for special cases like dividend or divisor being zero, or the divisor
264 // being greater than the dividend. Thus, the branch to `End` is unlikely,
265 // and we expect to more frequently enter `BB1`.
266 Value *ConBrSpecialCases = Builder.CreateCondBr(EarlyRet, End, BB1);
267 if (auto *Inst = dyn_cast<Instruction>(ConBrSpecialCases))
268 Inst->setMetadata(
269 LLVMContext::MD_prof,
270 MDBuilder(Inst->getContext()).createUnlikelyBranchWeights());
271
272 // ; bb1: ; preds = %special-cases
273 // ; %sr_1 = add i32 %sr, 1
274 // ; %tmp2 = sub i32 31, %sr
275 // ; %q = shl i32 %dividend, %tmp2
276 // ; %skipLoop = icmp eq i32 %sr_1, 0
277 // ; br i1 %skipLoop, label %loop-exit, label %preheader
278 Builder.SetInsertPoint(BB1);
279 Value *SR_1 = Builder.CreateAdd(SR, One);
280 Value *Tmp2 = Builder.CreateSub(MSB, SR);
281 Value *Q = Builder.CreateShl(Dividend, Tmp2);
282 // We assume that in the common case, the dividend's magnitude is larger than
283 // the divisor's magnitude such that the loop counter (SR) is non-zero.
284 // Specifically, if |dividend| >= 2 * |divisor|, then SR >= 1, ensuring SR_1
285 // >= 2. The case where SR_1 == 0 is thus considered unlikely.
286 Value *SkipLoop = Builder.CreateICmpEQ(SR_1, Zero);
287 Value *ConBrBB1 = Builder.CreateCondBr(SkipLoop, LoopExit, Preheader);
288 if (auto *Inst = dyn_cast<Instruction>(ConBrBB1))
289 Inst->setMetadata(
290 LLVMContext::MD_prof,
291 MDBuilder(Inst->getContext()).createUnlikelyBranchWeights());
292
293 // ; preheader: ; preds = %bb1
294 // ; %tmp3 = lshr i32 %dividend, %sr_1
295 // ; %tmp4 = add i32 %divisor, -1
296 // ; br label %do-while
297 Builder.SetInsertPoint(Preheader);
298 Value *Tmp3 = Builder.CreateLShr(Dividend, SR_1);
299 Value *Tmp4 = Builder.CreateAdd(Divisor, NegOne);
300 Builder.CreateBr(DoWhile);
301
302 // ; do-while: ; preds = %do-while, %preheader
303 // ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
304 // ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
305 // ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
306 // ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
307 // ; %tmp5 = shl i32 %r_1, 1
308 // ; %tmp6 = lshr i32 %q_2, 31
309 // ; %tmp7 = or i32 %tmp5, %tmp6
310 // ; %tmp8 = shl i32 %q_2, 1
311 // ; %q_1 = or i32 %carry_1, %tmp8
312 // ; %tmp9 = sub i32 %tmp4, %tmp7
313 // ; %tmp10 = ashr i32 %tmp9, 31
314 // ; %carry = and i32 %tmp10, 1
315 // ; %tmp11 = and i32 %tmp10, %divisor
316 // ; %r = sub i32 %tmp7, %tmp11
317 // ; %sr_2 = add i32 %sr_3, -1
318 // ; %tmp12 = icmp eq i32 %sr_2, 0
319 // ; br i1 %tmp12, label %loop-exit, label %do-while
320 Builder.SetInsertPoint(DoWhile);
321 PHINode *Carry_1 = Builder.CreatePHI(DivTy, 2);
322 PHINode *SR_3 = Builder.CreatePHI(DivTy, 2);
323 PHINode *R_1 = Builder.CreatePHI(DivTy, 2);
324 PHINode *Q_2 = Builder.CreatePHI(DivTy, 2);
325 Value *Tmp5 = Builder.CreateShl(R_1, One);
326 Value *Tmp6 = Builder.CreateLShr(Q_2, MSB);
327 Value *Tmp7 = Builder.CreateOr(Tmp5, Tmp6);
328 Value *Tmp8 = Builder.CreateShl(Q_2, One);
329 Value *Q_1 = Builder.CreateOr(Carry_1, Tmp8);
330 Value *Tmp9 = Builder.CreateSub(Tmp4, Tmp7);
331 Value *Tmp10 = Builder.CreateAShr(Tmp9, MSB);
332 Value *Carry = Builder.CreateAnd(Tmp10, One);
333 Value *Tmp11 = Builder.CreateAnd(Tmp10, Divisor);
334 Value *R = Builder.CreateSub(Tmp7, Tmp11);
335 Value *SR_2 = Builder.CreateAdd(SR_3, NegOne);
336 Value *Tmp12 = Builder.CreateICmpEQ(SR_2, Zero);
337 // The loop implements the core bit-by-bit binary long division algorithm.
338 // The branch is unlikely to exit the loop early until it has processed all
339 // significant bits.
340 Value *ConBrDoWhile = Builder.CreateCondBr(Tmp12, LoopExit, DoWhile);
341 if (auto *Inst = dyn_cast<Instruction>(ConBrDoWhile))
342 Inst->setMetadata(
343 LLVMContext::MD_prof,
344 MDBuilder(Inst->getContext()).createUnlikelyBranchWeights());
345
346 // ; loop-exit: ; preds = %do-while, %bb1
347 // ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
348 // ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
349 // ; %tmp13 = shl i32 %q_3, 1
350 // ; %q_4 = or i32 %carry_2, %tmp13
351 // ; br label %end
352 Builder.SetInsertPoint(LoopExit);
353 PHINode *Carry_2 = Builder.CreatePHI(DivTy, 2);
354 PHINode *Q_3 = Builder.CreatePHI(DivTy, 2);
355 Value *Tmp13 = Builder.CreateShl(Q_3, One);
356 Value *Q_4 = Builder.CreateOr(Carry_2, Tmp13);
357 Builder.CreateBr(End);
358
359 // ; end: ; preds = %loop-exit, %special-cases
360 // ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
361 // ; ret i32 %q_5
362 Builder.SetInsertPoint(End, End->begin());
363 PHINode *Q_5 = Builder.CreatePHI(DivTy, 2);
364
365 // Populate the Phis, since all values have now been created. Our Phis were:
366 // ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
367 Carry_1->addIncoming(Zero, Preheader);
368 Carry_1->addIncoming(Carry, DoWhile);
369 // ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
370 SR_3->addIncoming(SR_1, Preheader);
371 SR_3->addIncoming(SR_2, DoWhile);
372 // ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
373 R_1->addIncoming(Tmp3, Preheader);
374 R_1->addIncoming(R, DoWhile);
375 // ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
376 Q_2->addIncoming(Q, Preheader);
377 Q_2->addIncoming(Q_1, DoWhile);
378 // ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
379 Carry_2->addIncoming(Zero, BB1);
380 Carry_2->addIncoming(Carry, DoWhile);
381 // ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
382 Q_3->addIncoming(Q, BB1);
383 Q_3->addIncoming(Q_1, DoWhile);
384 // ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
385 Q_5->addIncoming(Q_4, LoopExit);
386 Q_5->addIncoming(RetVal, SpecialCases);
387
388 return Q_5;
389}
390
391/// Generate code to calculate the remainder of two integers, replacing Rem with
392/// the generated code. This currently generates code using the udiv expansion,
393/// but future work includes generating more specialized code, e.g. when more
394/// information about the operands are known.
395///
396/// Replace Rem with generated code.
398 assert((Rem->getOpcode() == Instruction::SRem ||
399 Rem->getOpcode() == Instruction::URem) &&
400 "Trying to expand remainder from a non-remainder function");
401
402 IRBuilder<> Builder(Rem);
403
404 assert(!Rem->getType()->isVectorTy() && "Div over vectors not supported");
405
406 // First prepare the sign if it's a signed remainder
407 if (Rem->getOpcode() == Instruction::SRem) {
408 Value *Remainder = generateSignedRemainderCode(Rem->getOperand(0),
409 Rem->getOperand(1), Builder);
410
411 // Check whether this is the insert point while Rem is still valid.
412 bool IsInsertPoint = Rem->getIterator() == Builder.GetInsertPoint();
413 Rem->replaceAllUsesWith(Remainder);
414 Rem->dropAllReferences();
415 Rem->eraseFromParent();
416
417 // If we didn't actually generate an urem instruction, we're done
418 // This happens for example if the input were constant. In this case the
419 // Builder insertion point was unchanged
420 if (IsInsertPoint)
421 return true;
422
423 BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
424 Rem = BO;
425 }
426
428 Rem->getOperand(1), Builder);
429
430 Rem->replaceAllUsesWith(Remainder);
431 Rem->dropAllReferences();
432 Rem->eraseFromParent();
433
434 // Expand the udiv
435 if (BinaryOperator *UDiv = dyn_cast<BinaryOperator>(Builder.GetInsertPoint())) {
436 assert(UDiv->getOpcode() == Instruction::UDiv && "Non-udiv in expansion?");
437 expandDivision(UDiv);
438 }
439
440 return true;
441}
442
443/// Generate code to divide two integers, replacing Div with the generated
444/// code. This currently generates code similarly to compiler-rt's
445/// implementations, but future work includes generating more specialized code
446/// when more information about the operands are known.
447///
448/// Replace Div with generated code.
450 assert((Div->getOpcode() == Instruction::SDiv ||
451 Div->getOpcode() == Instruction::UDiv) &&
452 "Trying to expand division from a non-division function");
453
454 IRBuilder<> Builder(Div);
455
456 assert(!Div->getType()->isVectorTy() && "Div over vectors not supported");
457
458 // First prepare the sign if it's a signed division
459 if (Div->getOpcode() == Instruction::SDiv) {
460 // Lower the code to unsigned division, and reset Div to point to the udiv.
461 Value *Quotient = generateSignedDivisionCode(Div->getOperand(0),
462 Div->getOperand(1), Builder);
463
464 // Check whether this is the insert point while Div is still valid.
465 bool IsInsertPoint = Div->getIterator() == Builder.GetInsertPoint();
466 Div->replaceAllUsesWith(Quotient);
467 Div->dropAllReferences();
468 Div->eraseFromParent();
469
470 // If we didn't actually generate an udiv instruction, we're done
471 // This happens for example if the input were constant. In this case the
472 // Builder insertion point was unchanged
473 if (IsInsertPoint)
474 return true;
475
476 BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
477 Div = BO;
478 }
479
480 // Insert the unsigned division code
482 Div->getOperand(1),
483 Builder);
484 Div->replaceAllUsesWith(Quotient);
485 Div->dropAllReferences();
486 Div->eraseFromParent();
487
488 return true;
489}
490
491/// Generate code to compute the remainder of two integers of bitwidth up to
492/// 32 bits. Uses the above routines and extends the inputs/truncates the
493/// outputs to operate in 32 bits; that is, these routines are good for targets
494/// that have no or very little suppport for smaller than 32 bit integer
495/// arithmetic.
496///
497/// Replace Rem with emulation code.
499 assert((Rem->getOpcode() == Instruction::SRem ||
500 Rem->getOpcode() == Instruction::URem) &&
501 "Trying to expand remainder from a non-remainder function");
502
503 Type *RemTy = Rem->getType();
504 assert(!RemTy->isVectorTy() && "Div over vectors not supported");
505
506 unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
507
508 assert(RemTyBitWidth <= 32 &&
509 "Div of bitwidth greater than 32 not supported");
510
511 if (RemTyBitWidth == 32)
512 return expandRemainder(Rem);
513
514 // If bitwidth smaller than 32 extend inputs, extend output and proceed
515 // with 32 bit division.
516 IRBuilder<> Builder(Rem);
517
518 Value *ExtDividend;
519 Value *ExtDivisor;
520 Value *ExtRem;
521 Value *Trunc;
522 Type *Int32Ty = Builder.getInt32Ty();
523
524 if (Rem->getOpcode() == Instruction::SRem) {
525 ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int32Ty);
526 ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int32Ty);
527 ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
528 } else {
529 ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int32Ty);
530 ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int32Ty);
531 ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
532 }
533 Trunc = Builder.CreateTrunc(ExtRem, RemTy);
534
535 Rem->replaceAllUsesWith(Trunc);
536 Rem->dropAllReferences();
537 Rem->eraseFromParent();
538
540}
541
542/// Generate code to compute the remainder of two integers of bitwidth up to
543/// 64 bits. Uses the above routines and extends the inputs/truncates the
544/// outputs to operate in 64 bits.
545///
546/// Replace Rem with emulation code.
548 assert((Rem->getOpcode() == Instruction::SRem ||
549 Rem->getOpcode() == Instruction::URem) &&
550 "Trying to expand remainder from a non-remainder function");
551
552 Type *RemTy = Rem->getType();
553 assert(!RemTy->isVectorTy() && "Div over vectors not supported");
554
555 unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
556
557 if (RemTyBitWidth >= 64)
558 return expandRemainder(Rem);
559
560 // If bitwidth smaller than 64 extend inputs, extend output and proceed
561 // with 64 bit division.
562 IRBuilder<> Builder(Rem);
563
564 Value *ExtDividend;
565 Value *ExtDivisor;
566 Value *ExtRem;
567 Value *Trunc;
568 Type *Int64Ty = Builder.getInt64Ty();
569
570 if (Rem->getOpcode() == Instruction::SRem) {
571 ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int64Ty);
572 ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int64Ty);
573 ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
574 } else {
575 ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int64Ty);
576 ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int64Ty);
577 ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
578 }
579 Trunc = Builder.CreateTrunc(ExtRem, RemTy);
580
581 Rem->replaceAllUsesWith(Trunc);
582 Rem->dropAllReferences();
583 Rem->eraseFromParent();
584
586}
587
588/// Generate code to divide two integers of bitwidth up to 32 bits. Uses the
589/// above routines and extends the inputs/truncates the outputs to operate
590/// in 32 bits; that is, these routines are good for targets that have no
591/// or very little support for smaller than 32 bit integer arithmetic.
592///
593/// Replace Div with emulation code.
595 assert((Div->getOpcode() == Instruction::SDiv ||
596 Div->getOpcode() == Instruction::UDiv) &&
597 "Trying to expand division from a non-division function");
598
599 Type *DivTy = Div->getType();
600 assert(!DivTy->isVectorTy() && "Div over vectors not supported");
601
602 unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
603
604 assert(DivTyBitWidth <= 32 && "Div of bitwidth greater than 32 not supported");
605
606 if (DivTyBitWidth == 32)
607 return expandDivision(Div);
608
609 // If bitwidth smaller than 32 extend inputs, extend output and proceed
610 // with 32 bit division.
611 IRBuilder<> Builder(Div);
612
613 Value *ExtDividend;
614 Value *ExtDivisor;
615 Value *ExtDiv;
616 Value *Trunc;
617 Type *Int32Ty = Builder.getInt32Ty();
618
619 if (Div->getOpcode() == Instruction::SDiv) {
620 ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int32Ty);
621 ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int32Ty);
622 ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
623 } else {
624 ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int32Ty);
625 ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int32Ty);
626 ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);
627 }
628 Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
629
630 Div->replaceAllUsesWith(Trunc);
631 Div->dropAllReferences();
632 Div->eraseFromParent();
633
634 return expandDivision(cast<BinaryOperator>(ExtDiv));
635}
636
637/// Generate code to divide two integers of bitwidth up to 64 bits. Uses the
638/// above routines and extends the inputs/truncates the outputs to operate
639/// in 64 bits.
640///
641/// Replace Div with emulation code.
643 assert((Div->getOpcode() == Instruction::SDiv ||
644 Div->getOpcode() == Instruction::UDiv) &&
645 "Trying to expand division from a non-division function");
646
647 Type *DivTy = Div->getType();
648 assert(!DivTy->isVectorTy() && "Div over vectors not supported");
649
650 unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
651
652 if (DivTyBitWidth >= 64)
653 return expandDivision(Div);
654
655 // If bitwidth smaller than 64 extend inputs, extend output and proceed
656 // with 64 bit division.
657 IRBuilder<> Builder(Div);
658
659 Value *ExtDividend;
660 Value *ExtDivisor;
661 Value *ExtDiv;
662 Value *Trunc;
663 Type *Int64Ty = Builder.getInt64Ty();
664
665 if (Div->getOpcode() == Instruction::SDiv) {
666 ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int64Ty);
667 ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int64Ty);
668 ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
669 } else {
670 ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int64Ty);
671 ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int64Ty);
672 ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);
673 }
674 Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
675
676 Div->replaceAllUsesWith(Trunc);
677 Div->dropAllReferences();
678 Div->eraseFromParent();
679
680 return expandDivision(cast<BinaryOperator>(ExtDiv));
681}
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:446
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
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
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
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:2908
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
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:257
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
self_iterator getIterator()
Definition ilist_node.h:123
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
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
LLVM_ABI bool expandRemainderUpTo64Bits(BinaryOperator *Rem)
Generate code to calculate the remainder of two integers, replacing Rem with the generated code.
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.