blob: 35af4be485f821f3320e583b0ed262aef18480d7 [file] [log] [blame]
Eugene Zelenko38c02bc2017-07-21 21:37:46 +00001//===- DemandedBits.cpp - Determine demanded bits -------------------------===//
James Molloy87405c72015-08-14 11:09:09 +00002//
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"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000023#include "llvm/ADT/APInt.h"
James Molloy87405c72015-08-14 11:09:09 +000024#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallVector.h"
James Molloybcd7f0a2015-10-08 12:39:59 +000026#include "llvm/ADT/StringExtras.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000027#include "llvm/Analysis/AssumptionCache.h"
James Molloy87405c72015-08-14 11:09:09 +000028#include "llvm/Analysis/ValueTracking.h"
29#include "llvm/IR/BasicBlock.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000030#include "llvm/IR/Constants.h"
James Molloy87405c72015-08-14 11:09:09 +000031#include "llvm/IR/DataLayout.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000032#include "llvm/IR/DerivedTypes.h"
James Molloy87405c72015-08-14 11:09:09 +000033#include "llvm/IR/Dominators.h"
34#include "llvm/IR/InstIterator.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000035#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
James Molloy87405c72015-08-14 11:09:09 +000037#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000038#include "llvm/IR/Intrinsics.h"
James Molloy87405c72015-08-14 11:09:09 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000041#include "llvm/IR/PassManager.h"
42#include "llvm/IR/Type.h"
43#include "llvm/IR/Use.h"
James Molloy87405c72015-08-14 11:09:09 +000044#include "llvm/Pass.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000045#include "llvm/Support/Casting.h"
James Molloy87405c72015-08-14 11:09:09 +000046#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000047#include "llvm/Support/KnownBits.h"
James Molloy87405c72015-08-14 11:09:09 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000049#include <algorithm>
50#include <cstdint>
51
James Molloy87405c72015-08-14 11:09:09 +000052using namespace llvm;
53
54#define DEBUG_TYPE "demanded-bits"
55
Michael Kupersteinde16b442016-04-18 23:55:01 +000056char DemandedBitsWrapperPass::ID = 0;
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000057
Michael Kupersteinde16b442016-04-18 23:55:01 +000058INITIALIZE_PASS_BEGIN(DemandedBitsWrapperPass, "demanded-bits",
59 "Demanded bits analysis", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000060INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
James Molloy87405c72015-08-14 11:09:09 +000061INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Michael Kupersteinde16b442016-04-18 23:55:01 +000062INITIALIZE_PASS_END(DemandedBitsWrapperPass, "demanded-bits",
63 "Demanded bits analysis", false, false)
James Molloy87405c72015-08-14 11:09:09 +000064
Michael Kupersteinde16b442016-04-18 23:55:01 +000065DemandedBitsWrapperPass::DemandedBitsWrapperPass() : FunctionPass(ID) {
66 initializeDemandedBitsWrapperPassPass(*PassRegistry::getPassRegistry());
James Molloy87405c72015-08-14 11:09:09 +000067}
68
Michael Kupersteinde16b442016-04-18 23:55:01 +000069void DemandedBitsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
James Molloy87405c72015-08-14 11:09:09 +000070 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +000071 AU.addRequired<AssumptionCacheTracker>();
James Molloy87405c72015-08-14 11:09:09 +000072 AU.addRequired<DominatorTreeWrapperPass>();
73 AU.setPreservesAll();
74}
75
Michael Kupersteinde16b442016-04-18 23:55:01 +000076void DemandedBitsWrapperPass::print(raw_ostream &OS, const Module *M) const {
77 DB->print(OS);
78}
79
James Molloy87405c72015-08-14 11:09:09 +000080static bool isAlwaysLive(Instruction *I) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +000081 return I->isTerminator() || isa<DbgInfoIntrinsic>(I) || I->isEHPad() ||
82 I->mayHaveSideEffects();
James Molloy87405c72015-08-14 11:09:09 +000083}
84
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +000085void DemandedBits::determineLiveOperandBits(
86 const Instruction *UserI, const Instruction *I, unsigned OperandNo,
Craig Topperb45eabc2017-04-26 16:39:58 +000087 const APInt &AOut, APInt &AB, KnownBits &Known, KnownBits &Known2) {
James Molloy87405c72015-08-14 11:09:09 +000088 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();
Craig Topperb45eabc2017-04-26 16:39:58 +000099 Known = KnownBits(BitWidth);
Craig Topper9fe35792017-05-13 17:22:16 +0000100 computeKnownBits(V1, Known, DL, 0, &AC, UserI, &DT);
James Molloy87405c72015-08-14 11:09:09 +0000101
102 if (V2) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000103 Known2 = KnownBits(BitWidth);
Craig Topper9fe35792017-05-13 17:22:16 +0000104 computeKnownBits(V2, Known2, DL, 0, &AC, UserI, &DT);
James Molloy87405c72015-08-14 11:09:09 +0000105 }
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;
Brian Gesiak0a7894d2017-04-13 16:44:25 +0000120 case Intrinsic::bitreverse:
Xin Tongbb8dbcf2017-06-19 20:10:41 +0000121 // The alive bits of the input are the reversed alive bits of
122 // the output.
Brian Gesiak0a7894d2017-04-13 16:44:25 +0000123 AB = AOut.reverseBits();
124 break;
James Molloy87405c72015-08-14 11:09:09 +0000125 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,
Craig Topper8df66c62017-05-12 17:20:30 +0000132 std::min(BitWidth, Known.countMaxLeadingZeros()+1));
James Molloy87405c72015-08-14 11:09:09 +0000133 }
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,
Craig Topper8df66c62017-05-12 17:20:30 +0000142 std::min(BitWidth, Known.countMaxTrailingZeros()+1));
James Molloy87405c72015-08-14 11:09:09 +0000143 }
144 break;
145 }
146 break;
147 case Instruction::Add:
148 case Instruction::Sub:
James Molloybcd7f0a2015-10-08 12:39:59 +0000149 case Instruction::Mul:
James Molloy87405c72015-08-14 11:09:09 +0000150 // Find the highest live output bit. We don't need any more input
151 // bits than that (adds, and thus subtracts, ripple only to the
152 // left).
153 AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
154 break;
155 case Instruction::Shl:
156 if (OperandNo == 0)
Sanjay Patel1bbdf4e2017-07-07 14:39:26 +0000157 if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
158 uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
James Molloy87405c72015-08-14 11:09:09 +0000159 AB = AOut.lshr(ShiftAmt);
160
161 // If the shift is nuw/nsw, then the high bits are not dead
162 // (because we've promised that they *must* be zero).
163 const ShlOperator *S = cast<ShlOperator>(UserI);
164 if (S->hasNoSignedWrap())
165 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
166 else if (S->hasNoUnsignedWrap())
167 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
168 }
169 break;
170 case Instruction::LShr:
171 if (OperandNo == 0)
Sanjay Patel1bbdf4e2017-07-07 14:39:26 +0000172 if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
173 uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
James Molloy87405c72015-08-14 11:09:09 +0000174 AB = AOut.shl(ShiftAmt);
175
176 // If the shift is exact, then the low bits are not dead
177 // (they must be zero).
178 if (cast<LShrOperator>(UserI)->isExact())
179 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
180 }
181 break;
182 case Instruction::AShr:
183 if (OperandNo == 0)
Sanjay Patel1bbdf4e2017-07-07 14:39:26 +0000184 if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
185 uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
James Molloy87405c72015-08-14 11:09:09 +0000186 AB = AOut.shl(ShiftAmt);
187 // Because the high input bit is replicated into the
188 // high-order bits of the result, if we need any of those
189 // bits, then we must keep the highest input bit.
190 if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
191 .getBoolValue())
Craig Topper24db6b82017-04-28 16:58:05 +0000192 AB.setSignBit();
James Molloy87405c72015-08-14 11:09:09 +0000193
194 // If the shift is exact, then the low bits are not dead
195 // (they must be zero).
196 if (cast<AShrOperator>(UserI)->isExact())
197 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
198 }
199 break;
200 case Instruction::And:
201 AB = AOut;
202
203 // For bits that are known zero, the corresponding bits in the
204 // other operand are dead (unless they're both zero, in which
205 // case they can't both be dead, so just mark the LHS bits as
206 // dead).
207 if (OperandNo == 0) {
208 ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
Craig Topperb45eabc2017-04-26 16:39:58 +0000209 AB &= ~Known2.Zero;
James Molloy87405c72015-08-14 11:09:09 +0000210 } else {
211 if (!isa<Instruction>(UserI->getOperand(0)))
212 ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
Craig Topperb45eabc2017-04-26 16:39:58 +0000213 AB &= ~(Known.Zero & ~Known2.Zero);
James Molloy87405c72015-08-14 11:09:09 +0000214 }
215 break;
216 case Instruction::Or:
217 AB = AOut;
218
219 // For bits that are known one, the corresponding bits in the
220 // other operand are dead (unless they're both one, in which
221 // case they can't both be dead, so just mark the LHS bits as
222 // dead).
223 if (OperandNo == 0) {
224 ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
Craig Topperb45eabc2017-04-26 16:39:58 +0000225 AB &= ~Known2.One;
James Molloy87405c72015-08-14 11:09:09 +0000226 } else {
227 if (!isa<Instruction>(UserI->getOperand(0)))
228 ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
Craig Topperb45eabc2017-04-26 16:39:58 +0000229 AB &= ~(Known.One & ~Known2.One);
James Molloy87405c72015-08-14 11:09:09 +0000230 }
231 break;
232 case Instruction::Xor:
233 case Instruction::PHI:
234 AB = AOut;
235 break;
236 case Instruction::Trunc:
237 AB = AOut.zext(BitWidth);
238 break;
239 case Instruction::ZExt:
240 AB = AOut.trunc(BitWidth);
241 break;
242 case Instruction::SExt:
243 AB = AOut.trunc(BitWidth);
244 // Because the high input bit is replicated into the
245 // high-order bits of the result, if we need any of those
246 // bits, then we must keep the highest input bit.
247 if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
248 AOut.getBitWidth() - BitWidth))
249 .getBoolValue())
Craig Topper24db6b82017-04-28 16:58:05 +0000250 AB.setSignBit();
James Molloy87405c72015-08-14 11:09:09 +0000251 break;
252 case Instruction::Select:
253 if (OperandNo != 0)
254 AB = AOut;
255 break;
256 }
257}
258
Michael Kupersteinde16b442016-04-18 23:55:01 +0000259bool DemandedBitsWrapperPass::runOnFunction(Function &F) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000260 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Kupersteinde16b442016-04-18 23:55:01 +0000261 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000262 DB.emplace(F, AC, DT);
James Molloyab9fdb92015-10-08 12:39:50 +0000263 return false;
264}
James Molloy87405c72015-08-14 11:09:09 +0000265
Michael Kupersteinde16b442016-04-18 23:55:01 +0000266void DemandedBitsWrapperPass::releaseMemory() {
267 DB.reset();
268}
269
James Molloyab9fdb92015-10-08 12:39:50 +0000270void DemandedBits::performAnalysis() {
271 if (Analyzed)
272 // Analysis already completed for this function.
273 return;
274 Analyzed = true;
Fangrui Songf78650a2018-07-30 19:41:25 +0000275
James Molloy87405c72015-08-14 11:09:09 +0000276 Visited.clear();
277 AliveBits.clear();
278
279 SmallVector<Instruction*, 128> Worklist;
280
281 // Collect the set of "root" instructions that are known live.
Michael Kupersteinde16b442016-04-18 23:55:01 +0000282 for (Instruction &I : instructions(F)) {
James Molloy87405c72015-08-14 11:09:09 +0000283 if (!isAlwaysLive(&I))
284 continue;
285
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000286 LLVM_DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
James Molloy87405c72015-08-14 11:09:09 +0000287 // For integer-valued instructions, set up an initial empty set of alive
288 // bits and add the instruction to the work list. For other instructions
289 // add their operands to the work list (for integer values operands, mark
290 // all bits as live).
291 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
Benjamin Kramera9e477b2016-07-21 13:37:55 +0000292 if (AliveBits.try_emplace(&I, IT->getBitWidth(), 0).second)
James Molloy87405c72015-08-14 11:09:09 +0000293 Worklist.push_back(&I);
James Molloy87405c72015-08-14 11:09:09 +0000294
295 continue;
296 }
297
298 // Non-integer-typed instructions...
299 for (Use &OI : I.operands()) {
300 if (Instruction *J = dyn_cast<Instruction>(OI)) {
301 if (IntegerType *IT = dyn_cast<IntegerType>(J->getType()))
302 AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth());
303 Worklist.push_back(J);
304 }
305 }
306 // To save memory, we don't add I to the Visited set here. Instead, we
307 // check isAlwaysLive on every instruction when searching for dead
308 // instructions later (we need to check isAlwaysLive for the
309 // integer-typed instructions anyway).
310 }
311
312 // Propagate liveness backwards to operands.
313 while (!Worklist.empty()) {
314 Instruction *UserI = Worklist.pop_back_val();
315
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000316 LLVM_DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
James Molloy87405c72015-08-14 11:09:09 +0000317 APInt AOut;
318 if (UserI->getType()->isIntegerTy()) {
319 AOut = AliveBits[UserI];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000320 LLVM_DEBUG(dbgs() << " Alive Out: " << AOut);
James Molloy87405c72015-08-14 11:09:09 +0000321 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000322 LLVM_DEBUG(dbgs() << "\n");
James Molloy87405c72015-08-14 11:09:09 +0000323
324 if (!UserI->getType()->isIntegerTy())
325 Visited.insert(UserI);
326
Craig Topperb45eabc2017-04-26 16:39:58 +0000327 KnownBits Known, Known2;
James Molloy87405c72015-08-14 11:09:09 +0000328 // Compute the set of alive bits for each operand. These are anded into the
329 // existing set, if any, and if that changes the set of alive bits, the
330 // operand is added to the work-list.
331 for (Use &OI : UserI->operands()) {
332 if (Instruction *I = dyn_cast<Instruction>(OI)) {
333 if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) {
334 unsigned BitWidth = IT->getBitWidth();
335 APInt AB = APInt::getAllOnesValue(BitWidth);
336 if (UserI->getType()->isIntegerTy() && !AOut &&
337 !isAlwaysLive(UserI)) {
338 AB = APInt(BitWidth, 0);
339 } else {
NAKAMURA Takumi84965032015-09-22 11:14:12 +0000340 // If all bits of the output are dead, then all bits of the input
James Molloy87405c72015-08-14 11:09:09 +0000341 // Bits of each operand that are used to compute alive bits of the
342 // output are alive, all others are dead.
343 determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB,
Craig Topperb45eabc2017-04-26 16:39:58 +0000344 Known, Known2);
James Molloy87405c72015-08-14 11:09:09 +0000345 }
346
347 // If we've added to the set of alive bits (or the operand has not
348 // been previously visited), then re-queue the operand to be visited
349 // again.
350 APInt ABPrev(BitWidth, 0);
351 auto ABI = AliveBits.find(I);
352 if (ABI != AliveBits.end())
353 ABPrev = ABI->second;
354
355 APInt ABNew = AB | ABPrev;
356 if (ABNew != ABPrev || ABI == AliveBits.end()) {
357 AliveBits[I] = std::move(ABNew);
358 Worklist.push_back(I);
359 }
360 } else if (!Visited.count(I)) {
361 Worklist.push_back(I);
362 }
363 }
364 }
365 }
James Molloy87405c72015-08-14 11:09:09 +0000366}
367
368APInt DemandedBits::getDemandedBits(Instruction *I) {
James Molloyab9fdb92015-10-08 12:39:50 +0000369 performAnalysis();
Fangrui Songf78650a2018-07-30 19:41:25 +0000370
Sanjay Patel042a5362017-08-16 14:28:23 +0000371 const DataLayout &DL = I->getModule()->getDataLayout();
Benjamin Kramera9e477b2016-07-21 13:37:55 +0000372 auto Found = AliveBits.find(I);
373 if (Found != AliveBits.end())
374 return Found->second;
James Molloy87405c72015-08-14 11:09:09 +0000375 return APInt::getAllOnesValue(DL.getTypeSizeInBits(I->getType()));
376}
377
378bool DemandedBits::isInstructionDead(Instruction *I) {
James Molloyab9fdb92015-10-08 12:39:50 +0000379 performAnalysis();
380
James Molloy87405c72015-08-14 11:09:09 +0000381 return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
382 !isAlwaysLive(I);
383}
384
Michael Kupersteinde16b442016-04-18 23:55:01 +0000385void DemandedBits::print(raw_ostream &OS) {
386 performAnalysis();
James Molloybcd7f0a2015-10-08 12:39:59 +0000387 for (auto &KV : AliveBits) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +0000388 OS << "DemandedBits: 0x" << Twine::utohexstr(KV.second.getLimitedValue())
389 << " for " << *KV.first << '\n';
James Molloybcd7f0a2015-10-08 12:39:59 +0000390 }
391}
392
Michael Kupersteinde16b442016-04-18 23:55:01 +0000393FunctionPass *llvm::createDemandedBitsWrapperPass() {
394 return new DemandedBitsWrapperPass();
395}
396
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000397AnalysisKey DemandedBitsAnalysis::Key;
Michael Kupersteinde16b442016-04-18 23:55:01 +0000398
399DemandedBits DemandedBitsAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000400 FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000401 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Michael Kupersteinde16b442016-04-18 23:55:01 +0000402 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000403 return DemandedBits(F, AC, DT);
Michael Kupersteinde16b442016-04-18 23:55:01 +0000404}
405
406PreservedAnalyses DemandedBitsPrinterPass::run(Function &F,
407 FunctionAnalysisManager &AM) {
408 AM.getResult<DemandedBitsAnalysis>(F).print(OS);
409 return PreservedAnalyses::all();
James Molloy87405c72015-08-14 11:09:09 +0000410}