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/ADT/APInt.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/InstIterator.h"
35 #include "llvm/IR/InstrTypes.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/PassManager.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/Use.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/KnownBits.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cstdint>
51 
52 using namespace llvm;
53 
54 #define DEBUG_TYPE "demanded-bits"
55 
56 char DemandedBitsWrapperPass::ID = 0;
57 
58 INITIALIZE_PASS_BEGIN(DemandedBitsWrapperPass, "demanded-bits",
59                       "Demanded bits analysis", false, false)
60 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
61 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
62 INITIALIZE_PASS_END(DemandedBitsWrapperPass, "demanded-bits",
63                     "Demanded bits analysis", false, false)
64 
65 DemandedBitsWrapperPass::DemandedBitsWrapperPass() : FunctionPass(ID) {
66   initializeDemandedBitsWrapperPassPass(*PassRegistry::getPassRegistry());
67 }
68 
69 void DemandedBitsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
70   AU.setPreservesCFG();
71   AU.addRequired<AssumptionCacheTracker>();
72   AU.addRequired<DominatorTreeWrapperPass>();
73   AU.setPreservesAll();
74 }
75 
76 void DemandedBitsWrapperPass::print(raw_ostream &OS, const Module *M) const {
77   DB->print(OS);
78 }
79 
80 static bool isAlwaysLive(Instruction *I) {
81   return I->isTerminator() || isa<DbgInfoIntrinsic>(I) || I->isEHPad() ||
82          I->mayHaveSideEffects();
83 }
84 
85 void DemandedBits::determineLiveOperandBits(
86     const Instruction *UserI, const Instruction *I, unsigned OperandNo,
87     const APInt &AOut, APInt &AB, KnownBits &Known, KnownBits &Known2) {
88   unsigned BitWidth = AB.getBitWidth();
89 
90   // We're called once per operand, but for some instructions, we need to
91   // compute known bits of both operands in order to determine the live bits of
92   // either (when both operands are instructions themselves). We don't,
93   // however, want to do this twice, so we cache the result in APInts that live
94   // in the caller. For the two-relevant-operands case, both operand values are
95   // provided here.
96   auto ComputeKnownBits =
97       [&](unsigned BitWidth, const Value *V1, const Value *V2) {
98         const DataLayout &DL = I->getModule()->getDataLayout();
99         Known = KnownBits(BitWidth);
100         computeKnownBits(V1, Known, DL, 0, &AC, UserI, &DT);
101 
102         if (V2) {
103           Known2 = KnownBits(BitWidth);
104           computeKnownBits(V2, Known2, DL, 0, &AC, UserI, &DT);
105         }
106       };
107 
108   switch (UserI->getOpcode()) {
109   default: break;
110   case Instruction::Call:
111   case Instruction::Invoke:
112     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(UserI))
113       switch (II->getIntrinsicID()) {
114       default: break;
115       case Intrinsic::bswap:
116         // The alive bits of the input are the swapped alive bits of
117         // the output.
118         AB = AOut.byteSwap();
119         break;
120       case Intrinsic::bitreverse:
121         // The alive bits of the input are the reversed alive bits of
122         // the output.
123         AB = AOut.reverseBits();
124         break;
125       case Intrinsic::ctlz:
126         if (OperandNo == 0) {
127           // We need some output bits, so we need all bits of the
128           // input to the left of, and including, the leftmost bit
129           // known to be one.
130           ComputeKnownBits(BitWidth, I, nullptr);
131           AB = APInt::getHighBitsSet(BitWidth,
132                  std::min(BitWidth, Known.countMaxLeadingZeros()+1));
133         }
134         break;
135       case Intrinsic::cttz:
136         if (OperandNo == 0) {
137           // We need some output bits, so we need all bits of the
138           // input to the right of, and including, the rightmost bit
139           // known to be one.
140           ComputeKnownBits(BitWidth, I, nullptr);
141           AB = APInt::getLowBitsSet(BitWidth,
142                  std::min(BitWidth, Known.countMaxTrailingZeros()+1));
143         }
144         break;
145       case Intrinsic::fshl:
146       case Intrinsic::fshr:
147         if (OperandNo == 2) {
148           // Shift amount is modulo the bitwidth. For powers of two we have
149           // SA % BW == SA & (BW - 1).
150           if (isPowerOf2_32(BitWidth))
151             AB = BitWidth - 1;
152         } else if (auto *SA = dyn_cast<ConstantInt>(II->getOperand(2))) {
153           // TODO: Support vectors.
154           // Normalize to funnel shift left. APInt shifts of BitWidth are well-
155           // defined, so no need to special-case zero shifts here.
156           uint64_t ShiftAmt = SA->getValue().urem(BitWidth);
157           if (II->getIntrinsicID() == Intrinsic::fshr)
158             ShiftAmt = BitWidth - ShiftAmt;
159 
160           if (OperandNo == 0)
161             AB = AOut.lshr(ShiftAmt);
162           else if (OperandNo == 1)
163             AB = AOut.shl(BitWidth - ShiftAmt);
164         }
165         break;
166       }
167     break;
168   case Instruction::Add:
169   case Instruction::Sub:
170   case Instruction::Mul:
171     // Find the highest live output bit. We don't need any more input
172     // bits than that (adds, and thus subtracts, ripple only to the
173     // left).
174     AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
175     break;
176   case Instruction::Shl:
177     if (OperandNo == 0)
178       if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
179         uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
180         AB = AOut.lshr(ShiftAmt);
181 
182         // If the shift is nuw/nsw, then the high bits are not dead
183         // (because we've promised that they *must* be zero).
184         const ShlOperator *S = cast<ShlOperator>(UserI);
185         if (S->hasNoSignedWrap())
186           AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
187         else if (S->hasNoUnsignedWrap())
188           AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
189       }
190     break;
191   case Instruction::LShr:
192     if (OperandNo == 0)
193       if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
194         uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
195         AB = AOut.shl(ShiftAmt);
196 
197         // If the shift is exact, then the low bits are not dead
198         // (they must be zero).
199         if (cast<LShrOperator>(UserI)->isExact())
200           AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
201       }
202     break;
203   case Instruction::AShr:
204     if (OperandNo == 0)
205       if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
206         uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
207         AB = AOut.shl(ShiftAmt);
208         // Because the high input bit is replicated into the
209         // high-order bits of the result, if we need any of those
210         // bits, then we must keep the highest input bit.
211         if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
212             .getBoolValue())
213           AB.setSignBit();
214 
215         // If the shift is exact, then the low bits are not dead
216         // (they must be zero).
217         if (cast<AShrOperator>(UserI)->isExact())
218           AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
219       }
220     break;
221   case Instruction::And:
222     AB = AOut;
223 
224     // For bits that are known zero, the corresponding bits in the
225     // other operand are dead (unless they're both zero, in which
226     // case they can't both be dead, so just mark the LHS bits as
227     // dead).
228     if (OperandNo == 0) {
229       ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
230       AB &= ~Known2.Zero;
231     } else {
232       if (!isa<Instruction>(UserI->getOperand(0)))
233         ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
234       AB &= ~(Known.Zero & ~Known2.Zero);
235     }
236     break;
237   case Instruction::Or:
238     AB = AOut;
239 
240     // For bits that are known one, the corresponding bits in the
241     // other operand are dead (unless they're both one, in which
242     // case they can't both be dead, so just mark the LHS bits as
243     // dead).
244     if (OperandNo == 0) {
245       ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
246       AB &= ~Known2.One;
247     } else {
248       if (!isa<Instruction>(UserI->getOperand(0)))
249         ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
250       AB &= ~(Known.One & ~Known2.One);
251     }
252     break;
253   case Instruction::Xor:
254   case Instruction::PHI:
255     AB = AOut;
256     break;
257   case Instruction::Trunc:
258     AB = AOut.zext(BitWidth);
259     break;
260   case Instruction::ZExt:
261     AB = AOut.trunc(BitWidth);
262     break;
263   case Instruction::SExt:
264     AB = AOut.trunc(BitWidth);
265     // Because the high input bit is replicated into the
266     // high-order bits of the result, if we need any of those
267     // bits, then we must keep the highest input bit.
268     if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
269                                       AOut.getBitWidth() - BitWidth))
270         .getBoolValue())
271       AB.setSignBit();
272     break;
273   case Instruction::Select:
274     if (OperandNo != 0)
275       AB = AOut;
276     break;
277   }
278 }
279 
280 bool DemandedBitsWrapperPass::runOnFunction(Function &F) {
281   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
282   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
283   DB.emplace(F, AC, DT);
284   return false;
285 }
286 
287 void DemandedBitsWrapperPass::releaseMemory() {
288   DB.reset();
289 }
290 
291 void DemandedBits::performAnalysis() {
292   if (Analyzed)
293     // Analysis already completed for this function.
294     return;
295   Analyzed = true;
296 
297   Visited.clear();
298   AliveBits.clear();
299 
300   SmallVector<Instruction*, 128> Worklist;
301 
302   // Collect the set of "root" instructions that are known live.
303   for (Instruction &I : instructions(F)) {
304     if (!isAlwaysLive(&I))
305       continue;
306 
307     LLVM_DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
308     // For integer-valued instructions, set up an initial empty set of alive
309     // bits and add the instruction to the work list. For other instructions
310     // add their operands to the work list (for integer values operands, mark
311     // all bits as live).
312     if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
313       if (AliveBits.try_emplace(&I, IT->getBitWidth(), 0).second)
314         Worklist.push_back(&I);
315 
316       continue;
317     }
318 
319     // Non-integer-typed instructions...
320     for (Use &OI : I.operands()) {
321       if (Instruction *J = dyn_cast<Instruction>(OI)) {
322         if (IntegerType *IT = dyn_cast<IntegerType>(J->getType()))
323           AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth());
324         Worklist.push_back(J);
325       }
326     }
327     // To save memory, we don't add I to the Visited set here. Instead, we
328     // check isAlwaysLive on every instruction when searching for dead
329     // instructions later (we need to check isAlwaysLive for the
330     // integer-typed instructions anyway).
331   }
332 
333   // Propagate liveness backwards to operands.
334   while (!Worklist.empty()) {
335     Instruction *UserI = Worklist.pop_back_val();
336 
337     LLVM_DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
338     APInt AOut;
339     if (UserI->getType()->isIntegerTy()) {
340       AOut = AliveBits[UserI];
341       LLVM_DEBUG(dbgs() << " Alive Out: " << AOut);
342     }
343     LLVM_DEBUG(dbgs() << "\n");
344 
345     if (!UserI->getType()->isIntegerTy())
346       Visited.insert(UserI);
347 
348     KnownBits Known, Known2;
349     // Compute the set of alive bits for each operand. These are anded into the
350     // existing set, if any, and if that changes the set of alive bits, the
351     // operand is added to the work-list.
352     for (Use &OI : UserI->operands()) {
353       if (Instruction *I = dyn_cast<Instruction>(OI)) {
354         if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) {
355           unsigned BitWidth = IT->getBitWidth();
356           APInt AB = APInt::getAllOnesValue(BitWidth);
357           if (UserI->getType()->isIntegerTy() && !AOut &&
358               !isAlwaysLive(UserI)) {
359             AB = APInt(BitWidth, 0);
360           } else {
361             // If all bits of the output are dead, then all bits of the input
362             // Bits of each operand that are used to compute alive bits of the
363             // output are alive, all others are dead.
364             determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB,
365                                      Known, Known2);
366           }
367 
368           // If we've added to the set of alive bits (or the operand has not
369           // been previously visited), then re-queue the operand to be visited
370           // again.
371           APInt ABPrev(BitWidth, 0);
372           auto ABI = AliveBits.find(I);
373           if (ABI != AliveBits.end())
374             ABPrev = ABI->second;
375 
376           APInt ABNew = AB | ABPrev;
377           if (ABNew != ABPrev || ABI == AliveBits.end()) {
378             AliveBits[I] = std::move(ABNew);
379             Worklist.push_back(I);
380           }
381         } else if (!Visited.count(I)) {
382           Worklist.push_back(I);
383         }
384       }
385     }
386   }
387 }
388 
389 APInt DemandedBits::getDemandedBits(Instruction *I) {
390   performAnalysis();
391 
392   const DataLayout &DL = I->getModule()->getDataLayout();
393   auto Found = AliveBits.find(I);
394   if (Found != AliveBits.end())
395     return Found->second;
396   return APInt::getAllOnesValue(DL.getTypeSizeInBits(I->getType()));
397 }
398 
399 bool DemandedBits::isInstructionDead(Instruction *I) {
400   performAnalysis();
401 
402   return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
403     !isAlwaysLive(I);
404 }
405 
406 void DemandedBits::print(raw_ostream &OS) {
407   performAnalysis();
408   for (auto &KV : AliveBits) {
409     OS << "DemandedBits: 0x" << Twine::utohexstr(KV.second.getLimitedValue())
410        << " for " << *KV.first << '\n';
411   }
412 }
413 
414 FunctionPass *llvm::createDemandedBitsWrapperPass() {
415   return new DemandedBitsWrapperPass();
416 }
417 
418 AnalysisKey DemandedBitsAnalysis::Key;
419 
420 DemandedBits DemandedBitsAnalysis::run(Function &F,
421                                              FunctionAnalysisManager &AM) {
422   auto &AC = AM.getResult<AssumptionAnalysis>(F);
423   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
424   return DemandedBits(F, AC, DT);
425 }
426 
427 PreservedAnalyses DemandedBitsPrinterPass::run(Function &F,
428                                                FunctionAnalysisManager &AM) {
429   AM.getResult<DemandedBitsAnalysis>(F).print(OS);
430   return PreservedAnalyses::all();
431 }
432