7ca188145c0bfe64598feb0dbf20976789c38e6a
[oota-llvm.git] / lib / Analysis / DemandedBits.cpp
1 //===---- DemandedBits.cpp - Determine demanded bits -----------------------===//
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 pass implements a demanded bits analysis. A demanded bit is one that
11 // contributes to a result; bits that are not demanded can be either zero or
12 // one without affecting control or data flow. For example in this sequence:
13 //
14 //   %1 = add i32 %x, %y
15 //   %2 = trunc i32 %1 to i16
16 //
17 // Only the lowest 16 bits of %1 are demanded; the rest are removed by the
18 // trunc.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Analysis/DemandedBits.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Analysis/AssumptionCache.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/InstIterator.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 using namespace llvm;
43
44 #define DEBUG_TYPE "demanded-bits"
45
46 char DemandedBits::ID = 0;
47 INITIALIZE_PASS_BEGIN(DemandedBits, "demanded-bits", "Demanded bits analysis",
48                       false, false)
49 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
50 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
51 INITIALIZE_PASS_END(DemandedBits, "demanded-bits", "Demanded bits analysis",
52                         false, false)
53
54 DemandedBits::DemandedBits() : FunctionPass(ID) {
55   initializeDemandedBitsPass(*PassRegistry::getPassRegistry());
56 }
57
58 void DemandedBits::getAnalysisUsage(AnalysisUsage &AU) const {
59   AU.setPreservesCFG();
60   AU.addRequired<AssumptionCacheTracker>();
61   AU.addRequired<DominatorTreeWrapperPass>();
62   AU.setPreservesAll();
63 }
64
65 static bool isAlwaysLive(Instruction *I) {
66   return isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
67       I->isEHPad() || I->mayHaveSideEffects();
68 }
69
70 void
71 DemandedBits::determineLiveOperandBits(const Instruction *UserI,
72                                        const Instruction *I, unsigned OperandNo,
73                                        const APInt &AOut, APInt &AB,
74                                        APInt &KnownZero, APInt &KnownOne,
75                                        APInt &KnownZero2, APInt &KnownOne2) {
76   unsigned BitWidth = AB.getBitWidth();
77
78   // We're called once per operand, but for some instructions, we need to
79   // compute known bits of both operands in order to determine the live bits of
80   // either (when both operands are instructions themselves). We don't,
81   // however, want to do this twice, so we cache the result in APInts that live
82   // in the caller. For the two-relevant-operands case, both operand values are
83   // provided here.
84   auto ComputeKnownBits =
85       [&](unsigned BitWidth, const Value *V1, const Value *V2) {
86         const DataLayout &DL = I->getModule()->getDataLayout();
87         KnownZero = APInt(BitWidth, 0);
88         KnownOne = APInt(BitWidth, 0);
89         computeKnownBits(const_cast<Value *>(V1), KnownZero, KnownOne, DL, 0,
90                          AC, UserI, DT);
91
92         if (V2) {
93           KnownZero2 = APInt(BitWidth, 0);
94           KnownOne2 = APInt(BitWidth, 0);
95           computeKnownBits(const_cast<Value *>(V2), KnownZero2, KnownOne2, DL,
96                            0, AC, UserI, DT);
97         }
98       };
99
100   switch (UserI->getOpcode()) {
101   default: break;
102   case Instruction::Call:
103   case Instruction::Invoke:
104     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(UserI))
105       switch (II->getIntrinsicID()) {
106       default: break;
107       case Intrinsic::bswap:
108         // The alive bits of the input are the swapped alive bits of
109         // the output.
110         AB = AOut.byteSwap();
111         break;
112       case Intrinsic::ctlz:
113         if (OperandNo == 0) {
114           // We need some output bits, so we need all bits of the
115           // input to the left of, and including, the leftmost bit
116           // known to be one.
117           ComputeKnownBits(BitWidth, I, nullptr);
118           AB = APInt::getHighBitsSet(BitWidth,
119                  std::min(BitWidth, KnownOne.countLeadingZeros()+1));
120         }
121         break;
122       case Intrinsic::cttz:
123         if (OperandNo == 0) {
124           // We need some output bits, so we need all bits of the
125           // input to the right of, and including, the rightmost bit
126           // known to be one.
127           ComputeKnownBits(BitWidth, I, nullptr);
128           AB = APInt::getLowBitsSet(BitWidth,
129                  std::min(BitWidth, KnownOne.countTrailingZeros()+1));
130         }
131         break;
132       }
133     break;
134   case Instruction::Add:
135   case Instruction::Sub:
136     // Find the highest live output bit. We don't need any more input
137     // bits than that (adds, and thus subtracts, ripple only to the
138     // left).
139     AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
140     break;
141   case Instruction::Shl:
142     if (OperandNo == 0)
143       if (ConstantInt *CI =
144             dyn_cast<ConstantInt>(UserI->getOperand(1))) {
145         uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
146         AB = AOut.lshr(ShiftAmt);
147
148         // If the shift is nuw/nsw, then the high bits are not dead
149         // (because we've promised that they *must* be zero).
150         const ShlOperator *S = cast<ShlOperator>(UserI);
151         if (S->hasNoSignedWrap())
152           AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
153         else if (S->hasNoUnsignedWrap())
154           AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
155       }
156     break;
157   case Instruction::LShr:
158     if (OperandNo == 0)
159       if (ConstantInt *CI =
160             dyn_cast<ConstantInt>(UserI->getOperand(1))) {
161         uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
162         AB = AOut.shl(ShiftAmt);
163
164         // If the shift is exact, then the low bits are not dead
165         // (they must be zero).
166         if (cast<LShrOperator>(UserI)->isExact())
167           AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
168       }
169     break;
170   case Instruction::AShr:
171     if (OperandNo == 0)
172       if (ConstantInt *CI =
173             dyn_cast<ConstantInt>(UserI->getOperand(1))) {
174         uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
175         AB = AOut.shl(ShiftAmt);
176         // Because the high input bit is replicated into the
177         // high-order bits of the result, if we need any of those
178         // bits, then we must keep the highest input bit.
179         if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
180             .getBoolValue())
181           AB.setBit(BitWidth-1);
182
183         // If the shift is exact, then the low bits are not dead
184         // (they must be zero).
185         if (cast<AShrOperator>(UserI)->isExact())
186           AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
187       }
188     break;
189   case Instruction::And:
190     AB = AOut;
191
192     // For bits that are known zero, the corresponding bits in the
193     // other operand are dead (unless they're both zero, in which
194     // case they can't both be dead, so just mark the LHS bits as
195     // dead).
196     if (OperandNo == 0) {
197       ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
198       AB &= ~KnownZero2;
199     } else {
200       if (!isa<Instruction>(UserI->getOperand(0)))
201         ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
202       AB &= ~(KnownZero & ~KnownZero2);
203     }
204     break;
205   case Instruction::Or:
206     AB = AOut;
207
208     // For bits that are known one, the corresponding bits in the
209     // other operand are dead (unless they're both one, in which
210     // case they can't both be dead, so just mark the LHS bits as
211     // dead).
212     if (OperandNo == 0) {
213       ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
214       AB &= ~KnownOne2;
215     } else {
216       if (!isa<Instruction>(UserI->getOperand(0)))
217         ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
218       AB &= ~(KnownOne & ~KnownOne2);
219     }
220     break;
221   case Instruction::Xor:
222   case Instruction::PHI:
223     AB = AOut;
224     break;
225   case Instruction::Trunc:
226     AB = AOut.zext(BitWidth);
227     break;
228   case Instruction::ZExt:
229     AB = AOut.trunc(BitWidth);
230     break;
231   case Instruction::SExt:
232     AB = AOut.trunc(BitWidth);
233     // Because the high input bit is replicated into the
234     // high-order bits of the result, if we need any of those
235     // bits, then we must keep the highest input bit.
236     if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
237                                       AOut.getBitWidth() - BitWidth))
238         .getBoolValue())
239       AB.setBit(BitWidth-1);
240     break;
241   case Instruction::Select:
242     if (OperandNo != 0)
243       AB = AOut;
244     break;
245   }
246 }
247
248 bool DemandedBits::runOnFunction(Function& F) {
249   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
250   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
251
252   Visited.clear();
253   AliveBits.clear();
254
255   SmallVector<Instruction*, 128> Worklist;
256
257   // Collect the set of "root" instructions that are known live.
258   for (Instruction &I : instructions(F)) {
259     if (!isAlwaysLive(&I))
260       continue;
261
262     DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
263     // For integer-valued instructions, set up an initial empty set of alive
264     // bits and add the instruction to the work list. For other instructions
265     // add their operands to the work list (for integer values operands, mark
266     // all bits as live).
267     if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
268       if (!AliveBits.count(&I)) {
269         AliveBits[&I] = APInt(IT->getBitWidth(), 0);
270         Worklist.push_back(&I);
271       }
272
273       continue;
274     }
275
276     // Non-integer-typed instructions...
277     for (Use &OI : I.operands()) {
278       if (Instruction *J = dyn_cast<Instruction>(OI)) {
279         if (IntegerType *IT = dyn_cast<IntegerType>(J->getType()))
280           AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth());
281         Worklist.push_back(J);
282       }
283     }
284     // To save memory, we don't add I to the Visited set here. Instead, we
285     // check isAlwaysLive on every instruction when searching for dead
286     // instructions later (we need to check isAlwaysLive for the
287     // integer-typed instructions anyway).
288   }
289
290   // Propagate liveness backwards to operands.
291   while (!Worklist.empty()) {
292     Instruction *UserI = Worklist.pop_back_val();
293
294     DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
295     APInt AOut;
296     if (UserI->getType()->isIntegerTy()) {
297       AOut = AliveBits[UserI];
298       DEBUG(dbgs() << " Alive Out: " << AOut);
299     }
300     DEBUG(dbgs() << "\n");
301
302     if (!UserI->getType()->isIntegerTy())
303       Visited.insert(UserI);
304
305     APInt KnownZero, KnownOne, KnownZero2, KnownOne2;
306     // Compute the set of alive bits for each operand. These are anded into the
307     // existing set, if any, and if that changes the set of alive bits, the
308     // operand is added to the work-list.
309     for (Use &OI : UserI->operands()) {
310       if (Instruction *I = dyn_cast<Instruction>(OI)) {
311         if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) {
312           unsigned BitWidth = IT->getBitWidth();
313           APInt AB = APInt::getAllOnesValue(BitWidth);
314           if (UserI->getType()->isIntegerTy() && !AOut &&
315               !isAlwaysLive(UserI)) {
316             AB = APInt(BitWidth, 0);
317           } else {
318             // If all bits of the output are dead, then all bits of the input 
319             // Bits of each operand that are used to compute alive bits of the
320             // output are alive, all others are dead.
321             determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB,
322                                      KnownZero, KnownOne,
323                                      KnownZero2, KnownOne2);
324           }
325
326           // If we've added to the set of alive bits (or the operand has not
327           // been previously visited), then re-queue the operand to be visited
328           // again.
329           APInt ABPrev(BitWidth, 0);
330           auto ABI = AliveBits.find(I);
331           if (ABI != AliveBits.end())
332             ABPrev = ABI->second;
333
334           APInt ABNew = AB | ABPrev;
335           if (ABNew != ABPrev || ABI == AliveBits.end()) {
336             AliveBits[I] = std::move(ABNew);
337             Worklist.push_back(I);
338           }
339         } else if (!Visited.count(I)) {
340           Worklist.push_back(I);
341         }
342       }
343     }
344   }
345
346   return false;
347 }
348
349 APInt DemandedBits::getDemandedBits(Instruction *I) {
350   const DataLayout &DL = I->getParent()->getModule()->getDataLayout();
351   if (AliveBits.count(I))
352     return AliveBits[I];
353   return APInt::getAllOnesValue(DL.getTypeSizeInBits(I->getType()));
354 }
355
356 bool DemandedBits::isInstructionDead(Instruction *I) {
357   return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
358     !isAlwaysLive(I);
359 }
360
361 FunctionPass *llvm::createDemandedBitsPass() {
362   return new DemandedBits();
363 }