1 //===---- BDCE.cpp - Bit-tracking dead code elimination -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Bit-Tracking Dead Code Elimination pass. Some
11 // instructions (shifts, some ands, ors, etc.) kill some of their input bits.
12 // We track these dead bits and remove instructions that compute only these
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar/BDCE.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/DemandedBits.h"
22 #include "llvm/Analysis/GlobalsModRef.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/IR/InstIterator.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Scalar.h"
32 #define DEBUG_TYPE "bdce"
34 STATISTIC(NumRemoved, "Number of instructions removed (unused)");
35 STATISTIC(NumSimplified, "Number of instructions trivialized (dead bits)");
37 /// If an instruction is trivialized (dead), then the chain of users of that
38 /// instruction may need to be cleared of assumptions that can no longer be
39 /// guaranteed correct.
40 static void clearAssumptionsOfUsers(Instruction *I, DemandedBits &DB) {
41 assert(I->getType()->isIntOrIntVectorTy() &&
42 "Trivializing a non-integer value?");
44 // Initialize the worklist with eligible direct users.
45 SmallVector<Instruction *, 16> WorkList;
46 for (User *JU : I->users()) {
47 // If all bits of a user are demanded, then we know that nothing below that
48 // in the def-use chain needs to be changed.
49 auto *J = dyn_cast<Instruction>(JU);
50 if (J && J->getType()->isIntOrIntVectorTy() &&
51 !DB.getDemandedBits(J).isAllOnesValue())
52 WorkList.push_back(J);
54 // Note that we need to check for non-int types above before asking for
55 // demanded bits. Normally, the only way to reach an instruction with an
56 // non-int type is via an instruction that has side effects (or otherwise
57 // will demand its input bits). However, if we have a readnone function
58 // that returns an unsized type (e.g., void), we must avoid asking for the
59 // demanded bits of the function call's return value. A void-returning
60 // readnone function is always dead (and so we can stop walking the use/def
61 // chain here), but the check is necessary to avoid asserting.
64 // DFS through subsequent users while tracking visits to avoid cycles.
65 SmallPtrSet<Instruction *, 16> Visited;
66 while (!WorkList.empty()) {
67 Instruction *J = WorkList.pop_back_val();
69 // NSW, NUW, and exact are based on operands that might have changed.
70 J->dropPoisonGeneratingFlags();
72 // We do not have to worry about llvm.assume or range metadata:
73 // 1. llvm.assume demands its operand, so trivializing can't change it.
74 // 2. range metadata only applies to memory accesses which demand all bits.
78 for (User *KU : J->users()) {
79 // If all bits of a user are demanded, then we know that nothing below
80 // that in the def-use chain needs to be changed.
81 auto *K = dyn_cast<Instruction>(KU);
82 if (K && !Visited.count(K) && K->getType()->isIntOrIntVectorTy() &&
83 !DB.getDemandedBits(K).isAllOnesValue())
84 WorkList.push_back(K);
89 static bool bitTrackingDCE(Function &F, DemandedBits &DB) {
90 SmallVector<Instruction*, 128> Worklist;
92 for (Instruction &I : instructions(F)) {
93 // If the instruction has side effects and no non-dbg uses,
94 // skip it. This way we avoid computing known bits on an instruction
95 // that will not help us.
96 if (I.mayHaveSideEffects() && I.use_empty())
99 // Remove instructions that are dead, either because they were not reached
100 // during analysis or have no demanded bits.
101 if (DB.isInstructionDead(&I) ||
102 (I.getType()->isIntOrIntVectorTy() &&
103 DB.getDemandedBits(&I).isNullValue() &&
104 wouldInstructionBeTriviallyDead(&I))) {
106 Worklist.push_back(&I);
107 I.dropAllReferences();
112 for (Use &U : I.operands()) {
113 // DemandedBits only detects dead integer uses.
114 if (!U->getType()->isIntOrIntVectorTy())
117 if (!isa<Instruction>(U) && !isa<Argument>(U))
120 if (!DB.isUseDead(&U))
123 LLVM_DEBUG(dbgs() << "BDCE: Trivializing: " << U << " (all bits dead)\n");
125 clearAssumptionsOfUsers(&I, DB);
127 // FIXME: In theory we could substitute undef here instead of zero.
128 // This should be reconsidered once we settle on the semantics of
129 // undef, poison, etc.
130 U.set(ConstantInt::get(U->getType(), 0));
136 for (Instruction *&I : Worklist) {
138 I->eraseFromParent();
144 PreservedAnalyses BDCEPass::run(Function &F, FunctionAnalysisManager &AM) {
145 auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
146 if (!bitTrackingDCE(F, DB))
147 return PreservedAnalyses::all();
149 PreservedAnalyses PA;
150 PA.preserveSet<CFGAnalyses>();
151 PA.preserve<GlobalsAA>();
156 struct BDCELegacyPass : public FunctionPass {
157 static char ID; // Pass identification, replacement for typeid
158 BDCELegacyPass() : FunctionPass(ID) {
159 initializeBDCELegacyPassPass(*PassRegistry::getPassRegistry());
162 bool runOnFunction(Function &F) override {
165 auto &DB = getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
166 return bitTrackingDCE(F, DB);
169 void getAnalysisUsage(AnalysisUsage &AU) const override {
170 AU.setPreservesCFG();
171 AU.addRequired<DemandedBitsWrapperPass>();
172 AU.addPreserved<GlobalsAAWrapperPass>();
177 char BDCELegacyPass::ID = 0;
178 INITIALIZE_PASS_BEGIN(BDCELegacyPass, "bdce",
179 "Bit-Tracking Dead Code Elimination", false, false)
180 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
181 INITIALIZE_PASS_END(BDCELegacyPass, "bdce",
182 "Bit-Tracking Dead Code Elimination", false, false)
184 FunctionPass *llvm::createBitTrackingDCEPass() { return new BDCELegacyPass(); }