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