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.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/DemandedBits.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
32 #define DEBUG_TYPE "bdce"
34 STATISTIC(NumRemoved, "Number of instructions removed (unused)");
35 STATISTIC(NumSimplified, "Number of instructions trivialized (dead bits)");
38 struct BDCE : public FunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 BDCE() : FunctionPass(ID) {
41 initializeBDCEPass(*PassRegistry::getPassRegistry());
44 bool runOnFunction(Function& F) override;
46 void getAnalysisUsage(AnalysisUsage& AU) const override {
48 AU.addRequired<DemandedBits>();
49 AU.addPreserved<GlobalsAAWrapperPass>();
55 INITIALIZE_PASS_BEGIN(BDCE, "bdce", "Bit-Tracking Dead Code Elimination",
57 INITIALIZE_PASS_DEPENDENCY(DemandedBits)
58 INITIALIZE_PASS_END(BDCE, "bdce", "Bit-Tracking Dead Code Elimination",
61 bool BDCE::runOnFunction(Function& F) {
62 if (skipOptnoneFunction(F))
64 DemandedBits &DB = getAnalysis<DemandedBits>();
66 SmallVector<Instruction*, 128> Worklist;
68 for (Instruction &I : instructions(F)) {
69 if (I.getType()->isIntegerTy() &&
70 !DB.getDemandedBits(&I).getBoolValue()) {
71 // For live instructions that have all dead bits, first make them dead by
72 // replacing all uses with something else. Then, if they don't need to
73 // remain live (because they have side effects, etc.) we can remove them.
74 DEBUG(dbgs() << "BDCE: Trivializing: " << I << " (all bits dead)\n");
75 // FIXME: In theory we could substitute undef here instead of zero.
76 // This should be reconsidered once we settle on the semantics of
77 // undef, poison, etc.
78 Value *Zero = ConstantInt::get(I.getType(), 0);
80 I.replaceAllUsesWith(Zero);
83 if (!DB.isInstructionDead(&I))
86 Worklist.push_back(&I);
87 I.dropAllReferences();
91 for (Instruction *&I : Worklist) {
99 FunctionPass *llvm::createBitTrackingDCEPass() {