LLVM  4.0.0
DemandedBits.cpp
Go to the documentation of this file.
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 
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CFG.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/InstIterator.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Debug.h"
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "demanded-bits"
44 
47  "Demanded bits analysis", false, false)
51  "Demanded bits analysis", false, false)
52 
53 DemandedBitsWrapperPass::DemandedBitsWrapperPass() : FunctionPass(ID) {
55 }
56 
58  AU.setPreservesCFG();
61  AU.setPreservesAll();
62 }
63 
65  DB->print(OS);
66 }
67 
68 static bool isAlwaysLive(Instruction *I) {
69  return isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
70  I->isEHPad() || I->mayHaveSideEffects();
71 }
72 
73 void DemandedBits::determineLiveOperandBits(
74  const Instruction *UserI, const Instruction *I, unsigned OperandNo,
75  const APInt &AOut, APInt &AB, APInt &KnownZero, APInt &KnownOne,
76  APInt &KnownZero2, APInt &KnownOne2) {
77  unsigned BitWidth = AB.getBitWidth();
78 
79  // We're called once per operand, but for some instructions, we need to
80  // compute known bits of both operands in order to determine the live bits of
81  // either (when both operands are instructions themselves). We don't,
82  // however, want to do this twice, so we cache the result in APInts that live
83  // in the caller. For the two-relevant-operands case, both operand values are
84  // provided here.
85  auto ComputeKnownBits =
86  [&](unsigned BitWidth, const Value *V1, const Value *V2) {
87  const DataLayout &DL = I->getModule()->getDataLayout();
88  KnownZero = APInt(BitWidth, 0);
89  KnownOne = APInt(BitWidth, 0);
90  computeKnownBits(const_cast<Value *>(V1), KnownZero, KnownOne, DL, 0,
91  &AC, UserI, &DT);
92 
93  if (V2) {
94  KnownZero2 = APInt(BitWidth, 0);
95  KnownOne2 = APInt(BitWidth, 0);
96  computeKnownBits(const_cast<Value *>(V2), KnownZero2, KnownOne2, DL,
97  0, &AC, UserI, &DT);
98  }
99  };
100 
101  switch (UserI->getOpcode()) {
102  default: break;
103  case Instruction::Call:
104  case Instruction::Invoke:
105  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(UserI))
106  switch (II->getIntrinsicID()) {
107  default: break;
108  case Intrinsic::bswap:
109  // The alive bits of the input are the swapped alive bits of
110  // the output.
111  AB = AOut.byteSwap();
112  break;
113  case Intrinsic::ctlz:
114  if (OperandNo == 0) {
115  // We need some output bits, so we need all bits of the
116  // input to the left of, and including, the leftmost bit
117  // known to be one.
118  ComputeKnownBits(BitWidth, I, nullptr);
119  AB = APInt::getHighBitsSet(BitWidth,
120  std::min(BitWidth, KnownOne.countLeadingZeros()+1));
121  }
122  break;
123  case Intrinsic::cttz:
124  if (OperandNo == 0) {
125  // We need some output bits, so we need all bits of the
126  // input to the right of, and including, the rightmost bit
127  // known to be one.
128  ComputeKnownBits(BitWidth, I, nullptr);
129  AB = APInt::getLowBitsSet(BitWidth,
130  std::min(BitWidth, KnownOne.countTrailingZeros()+1));
131  }
132  break;
133  }
134  break;
135  case Instruction::Add:
136  case Instruction::Sub:
137  case Instruction::Mul:
138  // Find the highest live output bit. We don't need any more input
139  // bits than that (adds, and thus subtracts, ripple only to the
140  // left).
141  AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
142  break;
143  case Instruction::Shl:
144  if (OperandNo == 0)
145  if (ConstantInt *CI =
146  dyn_cast<ConstantInt>(UserI->getOperand(1))) {
147  uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
148  AB = AOut.lshr(ShiftAmt);
149 
150  // If the shift is nuw/nsw, then the high bits are not dead
151  // (because we've promised that they *must* be zero).
152  const ShlOperator *S = cast<ShlOperator>(UserI);
153  if (S->hasNoSignedWrap())
154  AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
155  else if (S->hasNoUnsignedWrap())
156  AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
157  }
158  break;
159  case Instruction::LShr:
160  if (OperandNo == 0)
161  if (ConstantInt *CI =
162  dyn_cast<ConstantInt>(UserI->getOperand(1))) {
163  uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
164  AB = AOut.shl(ShiftAmt);
165 
166  // If the shift is exact, then the low bits are not dead
167  // (they must be zero).
168  if (cast<LShrOperator>(UserI)->isExact())
169  AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
170  }
171  break;
172  case Instruction::AShr:
173  if (OperandNo == 0)
174  if (ConstantInt *CI =
175  dyn_cast<ConstantInt>(UserI->getOperand(1))) {
176  uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
177  AB = AOut.shl(ShiftAmt);
178  // Because the high input bit is replicated into the
179  // high-order bits of the result, if we need any of those
180  // bits, then we must keep the highest input bit.
181  if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
182  .getBoolValue())
183  AB.setBit(BitWidth-1);
184 
185  // If the shift is exact, then the low bits are not dead
186  // (they must be zero).
187  if (cast<AShrOperator>(UserI)->isExact())
188  AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
189  }
190  break;
191  case Instruction::And:
192  AB = AOut;
193 
194  // For bits that are known zero, the corresponding bits in the
195  // other operand are dead (unless they're both zero, in which
196  // case they can't both be dead, so just mark the LHS bits as
197  // dead).
198  if (OperandNo == 0) {
199  ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
200  AB &= ~KnownZero2;
201  } else {
202  if (!isa<Instruction>(UserI->getOperand(0)))
203  ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
204  AB &= ~(KnownZero & ~KnownZero2);
205  }
206  break;
207  case Instruction::Or:
208  AB = AOut;
209 
210  // For bits that are known one, the corresponding bits in the
211  // other operand are dead (unless they're both one, in which
212  // case they can't both be dead, so just mark the LHS bits as
213  // dead).
214  if (OperandNo == 0) {
215  ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
216  AB &= ~KnownOne2;
217  } else {
218  if (!isa<Instruction>(UserI->getOperand(0)))
219  ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
220  AB &= ~(KnownOne & ~KnownOne2);
221  }
222  break;
223  case Instruction::Xor:
224  case Instruction::PHI:
225  AB = AOut;
226  break;
227  case Instruction::Trunc:
228  AB = AOut.zext(BitWidth);
229  break;
230  case Instruction::ZExt:
231  AB = AOut.trunc(BitWidth);
232  break;
233  case Instruction::SExt:
234  AB = AOut.trunc(BitWidth);
235  // Because the high input bit is replicated into the
236  // high-order bits of the result, if we need any of those
237  // bits, then we must keep the highest input bit.
238  if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
239  AOut.getBitWidth() - BitWidth))
240  .getBoolValue())
241  AB.setBit(BitWidth-1);
242  break;
243  case Instruction::Select:
244  if (OperandNo != 0)
245  AB = AOut;
246  break;
247  }
248 }
249 
251  auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
252  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
253  DB.emplace(F, AC, DT);
254  return false;
255 }
256 
258  DB.reset();
259 }
260 
261 void DemandedBits::performAnalysis() {
262  if (Analyzed)
263  // Analysis already completed for this function.
264  return;
265  Analyzed = true;
266 
267  Visited.clear();
268  AliveBits.clear();
269 
271 
272  // Collect the set of "root" instructions that are known live.
273  for (Instruction &I : instructions(F)) {
274  if (!isAlwaysLive(&I))
275  continue;
276 
277  DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
278  // For integer-valued instructions, set up an initial empty set of alive
279  // bits and add the instruction to the work list. For other instructions
280  // add their operands to the work list (for integer values operands, mark
281  // all bits as live).
282  if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
283  if (AliveBits.try_emplace(&I, IT->getBitWidth(), 0).second)
284  Worklist.push_back(&I);
285 
286  continue;
287  }
288 
289  // Non-integer-typed instructions...
290  for (Use &OI : I.operands()) {
291  if (Instruction *J = dyn_cast<Instruction>(OI)) {
292  if (IntegerType *IT = dyn_cast<IntegerType>(J->getType()))
293  AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth());
294  Worklist.push_back(J);
295  }
296  }
297  // To save memory, we don't add I to the Visited set here. Instead, we
298  // check isAlwaysLive on every instruction when searching for dead
299  // instructions later (we need to check isAlwaysLive for the
300  // integer-typed instructions anyway).
301  }
302 
303  // Propagate liveness backwards to operands.
304  while (!Worklist.empty()) {
305  Instruction *UserI = Worklist.pop_back_val();
306 
307  DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
308  APInt AOut;
309  if (UserI->getType()->isIntegerTy()) {
310  AOut = AliveBits[UserI];
311  DEBUG(dbgs() << " Alive Out: " << AOut);
312  }
313  DEBUG(dbgs() << "\n");
314 
315  if (!UserI->getType()->isIntegerTy())
316  Visited.insert(UserI);
317 
318  APInt KnownZero, KnownOne, KnownZero2, KnownOne2;
319  // Compute the set of alive bits for each operand. These are anded into the
320  // existing set, if any, and if that changes the set of alive bits, the
321  // operand is added to the work-list.
322  for (Use &OI : UserI->operands()) {
323  if (Instruction *I = dyn_cast<Instruction>(OI)) {
324  if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) {
325  unsigned BitWidth = IT->getBitWidth();
326  APInt AB = APInt::getAllOnesValue(BitWidth);
327  if (UserI->getType()->isIntegerTy() && !AOut &&
328  !isAlwaysLive(UserI)) {
329  AB = APInt(BitWidth, 0);
330  } else {
331  // If all bits of the output are dead, then all bits of the input
332  // Bits of each operand that are used to compute alive bits of the
333  // output are alive, all others are dead.
334  determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB,
335  KnownZero, KnownOne,
336  KnownZero2, KnownOne2);
337  }
338 
339  // If we've added to the set of alive bits (or the operand has not
340  // been previously visited), then re-queue the operand to be visited
341  // again.
342  APInt ABPrev(BitWidth, 0);
343  auto ABI = AliveBits.find(I);
344  if (ABI != AliveBits.end())
345  ABPrev = ABI->second;
346 
347  APInt ABNew = AB | ABPrev;
348  if (ABNew != ABPrev || ABI == AliveBits.end()) {
349  AliveBits[I] = std::move(ABNew);
350  Worklist.push_back(I);
351  }
352  } else if (!Visited.count(I)) {
353  Worklist.push_back(I);
354  }
355  }
356  }
357  }
358 }
359 
361  performAnalysis();
362 
363  const DataLayout &DL = I->getParent()->getModule()->getDataLayout();
364  auto Found = AliveBits.find(I);
365  if (Found != AliveBits.end())
366  return Found->second;
368 }
369 
371  performAnalysis();
372 
373  return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
374  !isAlwaysLive(I);
375 }
376 
378  performAnalysis();
379  for (auto &KV : AliveBits) {
380  OS << "DemandedBits: 0x" << utohexstr(KV.second.getLimitedValue()) << " for "
381  << *KV.first << "\n";
382  }
383 }
384 
386  return new DemandedBitsWrapperPass();
387 }
388 
389 AnalysisKey DemandedBitsAnalysis::Key;
390 
393  auto &AC = AM.getResult<AssumptionAnalysis>(F);
394  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
395  return DemandedBits(F, AC, DT);
396 }
397 
400  AM.getResult<DemandedBitsAnalysis>(F).print(OS);
401  return PreservedAnalyses::all();
402 }
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT,"arm-default-it","Generate IT block based on arch"), clEnumValN(RestrictedIT,"arm-restrict-it","Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT,"arm-no-restrict-it","Allow IT blocks based on ARMv7")))
void computeKnownBits(const Value *V, APInt &KnownZero, APInt &KnownOne, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:102
void initializeDemandedBitsWrapperPassPass(PassRegistry &)
APInt byteSwap() const
Definition: APInt.cpp:744
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:458
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
bool isInstructionDead(Instruction *I)
Return true if, during analysis, I could not be reached.
void setBit(unsigned bitPosition)
Set a given bit to 1.
Definition: APInt.cpp:553
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
Definition: Operator.h:104
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Definition: APInt.h:536
An immutable pass that tracks lazily created AssumptionCache objects.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:450
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
Definition: APInt.h:409
demanded bits
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:189
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:53
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
Definition: BasicBlock.cpp:116
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.cpp:1122
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
An analysis that produces DemandedBits for a function.
Definition: DemandedBits.h:90
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:850
#define F(x, y, z)
Definition: MD5.cpp:51
demanded Demanded bits false
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1279
DemandedBits run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce demanded bits information.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with etc Experimental Use value profile to guide fuzzing Number of simultaneous worker processes to run the jobs If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
Definition: APInt.h:518
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:916
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:653
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
Definition: APInt.h:1947
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Definition: APInt.h:1952
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1255
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
Value * getOperand(unsigned i) const
Definition: User.h:145
op_range operands()
Definition: User.h:213
Class to represent integer types.
Definition: DerivedTypes.h:39
demanded Demanded bits analysis
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
Definition: APInt.cpp:703
A function analysis which provides an AssumptionCache.
INITIALIZE_PASS_BEGIN(DemandedBitsWrapperPass,"demanded-bits","Demanded bits analysis", false, false) INITIALIZE_PASS_END(DemandedBitsWrapperPass
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This is the shared class of boolean and integer constants.
Definition: Constants.h:88
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:58
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:382
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:276
APInt getDemandedBits(Instruction *I)
Return the bits demanded from instruction I.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Class for arbitrary precision integers.
Definition: APInt.h:77
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:195
void setPreservesAll()
Set by analyses that do not transform their input at all.
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
Definition: APInt.h:1942
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Definition: Instruction.h:453
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:384
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
#define I(x, y, z)
Definition: MD5.cpp:54
static std::string utohexstr(uint64_t X, bool LowerCase=false)
Definition: StringExtras.h:48
LLVM Value Representation.
Definition: Value.h:71
static bool isAlwaysLive(Instruction *I)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:111
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:533
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
#define DEBUG(X)
Definition: Debug.h:100
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
Definition: APInt.h:1343
inst_range instructions(Function *F)
Definition: InstIterator.h:132
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:980
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:217
FunctionPass * createDemandedBitsWrapperPass()
Create a demanded bits analysis pass.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:64
const BasicBlock * getParent() const
Definition: Instruction.h:62
void releaseMemory() override
Clean up memory in between runs.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property...
Definition: Operator.h:98
void print(raw_ostream &OS)
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44