LLVM  10.0.0svn
Go to the documentation of this file.
1 //===---- BDCE.cpp - Bit-tracking dead code elimination -------------------===//
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 file implements the Bit-Tracking Dead Code Elimination pass. Some
10 // instructions (shifts, some ands, ors, etc.) kill some of their input bits.
11 // We track these dead bits and remove instructions that compute only these
12 // dead bits.
13 //
14 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/Debug.h"
28 #include "llvm/Transforms/Scalar.h"
29 using namespace llvm;
31 #define DEBUG_TYPE "bdce"
33 STATISTIC(NumRemoved, "Number of instructions removed (unused)");
34 STATISTIC(NumSimplified, "Number of instructions trivialized (dead bits)");
36 /// If an instruction is trivialized (dead), then the chain of users of that
37 /// instruction may need to be cleared of assumptions that can no longer be
38 /// guaranteed correct.
41  "Trivializing a non-integer value?");
43  // Initialize the worklist with eligible direct users.
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() &&
52  Visited.insert(J);
53  WorkList.push_back(J);
54  }
56  // Note that we need to check for non-int types above before asking for
57  // demanded bits. Normally, the only way to reach an instruction with an
58  // non-int type is via an instruction that has side effects (or otherwise
59  // will demand its input bits). However, if we have a readnone function
60  // that returns an unsized type (e.g., void), we must avoid asking for the
61  // demanded bits of the function call's return value. A void-returning
62  // readnone function is always dead (and so we can stop walking the use/def
63  // chain here), but the check is necessary to avoid asserting.
64  }
66  // DFS through subsequent users while tracking visits to avoid cycles.
67  while (!WorkList.empty()) {
68  Instruction *J = WorkList.pop_back_val();
70  // NSW, NUW, and exact are based on operands that might have changed.
73  // We do not have to worry about llvm.assume or range metadata:
74  // 1. llvm.assume demands its operand, so trivializing can't change it.
75  // 2. range metadata only applies to memory accesses which demand all bits.
77  for (User *KU : J->users()) {
78  // If all bits of a user are demanded, then we know that nothing below
79  // that in the def-use chain needs to be changed.
80  auto *K = dyn_cast<Instruction>(KU);
81  if (K && Visited.insert(K).second && K->getType()->isIntOrIntVectorTy() &&
83  WorkList.push_back(K);
84  }
85  }
86 }
88 static bool bitTrackingDCE(Function &F, DemandedBits &DB) {
90  bool Changed = false;
91  for (Instruction &I : instructions(F)) {
92  // If the instruction has side effects and no non-dbg uses,
93  // skip it. This way we avoid computing known bits on an instruction
94  // that will not help us.
95  if (I.mayHaveSideEffects() && I.use_empty())
96  continue;
98  // Remove instructions that are dead, either because they were not reached
99  // during analysis or have no demanded bits.
100  if (DB.isInstructionDead(&I) ||
101  (I.getType()->isIntOrIntVectorTy() &&
102  DB.getDemandedBits(&I).isNullValue() &&
105  Worklist.push_back(&I);
106  I.dropAllReferences();
107  Changed = true;
108  continue;
109  }
111  for (Use &U : I.operands()) {
112  // DemandedBits only detects dead integer uses.
113  if (!U->getType()->isIntOrIntVectorTy())
114  continue;
116  if (!isa<Instruction>(U) && !isa<Argument>(U))
117  continue;
119  if (!DB.isUseDead(&U))
120  continue;
122  LLVM_DEBUG(dbgs() << "BDCE: Trivializing: " << U << " (all bits dead)\n");
126  // FIXME: In theory we could substitute undef here instead of zero.
127  // This should be reconsidered once we settle on the semantics of
128  // undef, poison, etc.
129  U.set(ConstantInt::get(U->getType(), 0));
130  ++NumSimplified;
131  Changed = true;
132  }
133  }
135  for (Instruction *&I : Worklist) {
136  ++NumRemoved;
137  I->eraseFromParent();
138  }
140  return Changed;
141 }
144  auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
145  if (!bitTrackingDCE(F, DB))
146  return PreservedAnalyses::all();
149  PA.preserveSet<CFGAnalyses>();
150  PA.preserve<GlobalsAA>();
151  return PA;
152 }
154 namespace {
155 struct BDCELegacyPass : public FunctionPass {
156  static char ID; // Pass identification, replacement for typeid
157  BDCELegacyPass() : FunctionPass(ID) {
159  }
161  bool runOnFunction(Function &F) override {
162  if (skipFunction(F))
163  return false;
164  auto &DB = getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
165  return bitTrackingDCE(F, DB);
166  }
168  void getAnalysisUsage(AnalysisUsage &AU) const override {
169  AU.setPreservesCFG();
172  }
173 };
174 }
176 char BDCELegacyPass::ID = 0;
178  "Bit-Tracking Dead Code Elimination", false, false)
180 INITIALIZE_PASS_END(BDCELegacyPass, "bdce",
181  "Bit-Tracking Dead Code Elimination", false, false)
183 FunctionPass *llvm::createBitTrackingDCEPass() { return new BDCELegacyPass(); }
Legacy wrapper pass to provide the GlobalsAAResult object.
void initializeBDCELegacyPassPass(PassRegistry &)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This is the interface for a simple mod/ref and alias analysis over globals.
bool isInstructionDead(Instruction *I)
Return true if, during analysis, I could not be reached.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: BDCE.cpp:143
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
Definition: Local.cpp:1605
STATISTIC(NumFunctions, "Total number of functions")
AnalysisUsage & addRequired()
Definition: PassSupport.h:50
static bool bitTrackingDCE(Function &F, DemandedBits &DB)
Definition: BDCE.cpp:88
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
An analysis that produces DemandedBits for a function.
Definition: DemandedBits.h:106
void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:203
static bool runOnFunction(Function &F, bool PostInlining)
bool isAllOnesValue() const
Determine if all bits are set.
Definition: APInt.h:395
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
Represent the analysis usage information of a pass.
Analysis pass providing a never-invalidated alias analysis result.
FunctionPass * createBitTrackingDCEPass()
Definition: BDCE.cpp:183
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Bit Tracking Dead Code Elimination
Definition: BDCE.cpp:180
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:653
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:301
static void clearAssumptionsOfUsers(Instruction *I, DemandedBits &DB)
If an instruction is trivialized (dead), then the chain of users of that instruction may need to be c...
Definition: BDCE.cpp:39
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
Definition: BDCE.cpp:180
iterator_range< user_iterator > users()
Definition: Value.h:420
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:115
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:190
#define I(x, y, z)
Definition: MD5.cpp:58
INITIALIZE_PASS_BEGIN(BDCELegacyPass, "bdce", "Bit-Tracking Dead Code Elimination", false, false) INITIALIZE_PASS_END(BDCELegacyPass
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:175
bool isUseDead(Use *U)
Return whether this use is dead by means of not having any demanded bits.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool wouldInstructionBeTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used...
Definition: Local.cpp:366
inst_range instructions(Function *F)
Definition: InstIterator.h:133
A container for analyses that lazily runs them and caches their results.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
bool isNullValue() const
Determine if all bits are clear.
Definition: APInt.h:405