1 //===- DemandedBits.cpp - Determine demanded bits -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements a demanded bits analysis. A demanded bit is one that
10 // contributes to a result; bits that are not demanded can be either zero or
11 // one without affecting control or data flow. For example in this sequence:
12 //
13 //   %1 = add i32 %x, %y
14 //   %2 = trunc i32 %1 to i16
15 //
16 // Only the lowest 16 bits of %1 are demanded; the rest are removed by the
17 // trunc.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "llvm/Analysis/DemandedBits.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/InstIterator.h"
33 #include "llvm/IR/InstrTypes.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/IR/PassManager.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Use.h"
43 #include "llvm/InitializePasses.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 using namespace llvm::PatternMatch;
54 
55 #define DEBUG_TYPE "demanded-bits"
56 
57 char DemandedBitsWrapperPass::ID = 0;
58 
59 INITIALIZE_PASS_BEGIN(DemandedBitsWrapperPass, "demanded-bits",
60                       "Demanded bits analysis", false, false)
61 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
62 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
63 INITIALIZE_PASS_END(DemandedBitsWrapperPass, "demanded-bits",
64                     "Demanded bits analysis", false, false)
65 
66 DemandedBitsWrapperPass::DemandedBitsWrapperPass() : FunctionPass(ID) {
67   initializeDemandedBitsWrapperPassPass(*PassRegistry::getPassRegistry());
68 }
69 
70 void DemandedBitsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
71   AU.setPreservesCFG();
72   AU.addRequired<AssumptionCacheTracker>();
73   AU.addRequired<DominatorTreeWrapperPass>();
74   AU.setPreservesAll();
75 }
76 
77 void DemandedBitsWrapperPass::print(raw_ostream &OS, const Module *M) const {
78   DB->print(OS);
79 }
80 
81 static bool isAlwaysLive(Instruction *I) {
82   return I->isTerminator() || isa<DbgInfoIntrinsic>(I) || I->isEHPad() ||
83          I->mayHaveSideEffects();
84 }
85 
86 void DemandedBits::determineLiveOperandBits(
87     const Instruction *UserI, const Value *Val, unsigned OperandNo,
88     const APInt &AOut, APInt &AB, KnownBits &Known, KnownBits &Known2,
89     bool &KnownBitsComputed) {
90   unsigned BitWidth = AB.getBitWidth();
91 
92   // We're called once per operand, but for some instructions, we need to
93   // compute known bits of both operands in order to determine the live bits of
94   // either (when both operands are instructions themselves). We don't,
95   // however, want to do this twice, so we cache the result in APInts that live
96   // in the caller. For the two-relevant-operands case, both operand values are
97   // provided here.
98   auto ComputeKnownBits =
99       [&](unsigned BitWidth, const Value *V1, const Value *V2) {
100         if (KnownBitsComputed)
101           return;
102         KnownBitsComputed = true;
103 
104         const DataLayout &DL = UserI->getModule()->getDataLayout();
105         Known = KnownBits(BitWidth);
106         computeKnownBits(V1, Known, DL, 0, &AC, UserI, &DT);
107 
108         if (V2) {
109           Known2 = KnownBits(BitWidth);
110           computeKnownBits(V2, Known2, DL, 0, &AC, UserI, &DT);
111         }
112       };
113 
114   switch (UserI->getOpcode()) {
115   default: break;
116   case Instruction::Call:
117   case Instruction::Invoke:
118     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(UserI))
119       switch (II->getIntrinsicID()) {
120       default: break;
121       case Intrinsic::bswap:
122         // The alive bits of the input are the swapped alive bits of
123         // the output.
124         AB = AOut.byteSwap();
125         break;
126       case Intrinsic::bitreverse:
127         // The alive bits of the input are the reversed alive bits of
128         // the output.
129         AB = AOut.reverseBits();
130         break;
131       case Intrinsic::ctlz:
132         if (OperandNo == 0) {
133           // We need some output bits, so we need all bits of the
134           // input to the left of, and including, the leftmost bit
135           // known to be one.
136           ComputeKnownBits(BitWidth, Val, nullptr);
137           AB = APInt::getHighBitsSet(BitWidth,
138                  std::min(BitWidth, Known.countMaxLeadingZeros()+1));
139         }
140         break;
141       case Intrinsic::cttz:
142         if (OperandNo == 0) {
143           // We need some output bits, so we need all bits of the
144           // input to the right of, and including, the rightmost bit
145           // known to be one.
146           ComputeKnownBits(BitWidth, Val, nullptr);
147           AB = APInt::getLowBitsSet(BitWidth,
148                  std::min(BitWidth, Known.countMaxTrailingZeros()+1));
149         }
150         break;
151       case Intrinsic::fshl:
152       case Intrinsic::fshr: {
153         const APInt *SA;
154         if (OperandNo == 2) {
155           // Shift amount is modulo the bitwidth. For powers of two we have
156           // SA % BW == SA & (BW - 1).
157           if (isPowerOf2_32(BitWidth))
158             AB = BitWidth - 1;
159         } else if (match(II->getOperand(2), m_APInt(SA))) {
160           // Normalize to funnel shift left. APInt shifts of BitWidth are well-
161           // defined, so no need to special-case zero shifts here.
162           uint64_t ShiftAmt = SA->urem(BitWidth);
163           if (II->getIntrinsicID() == Intrinsic::fshr)
164             ShiftAmt = BitWidth - ShiftAmt;
165 
166           if (OperandNo == 0)
167             AB = AOut.lshr(ShiftAmt);
168           else if (OperandNo == 1)
169             AB = AOut.shl(BitWidth - ShiftAmt);
170         }
171         break;
172       }
173       }
174     break;
175   case Instruction::Add:
176     if (AOut.isMask()) {
177       AB = AOut;
178     } else {
179       ComputeKnownBits(BitWidth, UserI->getOperand(0), UserI->getOperand(1));
180       AB = determineLiveOperandBitsAdd(OperandNo, AOut, Known, Known2);
181     }
182     break;
183   case Instruction::Sub:
184     if (AOut.isMask()) {
185       AB = AOut;
186     } else {
187       ComputeKnownBits(BitWidth, UserI->getOperand(0), UserI->getOperand(1));
188       AB = determineLiveOperandBitsSub(OperandNo, AOut, Known, Known2);
189     }
190     break;
191   case Instruction::Mul:
192     // Find the highest live output bit. We don't need any more input
193     // bits than that (adds, and thus subtracts, ripple only to the
194     // left).
195     AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
196     break;
197   case Instruction::Shl:
198     if (OperandNo == 0) {
199       const APInt *ShiftAmtC;
200       if (match(UserI->getOperand(1), m_APInt(ShiftAmtC))) {
201         uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
202         AB = AOut.lshr(ShiftAmt);
203 
204         // If the shift is nuw/nsw, then the high bits are not dead
205         // (because we've promised that they *must* be zero).
206         const ShlOperator *S = cast<ShlOperator>(UserI);
207         if (S->hasNoSignedWrap())
208           AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
209         else if (S->hasNoUnsignedWrap())
210           AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
211       }
212     }
213     break;
214   case Instruction::LShr:
215     if (OperandNo == 0) {
216       const APInt *ShiftAmtC;
217       if (match(UserI->getOperand(1), m_APInt(ShiftAmtC))) {
218         uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
219         AB = AOut.shl(ShiftAmt);
220 
221         // If the shift is exact, then the low bits are not dead
222         // (they must be zero).
223         if (cast<LShrOperator>(UserI)->isExact())
224           AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
225       }
226     }
227     break;
228   case Instruction::AShr:
229     if (OperandNo == 0) {
230       const APInt *ShiftAmtC;
231       if (match(UserI->getOperand(1), m_APInt(ShiftAmtC))) {
232         uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
233         AB = AOut.shl(ShiftAmt);
234         // Because the high input bit is replicated into the
235         // high-order bits of the result, if we need any of those
236         // bits, then we must keep the highest input bit.
237         if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
238             .getBoolValue())
239           AB.setSignBit();
240 
241         // If the shift is exact, then the low bits are not dead
242         // (they must be zero).
243         if (cast<AShrOperator>(UserI)->isExact())
244           AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
245       }
246     }
247     break;
248   case Instruction::And:
249     AB = AOut;
250 
251     // For bits that are known zero, the corresponding bits in the
252     // other operand are dead (unless they're both zero, 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.Zero;
258     else
259       AB &= ~(Known.Zero & ~Known2.Zero);
260     break;
261   case Instruction::Or:
262     AB = AOut;
263 
264     // For bits that are known one, the corresponding bits in the
265     // other operand are dead (unless they're both one, in which
266     // case they can't both be dead, so just mark the LHS bits as
267     // dead).
268     ComputeKnownBits(BitWidth, UserI->getOperand(0), UserI->getOperand(1));
269     if (OperandNo == 0)
270       AB &= ~Known2.One;
271     else
272       AB &= ~(Known.One & ~Known2.One);
273     break;
274   case Instruction::Xor:
275   case Instruction::PHI:
276     AB = AOut;
277     break;
278   case Instruction::Trunc:
279     AB = AOut.zext(BitWidth);
280     break;
281   case Instruction::ZExt:
282     AB = AOut.trunc(BitWidth);
283     break;
284   case Instruction::SExt:
285     AB = AOut.trunc(BitWidth);
286     // Because the high input bit is replicated into the
287     // high-order bits of the result, if we need any of those
288     // bits, then we must keep the highest input bit.
289     if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
290                                       AOut.getBitWidth() - BitWidth))
291         .getBoolValue())
292       AB.setSignBit();
293     break;
294   case Instruction::Select:
295     if (OperandNo != 0)
296       AB = AOut;
297     break;
298   case Instruction::ExtractElement:
299     if (OperandNo == 0)
300       AB = AOut;
301     break;
302   case Instruction::InsertElement:
303   case Instruction::ShuffleVector:
304     if (OperandNo == 0 || OperandNo == 1)
305       AB = AOut;
306     break;
307   }
308 }
309 
310 bool DemandedBitsWrapperPass::runOnFunction(Function &F) {
311   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
312   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
313   DB.emplace(F, AC, DT);
314   return false;
315 }
316 
317 void DemandedBitsWrapperPass::releaseMemory() {
318   DB.reset();
319 }
320 
321 void DemandedBits::performAnalysis() {
322   if (Analyzed)
323     // Analysis already completed for this function.
324     return;
325   Analyzed = true;
326 
327   Visited.clear();
328   AliveBits.clear();
329   DeadUses.clear();
330 
331   SmallSetVector<Instruction*, 16> Worklist;
332 
333   // Collect the set of "root" instructions that are known live.
334   for (Instruction &I : instructions(F)) {
335     if (!isAlwaysLive(&I))
336       continue;
337 
338     LLVM_DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
339     // For integer-valued instructions, set up an initial empty set of alive
340     // bits and add the instruction to the work list. For other instructions
341     // add their operands to the work list (for integer values operands, mark
342     // all bits as live).
343     Type *T = I.getType();
344     if (T->isIntOrIntVectorTy()) {
345       if (AliveBits.try_emplace(&I, T->getScalarSizeInBits(), 0).second)
346         Worklist.insert(&I);
347 
348       continue;
349     }
350 
351     // Non-integer-typed instructions...
352     for (Use &OI : I.operands()) {
353       if (Instruction *J = dyn_cast<Instruction>(OI)) {
354         Type *T = J->getType();
355         if (T->isIntOrIntVectorTy())
356           AliveBits[J] = APInt::getAllOnesValue(T->getScalarSizeInBits());
357         else
358           Visited.insert(J);
359         Worklist.insert(J);
360       }
361     }
362     // To save memory, we don't add I to the Visited set here. Instead, we
363     // check isAlwaysLive on every instruction when searching for dead
364     // instructions later (we need to check isAlwaysLive for the
365     // integer-typed instructions anyway).
366   }
367 
368   // Propagate liveness backwards to operands.
369   while (!Worklist.empty()) {
370     Instruction *UserI = Worklist.pop_back_val();
371 
372     LLVM_DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
373     APInt AOut;
374     bool InputIsKnownDead = false;
375     if (UserI->getType()->isIntOrIntVectorTy()) {
376       AOut = AliveBits[UserI];
377       LLVM_DEBUG(dbgs() << " Alive Out: 0x"
378                         << Twine::utohexstr(AOut.getLimitedValue()));
379 
380       // If all bits of the output are dead, then all bits of the input
381       // are also dead.
382       InputIsKnownDead = !AOut && !isAlwaysLive(UserI);
383     }
384     LLVM_DEBUG(dbgs() << "\n");
385 
386     KnownBits Known, Known2;
387     bool KnownBitsComputed = false;
388     // Compute the set of alive bits for each operand. These are anded into the
389     // existing set, if any, and if that changes the set of alive bits, the
390     // operand is added to the work-list.
391     for (Use &OI : UserI->operands()) {
392       // We also want to detect dead uses of arguments, but will only store
393       // demanded bits for instructions.
394       Instruction *I = dyn_cast<Instruction>(OI);
395       if (!I && !isa<Argument>(OI))
396         continue;
397 
398       Type *T = OI->getType();
399       if (T->isIntOrIntVectorTy()) {
400         unsigned BitWidth = T->getScalarSizeInBits();
401         APInt AB = APInt::getAllOnesValue(BitWidth);
402         if (InputIsKnownDead) {
403           AB = APInt(BitWidth, 0);
404         } else {
405           // Bits of each operand that are used to compute alive bits of the
406           // output are alive, all others are dead.
407           determineLiveOperandBits(UserI, OI, OI.getOperandNo(), AOut, AB,
408                                    Known, Known2, KnownBitsComputed);
409 
410           // Keep track of uses which have no demanded bits.
411           if (AB.isNullValue())
412             DeadUses.insert(&OI);
413           else
414             DeadUses.erase(&OI);
415         }
416 
417         if (I) {
418           // If we've added to the set of alive bits (or the operand has not
419           // been previously visited), then re-queue the operand to be visited
420           // again.
421           auto Res = AliveBits.try_emplace(I);
422           if (Res.second || (AB |= Res.first->second) != Res.first->second) {
423             Res.first->second = std::move(AB);
424             Worklist.insert(I);
425           }
426         }
427       } else if (I && Visited.insert(I).second) {
428         Worklist.insert(I);
429       }
430     }
431   }
432 }
433 
434 APInt DemandedBits::getDemandedBits(Instruction *I) {
435   performAnalysis();
436 
437   auto Found = AliveBits.find(I);
438   if (Found != AliveBits.end())
439     return Found->second;
440 
441   const DataLayout &DL = I->getModule()->getDataLayout();
442   return APInt::getAllOnesValue(
443       DL.getTypeSizeInBits(I->getType()->getScalarType()));
444 }
445 
446 bool DemandedBits::isInstructionDead(Instruction *I) {
447   performAnalysis();
448 
449   return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
450     !isAlwaysLive(I);
451 }
452 
453 bool DemandedBits::isUseDead(Use *U) {
454   // We only track integer uses, everything else is assumed live.
455   if (!(*U)->getType()->isIntOrIntVectorTy())
456     return false;
457 
458   // Uses by always-live instructions are never dead.
459   Instruction *UserI = cast<Instruction>(U->getUser());
460   if (isAlwaysLive(UserI))
461     return false;
462 
463   performAnalysis();
464   if (DeadUses.count(U))
465     return true;
466 
467   // If no output bits are demanded, no input bits are demanded and the use
468   // is dead. These uses might not be explicitly present in the DeadUses map.
469   if (UserI->getType()->isIntOrIntVectorTy()) {
470     auto Found = AliveBits.find(UserI);
471     if (Found != AliveBits.end() && Found->second.isNullValue())
472       return true;
473   }
474 
475   return false;
476 }
477 
478 void DemandedBits::print(raw_ostream &OS) {
479   performAnalysis();
480   for (auto &KV : AliveBits) {
481     OS << "DemandedBits: 0x" << Twine::utohexstr(KV.second.getLimitedValue())
482        << " for " << *KV.first << '\n';
483   }
484 }
485 
486 static APInt determineLiveOperandBitsAddCarry(unsigned OperandNo,
487                                               const APInt &AOut,
488                                               const KnownBits &LHS,
489                                               const KnownBits &RHS,
490                                               bool CarryZero, bool CarryOne) {
491   assert(!(CarryZero && CarryOne) &&
492          "Carry can't be zero and one at the same time");
493 
494   // The following check should be done by the caller, as it also indicates
495   // that LHS and RHS don't need to be computed.
496   //
497   // if (AOut.isMask())
498   //   return AOut;
499 
500   // Boundary bits' carry out is unaffected by their carry in.
501   APInt Bound = (LHS.Zero & RHS.Zero) | (LHS.One & RHS.One);
502 
503   // First, the alive carry bits are determined from the alive output bits:
504   // Let demand ripple to the right but only up to any set bit in Bound.
505   //   AOut         = -1----
506   //   Bound        = ----1-
507   //   ACarry&~AOut = --111-
508   APInt RBound = Bound.reverseBits();
509   APInt RAOut = AOut.reverseBits();
510   APInt RProp = RAOut + (RAOut | ~RBound);
511   APInt RACarry = RProp ^ ~RBound;
512   APInt ACarry = RACarry.reverseBits();
513 
514   // Then, the alive input bits are determined from the alive carry bits:
515   APInt NeededToMaintainCarryZero;
516   APInt NeededToMaintainCarryOne;
517   if (OperandNo == 0) {
518     NeededToMaintainCarryZero = LHS.Zero | ~RHS.Zero;
519     NeededToMaintainCarryOne = LHS.One | ~RHS.One;
520   } else {
521     NeededToMaintainCarryZero = RHS.Zero | ~LHS.Zero;
522     NeededToMaintainCarryOne = RHS.One | ~LHS.One;
523   }
524 
525   // As in computeForAddCarry
526   APInt PossibleSumZero = ~LHS.Zero + ~RHS.Zero + !CarryZero;
527   APInt PossibleSumOne = LHS.One + RHS.One + CarryOne;
528 
529   // The below is simplified from
530   //
531   // APInt CarryKnownZero = ~(PossibleSumZero ^ LHS.Zero ^ RHS.Zero);
532   // APInt CarryKnownOne = PossibleSumOne ^ LHS.One ^ RHS.One;
533   // APInt CarryUnknown = ~(CarryKnownZero | CarryKnownOne);
534   //
535   // APInt NeededToMaintainCarry =
536   //   (CarryKnownZero & NeededToMaintainCarryZero) |
537   //   (CarryKnownOne  & NeededToMaintainCarryOne) |
538   //   CarryUnknown;
539 
540   APInt NeededToMaintainCarry = (~PossibleSumZero | NeededToMaintainCarryZero) &
541                                 (PossibleSumOne | NeededToMaintainCarryOne);
542 
543   APInt AB = AOut | (ACarry & NeededToMaintainCarry);
544   return AB;
545 }
546 
547 APInt DemandedBits::determineLiveOperandBitsAdd(unsigned OperandNo,
548                                                 const APInt &AOut,
549                                                 const KnownBits &LHS,
550                                                 const KnownBits &RHS) {
551   return determineLiveOperandBitsAddCarry(OperandNo, AOut, LHS, RHS, true,
552                                           false);
553 }
554 
555 APInt DemandedBits::determineLiveOperandBitsSub(unsigned OperandNo,
556                                                 const APInt &AOut,
557                                                 const KnownBits &LHS,
558                                                 const KnownBits &RHS) {
559   KnownBits NRHS;
560   NRHS.Zero = RHS.One;
561   NRHS.One = RHS.Zero;
562   return determineLiveOperandBitsAddCarry(OperandNo, AOut, LHS, NRHS, false,
563                                           true);
564 }
565 
566 FunctionPass *llvm::createDemandedBitsWrapperPass() {
567   return new DemandedBitsWrapperPass();
568 }
569 
570 AnalysisKey DemandedBitsAnalysis::Key;
571 
572 DemandedBits DemandedBitsAnalysis::run(Function &F,
573                                              FunctionAnalysisManager &AM) {
574   auto &AC = AM.getResult<AssumptionAnalysis>(F);
575   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
576   return DemandedBits(F, AC, DT);
577 }
578 
579 PreservedAnalyses DemandedBitsPrinterPass::run(Function &F,
580                                                FunctionAnalysisManager &AM) {
581   AM.getResult<DemandedBitsAnalysis>(F).print(OS);
582   return PreservedAnalyses::all();
583 }
584