42 #define DEBUG_TYPE "bypass-slow-division" 50 QuotRemPair(
Value *InQuotient,
Value *InRemainder)
51 : Quotient(InQuotient), Remainder(InRemainder) {}
57 struct QuotRemWithBB {
59 Value *Quotient =
nullptr;
60 Value *Remainder =
nullptr;
77 class FastDivInsertionTask {
78 bool IsValidTask =
false;
83 bool isHashLikeValue(
Value *V, VisitedSetTy &Visited);
86 QuotRemWithBB createFastBB(
BasicBlock *Successor);
87 QuotRemPair createDivRemPhiNodes(QuotRemWithBB &LHS, QuotRemWithBB &RHS,
93 return SlowDivOrRem->
getOpcode() == Instruction::SDiv ||
94 SlowDivOrRem->
getOpcode() == Instruction::SRem;
98 return SlowDivOrRem->
getOpcode() == Instruction::SDiv ||
99 SlowDivOrRem->
getOpcode() == Instruction::UDiv;
102 Type *getSlowType() {
return SlowDivOrRem->
getType(); }
105 FastDivInsertionTask(
Instruction *
I,
const BypassWidthsTy &BypassWidths);
107 Value *getReplacement(DivCacheTy &Cache);
112 FastDivInsertionTask::FastDivInsertionTask(
Instruction *
I,
113 const BypassWidthsTy &BypassWidths) {
115 case Instruction::UDiv:
116 case Instruction::SDiv:
117 case Instruction::URem:
118 case Instruction::SRem:
132 auto BI = BypassWidths.find(SlowType->
getBitWidth());
133 if (BI == BypassWidths.end())
151 Value *FastDivInsertionTask::getReplacement(DivCacheTy &Cache) {
157 Value *Dividend = SlowDivOrRem->getOperand(0);
158 Value *Divisor = SlowDivOrRem->getOperand(1);
160 auto CacheI = Cache.find(Key);
162 if (CacheI == Cache.end()) {
168 CacheI = Cache.insert({
Key, *OptResult}).
first;
171 QuotRemPair &
Value = CacheI->second;
172 return isDivisionOp() ? Value.Quotient : Value.Remainder;
190 bool FastDivInsertionTask::isHashLikeValue(
Value *V, VisitedSetTy &Visited) {
196 case Instruction::Xor:
198 case Instruction::Mul: {
205 if (!C && isa<BitCastInst>(Op1))
206 C = dyn_cast<ConstantInt>(cast<BitCastInst>(Op1)->getOperand(0));
209 case Instruction::PHI:
212 if (Visited.size() >= 16)
216 if (Visited.find(I) != Visited.end())
222 return getValueRange(V, Visited) == VALRNG_LIKELY_LONG ||
232 VisitedSetTy &Visited) {
233 unsigned ShortLen = BypassType->getBitWidth();
236 assert(LongLen > ShortLen &&
"Value type must be wider than BypassType");
237 unsigned HiBits = LongLen - ShortLen;
239 const DataLayout &DL = SlowDivOrRem->getModule()->getDataLayout();
245 return VALRNG_KNOWN_SHORT;
248 return VALRNG_LIKELY_LONG;
254 if (isHashLikeValue(V, Visited))
255 return VALRNG_LIKELY_LONG;
257 return VALRNG_UNKNOWN;
262 QuotRemWithBB FastDivInsertionTask::createSlowBB(
BasicBlock *SuccessorBB) {
263 QuotRemWithBB DivRemPair;
265 MainBB->getParent(), SuccessorBB);
266 IRBuilder<> Builder(DivRemPair.BB, DivRemPair.BB->begin());
268 Value *Dividend = SlowDivOrRem->getOperand(0);
269 Value *Divisor = SlowDivOrRem->getOperand(1);
272 DivRemPair.Quotient = Builder.CreateSDiv(Dividend, Divisor);
273 DivRemPair.Remainder = Builder.CreateSRem(Dividend, Divisor);
275 DivRemPair.Quotient = Builder.CreateUDiv(Dividend, Divisor);
276 DivRemPair.Remainder = Builder.CreateURem(Dividend, Divisor);
279 Builder.CreateBr(SuccessorBB);
285 QuotRemWithBB FastDivInsertionTask::createFastBB(
BasicBlock *SuccessorBB) {
286 QuotRemWithBB DivRemPair;
288 MainBB->getParent(), SuccessorBB);
289 IRBuilder<> Builder(DivRemPair.BB, DivRemPair.BB->begin());
291 Value *Dividend = SlowDivOrRem->getOperand(0);
292 Value *Divisor = SlowDivOrRem->getOperand(1);
293 Value *ShortDivisorV =
294 Builder.CreateCast(Instruction::Trunc, Divisor, BypassType);
295 Value *ShortDividendV =
296 Builder.CreateCast(Instruction::Trunc, Dividend, BypassType);
299 Value *ShortQV = Builder.CreateUDiv(ShortDividendV, ShortDivisorV);
300 Value *ShortRV = Builder.CreateURem(ShortDividendV, ShortDivisorV);
301 DivRemPair.Quotient =
302 Builder.CreateCast(Instruction::ZExt, ShortQV, getSlowType());
303 DivRemPair.Remainder =
304 Builder.CreateCast(Instruction::ZExt, ShortRV, getSlowType());
305 Builder.CreateBr(SuccessorBB);
311 QuotRemPair FastDivInsertionTask::createDivRemPhiNodes(QuotRemWithBB &LHS,
315 PHINode *QuoPhi = Builder.CreatePHI(getSlowType(), 2);
316 QuoPhi->addIncoming(LHS.Quotient, LHS.BB);
317 QuoPhi->addIncoming(RHS.Quotient, RHS.BB);
318 PHINode *RemPhi = Builder.CreatePHI(getSlowType(), 2);
321 return QuotRemPair(QuoPhi, RemPhi);
328 Value *FastDivInsertionTask::insertOperandRuntimeCheck(
Value *Op1,
Value *Op2) {
329 assert((Op1 || Op2) &&
"Nothing to check");
336 OrV = Op1 ? Op1 : Op2;
340 uint64_t BitMask = ~BypassType->getBitMask();
341 Value *AndV = Builder.CreateAnd(OrV, BitMask);
345 return Builder.CreateICmpEQ(AndV, ZeroV);
351 Value *Dividend = SlowDivOrRem->getOperand(0);
352 Value *Divisor = SlowDivOrRem->getOperand(1);
355 ValueRange DividendRange = getValueRange(Dividend, SetL);
356 if (DividendRange == VALRNG_LIKELY_LONG)
360 ValueRange DivisorRange = getValueRange(Divisor, SetR);
361 if (DivisorRange == VALRNG_LIKELY_LONG)
364 bool DividendShort = (DividendRange == VALRNG_KNOWN_SHORT);
365 bool DivisorShort = (DivisorRange == VALRNG_KNOWN_SHORT);
367 if (DividendShort && DivisorShort) {
380 return QuotRemPair(ExtDiv, ExtRem);
383 if (isa<ConstantInt>(Divisor)) {
394 if (
auto *BCI = dyn_cast<BitCastInst>(Divisor))
395 if (BCI->getParent() == SlowDivOrRem->getParent() &&
396 isa<ConstantInt>(BCI->getOperand(0)))
418 Long.Remainder = Dividend;
419 QuotRemWithBB
Fast = createFastBB(SuccessorBB);
420 QuotRemPair Result = createDivRemPhiNodes(Fast, Long, SuccessorBB);
422 Value *CmpV = Builder.CreateICmpUGE(Dividend, Divisor);
423 Builder.CreateCondBr(CmpV, Fast.BB, SuccessorBB);
433 QuotRemWithBB
Fast = createFastBB(SuccessorBB);
434 QuotRemWithBB Slow = createSlowBB(SuccessorBB);
435 QuotRemPair Result = createDivRemPhiNodes(Fast, Slow, SuccessorBB);
436 Value *CmpV = insertOperandRuntimeCheck(DividendShort ?
nullptr : Dividend,
437 DivisorShort ?
nullptr : Divisor);
447 const BypassWidthsTy &BypassWidths) {
448 DivCacheTy PerBBDivCache;
450 bool MadeChange =
false;
452 while (Next !=
nullptr) {
462 FastDivInsertionTask Task(I, BypassWidths);
463 if (
Value *Replacement = Task.getReplacement(PerBBDivCache)) {
473 for (
auto &KV : PerBBDivCache)
474 for (
Value *V : {KV.second.Quotient, KV.second.Remainder})
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class represents lattice values for constants.
LLVMContext & getContext() const
All values hold a context through their type.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
iterator begin()
Instruction iterator methods.
bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
Type * getType() const
All values are typed, get the type of this value.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Value * getOperand(unsigned i) const
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
bool hasNUses(unsigned N) const
Return true if this Value has exactly N users.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Class to represent integer types.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
const InstListType & getInstList() const
Return the underlying instruction list container.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
This is the shared class of boolean and integer constants.
Module.h This file contains the declarations for the Module class.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateUDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
unsigned getIntegerBitWidth() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static int isSignedOp(ISD::CondCode Opcode)
For an integer comparison, return 1 if the comparison is a signed operation and 2 if the result is an...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
LLVM Value Representation.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
const BasicBlock * getParent() const