blob: ac18b7d5a058e4a111a0de600c1e3e0ab75d36be [file] [log] [blame]
Preston Gurd2e2efd92012-09-04 18:22:17 +00001//===-- BypassSlowDivision.cpp - Bypass slow 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 optimization for div and rem on architectures that
11// execute short instructions significantly faster than longer instructions.
12// For example, on Intel Atom 32-bit divides are slow enough that during
13// runtime it is profitable to check the value of the operands, and if they are
14// positive and less than 256 use an unsigned 8-bit divide.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "bypass-slow-division"
19#include "llvm/Instructions.h"
20#include "llvm/Function.h"
21#include "llvm/IRBuilder.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/Transforms/Utils/BypassSlowDivision.h"
24
25using namespace llvm;
26
Benjamin Kramer04142bc2012-09-10 11:52:08 +000027namespace {
Preston Gurd2e2efd92012-09-04 18:22:17 +000028 struct DivOpInfo {
29 bool SignedOp;
30 Value *Dividend;
31 Value *Divisor;
32
33 DivOpInfo(bool InSignedOp, Value *InDividend, Value *InDivisor)
34 : SignedOp(InSignedOp), Dividend(InDividend), Divisor(InDivisor) {}
35 };
36
37 struct DivPhiNodes {
38 PHINode *Quotient;
39 PHINode *Remainder;
40
41 DivPhiNodes(PHINode *InQuotient, PHINode *InRemainder)
42 : Quotient(InQuotient), Remainder(InRemainder) {}
43 };
Benjamin Kramer04142bc2012-09-10 11:52:08 +000044}
Preston Gurd2e2efd92012-09-04 18:22:17 +000045
Benjamin Kramer04142bc2012-09-10 11:52:08 +000046namespace llvm {
Preston Gurd2e2efd92012-09-04 18:22:17 +000047 template<>
48 struct DenseMapInfo<DivOpInfo> {
49 static bool isEqual(const DivOpInfo &Val1, const DivOpInfo &Val2) {
50 return Val1.SignedOp == Val2.SignedOp &&
51 Val1.Dividend == Val2.Dividend &&
52 Val1.Divisor == Val2.Divisor;
53 }
54
55 static DivOpInfo getEmptyKey() {
56 return DivOpInfo(false, 0, 0);
57 }
58
59 static DivOpInfo getTombstoneKey() {
60 return DivOpInfo(true, 0, 0);
61 }
62
63 static unsigned getHashValue(const DivOpInfo &Val) {
64 return (unsigned)(reinterpret_cast<uintptr_t>(Val.Dividend) ^
65 reinterpret_cast<uintptr_t>(Val.Divisor)) ^
Jakub Staszak7b2d20d2012-09-04 20:48:24 +000066 (unsigned)Val.SignedOp;
Preston Gurd2e2efd92012-09-04 18:22:17 +000067 }
68 };
69
70 typedef DenseMap<DivOpInfo, DivPhiNodes> DivCacheTy;
71}
72
73// insertFastDiv - Substitutes the div/rem instruction with code that checks the
74// value of the operands and uses a shorter-faster div/rem instruction when
75// possible and the longer-slower div/rem instruction otherwise.
Jakub Staszak7b2d20d2012-09-04 20:48:24 +000076static bool insertFastDiv(Function &F,
Preston Gurd2e2efd92012-09-04 18:22:17 +000077 Function::iterator &I,
78 BasicBlock::iterator &J,
79 IntegerType *BypassType,
80 bool UseDivOp,
81 bool UseSignedOp,
Jakub Staszak7b2d20d2012-09-04 20:48:24 +000082 DivCacheTy &PerBBDivCache) {
Preston Gurd2e2efd92012-09-04 18:22:17 +000083 // Get instruction operands
84 Instruction *Instr = J;
85 Value *Dividend = Instr->getOperand(0);
86 Value *Divisor = Instr->getOperand(1);
87
Jakub Staszak7b2d20d2012-09-04 20:48:24 +000088 if (isa<ConstantInt>(Divisor) ||
89 (isa<ConstantInt>(Dividend) && isa<ConstantInt>(Divisor))) {
Preston Gurd2e2efd92012-09-04 18:22:17 +000090 // Operations with immediate values should have
91 // been solved and replaced during compile time.
Jakub Staszak7b2d20d2012-09-04 20:48:24 +000092 return false;
Preston Gurd2e2efd92012-09-04 18:22:17 +000093 }
94
95 // Basic Block is split before divide
96 BasicBlock *MainBB = I;
97 BasicBlock *SuccessorBB = I->splitBasicBlock(J);
Jakub Staszak7b2d20d2012-09-04 20:48:24 +000098 ++I; //advance iterator I to successorBB
Preston Gurd2e2efd92012-09-04 18:22:17 +000099
100 // Add new basic block for slow divide operation
101 BasicBlock *SlowBB = BasicBlock::Create(F.getContext(), "",
102 MainBB->getParent(), SuccessorBB);
103 SlowBB->moveBefore(SuccessorBB);
104 IRBuilder<> SlowBuilder(SlowBB, SlowBB->begin());
105 Value *SlowQuotientV;
106 Value *SlowRemainderV;
107 if (UseSignedOp) {
108 SlowQuotientV = SlowBuilder.CreateSDiv(Dividend, Divisor);
109 SlowRemainderV = SlowBuilder.CreateSRem(Dividend, Divisor);
110 } else {
111 SlowQuotientV = SlowBuilder.CreateUDiv(Dividend, Divisor);
112 SlowRemainderV = SlowBuilder.CreateURem(Dividend, Divisor);
113 }
114 SlowBuilder.CreateBr(SuccessorBB);
115
116 // Add new basic block for fast divide operation
117 BasicBlock *FastBB = BasicBlock::Create(F.getContext(), "",
118 MainBB->getParent(), SuccessorBB);
119 FastBB->moveBefore(SlowBB);
120 IRBuilder<> FastBuilder(FastBB, FastBB->begin());
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000121 Value *ShortDivisorV = FastBuilder.CreateCast(Instruction::Trunc, Divisor,
122 BypassType);
123 Value *ShortDividendV = FastBuilder.CreateCast(Instruction::Trunc, Dividend,
124 BypassType);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000125
126 // udiv/urem because optimization only handles positive numbers
127 Value *ShortQuotientV = FastBuilder.CreateExactUDiv(ShortDividendV,
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000128 ShortDivisorV);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000129 Value *ShortRemainderV = FastBuilder.CreateURem(ShortDividendV,
130 ShortDivisorV);
131 Value *FastQuotientV = FastBuilder.CreateCast(Instruction::ZExt,
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000132 ShortQuotientV,
133 Dividend->getType());
Preston Gurd2e2efd92012-09-04 18:22:17 +0000134 Value *FastRemainderV = FastBuilder.CreateCast(Instruction::ZExt,
135 ShortRemainderV,
136 Dividend->getType());
137 FastBuilder.CreateBr(SuccessorBB);
138
139 // Phi nodes for result of div and rem
140 IRBuilder<> SuccessorBuilder(SuccessorBB, SuccessorBB->begin());
141 PHINode *QuoPhi = SuccessorBuilder.CreatePHI(Instr->getType(), 2);
142 QuoPhi->addIncoming(SlowQuotientV, SlowBB);
143 QuoPhi->addIncoming(FastQuotientV, FastBB);
144 PHINode *RemPhi = SuccessorBuilder.CreatePHI(Instr->getType(), 2);
145 RemPhi->addIncoming(SlowRemainderV, SlowBB);
146 RemPhi->addIncoming(FastRemainderV, FastBB);
147
148 // Replace Instr with appropriate phi node
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000149 if (UseDivOp)
Preston Gurd2e2efd92012-09-04 18:22:17 +0000150 Instr->replaceAllUsesWith(QuoPhi);
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000151 else
Preston Gurd2e2efd92012-09-04 18:22:17 +0000152 Instr->replaceAllUsesWith(RemPhi);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000153 Instr->eraseFromParent();
154
155 // Combine operands into a single value with OR for value testing below
156 MainBB->getInstList().back().eraseFromParent();
157 IRBuilder<> MainBuilder(MainBB, MainBB->end());
158 Value *OrV = MainBuilder.CreateOr(Dividend, Divisor);
159
160 // BitMask is inverted to check if the operands are
161 // larger than the bypass type
162 uint64_t BitMask = ~BypassType->getBitMask();
163 Value *AndV = MainBuilder.CreateAnd(OrV, BitMask);
164
165 // Compare operand values and branch
166 Value *ZeroV = MainBuilder.getInt32(0);
167 Value *CmpV = MainBuilder.CreateICmpEQ(AndV, ZeroV);
168 MainBuilder.CreateCondBr(CmpV, FastBB, SlowBB);
169
170 // point iterator J at first instruction of successorBB
171 J = I->begin();
172
173 // Cache phi nodes to be used later in place of other instances
174 // of div or rem with the same sign, dividend, and divisor
175 DivOpInfo Key(UseSignedOp, Dividend, Divisor);
176 DivPhiNodes Value(QuoPhi, RemPhi);
177 PerBBDivCache.insert(std::pair<DivOpInfo, DivPhiNodes>(Key, Value));
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000178 return true;
Preston Gurd2e2efd92012-09-04 18:22:17 +0000179}
180
181// reuseOrInsertFastDiv - Reuses previously computed dividend or remainder if
182// operands and operation are identical. Otherwise call insertFastDiv to perform
183// the optimization and cache the resulting dividend and remainder.
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000184static bool reuseOrInsertFastDiv(Function &F,
Preston Gurd2e2efd92012-09-04 18:22:17 +0000185 Function::iterator &I,
186 BasicBlock::iterator &J,
187 IntegerType *BypassType,
188 bool UseDivOp,
189 bool UseSignedOp,
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000190 DivCacheTy &PerBBDivCache) {
Preston Gurd2e2efd92012-09-04 18:22:17 +0000191 // Get instruction operands
192 Instruction *Instr = J;
193 DivOpInfo Key(UseSignedOp, Instr->getOperand(0), Instr->getOperand(1));
Jakub Staszakbe119912012-09-04 23:11:11 +0000194 DivCacheTy::iterator CacheI = PerBBDivCache.find(Key);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000195
196 if (CacheI == PerBBDivCache.end()) {
197 // If previous instance does not exist, insert fast div
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000198 return insertFastDiv(F, I, J, BypassType, UseDivOp, UseSignedOp,
199 PerBBDivCache);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000200 }
201
202 // Replace operation value with previously generated phi node
Jakub Staszakbe119912012-09-04 23:11:11 +0000203 DivPhiNodes &Value = CacheI->second;
Preston Gurd2e2efd92012-09-04 18:22:17 +0000204 if (UseDivOp) {
205 // Replace all uses of div instruction with quotient phi node
206 J->replaceAllUsesWith(Value.Quotient);
207 } else {
208 // Replace all uses of rem instruction with remainder phi node
209 J->replaceAllUsesWith(Value.Remainder);
210 }
211
212 // Advance to next operation
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000213 ++J;
Preston Gurd2e2efd92012-09-04 18:22:17 +0000214
215 // Remove redundant operation
216 Instr->eraseFromParent();
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000217 return true;
Preston Gurd2e2efd92012-09-04 18:22:17 +0000218}
219
220// bypassSlowDivision - This optimization identifies DIV instructions that can
221// be profitably bypassed and carried out with a shorter, faster divide.
Benjamin Kramer04142bc2012-09-10 11:52:08 +0000222bool llvm::bypassSlowDivision(Function &F,
223 Function::iterator &I,
Evan Cheng911908d2012-09-14 21:25:34 +0000224 const DenseMap<Type*, Type*> &BypassTypeMap) {
Preston Gurd2e2efd92012-09-04 18:22:17 +0000225 DivCacheTy DivCache;
226
227 bool MadeChange = false;
228 for (BasicBlock::iterator J = I->begin(); J != I->end(); J++) {
229
230 // Get instruction details
231 unsigned Opcode = J->getOpcode();
232 bool UseDivOp = Opcode == Instruction::SDiv || Opcode == Instruction::UDiv;
233 bool UseRemOp = Opcode == Instruction::SRem || Opcode == Instruction::URem;
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000234 bool UseSignedOp = Opcode == Instruction::SDiv ||
235 Opcode == Instruction::SRem;
Preston Gurd2e2efd92012-09-04 18:22:17 +0000236
237 // Only optimize div or rem ops
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000238 if (!UseDivOp && !UseRemOp)
Preston Gurd2e2efd92012-09-04 18:22:17 +0000239 continue;
Preston Gurd2e2efd92012-09-04 18:22:17 +0000240
Jakub Staszak7b2d20d2012-09-04 20:48:24 +0000241 // Continue if div/rem type is not bypassed
242 DenseMap<Type *, Type *>::const_iterator BT =
243 BypassTypeMap.find(J->getType());
244 if (BT == BypassTypeMap.end())
245 continue;
246
247 IntegerType *BypassType = cast<IntegerType>(BT->second);
248 MadeChange |= reuseOrInsertFastDiv(F, I, J, BypassType, UseDivOp,
249 UseSignedOp, DivCache);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000250 }
251
252 return MadeChange;
253}