12bb61ba2SHal Finkel //===---- BDCE.cpp - Bit-tracking dead code elimination -------------------===//
22bb61ba2SHal Finkel //
32bb61ba2SHal Finkel //                     The LLVM Compiler Infrastructure
42bb61ba2SHal Finkel //
52bb61ba2SHal Finkel // This file is distributed under the University of Illinois Open Source
62bb61ba2SHal Finkel // License. See LICENSE.TXT for details.
72bb61ba2SHal Finkel //
82bb61ba2SHal Finkel //===----------------------------------------------------------------------===//
92bb61ba2SHal Finkel //
102bb61ba2SHal Finkel // This file implements the Bit-Tracking Dead Code Elimination pass. Some
112bb61ba2SHal Finkel // instructions (shifts, some ands, ors, etc.) kill some of their input bits.
122bb61ba2SHal Finkel // We track these dead bits and remove instructions that compute only these
132bb61ba2SHal Finkel // dead bits.
142bb61ba2SHal Finkel //
152bb61ba2SHal Finkel //===----------------------------------------------------------------------===//
162bb61ba2SHal Finkel 
17655a145eSDavide Italiano #include "llvm/Transforms/Scalar/BDCE.h"
18fe346f9fSSanjay Patel #include "llvm/ADT/SmallPtrSet.h"
192bb61ba2SHal Finkel #include "llvm/ADT/SmallVector.h"
202bb61ba2SHal Finkel #include "llvm/ADT/Statistic.h"
2187405c7fSJames Molloy #include "llvm/Analysis/DemandedBits.h"
22655a145eSDavide Italiano #include "llvm/Analysis/GlobalsModRef.h"
23*31b98d2eSDavid Blaikie #include "llvm/Transforms/Utils/Local.h"
242bb61ba2SHal Finkel #include "llvm/IR/InstIterator.h"
252bb61ba2SHal Finkel #include "llvm/IR/Instructions.h"
262bb61ba2SHal Finkel #include "llvm/Pass.h"
272bb61ba2SHal Finkel #include "llvm/Support/Debug.h"
282bb61ba2SHal Finkel #include "llvm/Support/raw_ostream.h"
29655a145eSDavide Italiano #include "llvm/Transforms/Scalar.h"
302bb61ba2SHal Finkel using namespace llvm;
312bb61ba2SHal Finkel 
322bb61ba2SHal Finkel #define DEBUG_TYPE "bdce"
332bb61ba2SHal Finkel 
342bb61ba2SHal Finkel STATISTIC(NumRemoved, "Number of instructions removed (unused)");
352bb61ba2SHal Finkel STATISTIC(NumSimplified, "Number of instructions trivialized (dead bits)");
362bb61ba2SHal Finkel 
37fe346f9fSSanjay Patel /// If an instruction is trivialized (dead), then the chain of users of that
38fe346f9fSSanjay Patel /// instruction may need to be cleared of assumptions that can no longer be
39fe346f9fSSanjay Patel /// guaranteed correct.
40fe346f9fSSanjay Patel static void clearAssumptionsOfUsers(Instruction *I, DemandedBits &DB) {
41fe346f9fSSanjay Patel   assert(I->getType()->isIntegerTy() && "Trivializing a non-integer value?");
42fe346f9fSSanjay Patel 
43fe346f9fSSanjay Patel   // Initialize the worklist with eligible direct users.
44fe346f9fSSanjay Patel   SmallVector<Instruction *, 16> WorkList;
45fe346f9fSSanjay Patel   for (User *JU : I->users()) {
46a1067d9bSSanjay Patel     // If all bits of a user are demanded, then we know that nothing below that
47a1067d9bSSanjay Patel     // in the def-use chain needs to be changed.
48fe346f9fSSanjay Patel     auto *J = dyn_cast<Instruction>(JU);
499e54b709SHal Finkel     if (J && J->getType()->isSized() &&
509e54b709SHal Finkel         !DB.getDemandedBits(J).isAllOnesValue())
51fe346f9fSSanjay Patel       WorkList.push_back(J);
529e54b709SHal Finkel 
539e54b709SHal Finkel     // Note that we need to check for unsized types above before asking for
549e54b709SHal Finkel     // demanded bits. Normally, the only way to reach an instruction with an
559e54b709SHal Finkel     // unsized type is via an instruction that has side effects (or otherwise
569e54b709SHal Finkel     // will demand its input bits). However, if we have a readnone function
579e54b709SHal Finkel     // that returns an unsized type (e.g., void), we must avoid asking for the
589e54b709SHal Finkel     // demanded bits of the function call's return value. A void-returning
599e54b709SHal Finkel     // readnone function is always dead (and so we can stop walking the use/def
609e54b709SHal Finkel     // chain here), but the check is necessary to avoid asserting.
61fe346f9fSSanjay Patel   }
62fe346f9fSSanjay Patel 
63fe346f9fSSanjay Patel   // DFS through subsequent users while tracking visits to avoid cycles.
64fe346f9fSSanjay Patel   SmallPtrSet<Instruction *, 16> Visited;
65fe346f9fSSanjay Patel   while (!WorkList.empty()) {
66fe346f9fSSanjay Patel     Instruction *J = WorkList.pop_back_val();
67fe346f9fSSanjay Patel 
68fe346f9fSSanjay Patel     // NSW, NUW, and exact are based on operands that might have changed.
69fe346f9fSSanjay Patel     J->dropPoisonGeneratingFlags();
70fe346f9fSSanjay Patel 
71fe346f9fSSanjay Patel     // We do not have to worry about llvm.assume or range metadata:
72fe346f9fSSanjay Patel     // 1. llvm.assume demands its operand, so trivializing can't change it.
73fe346f9fSSanjay Patel     // 2. range metadata only applies to memory accesses which demand all bits.
74fe346f9fSSanjay Patel 
75fe346f9fSSanjay Patel     Visited.insert(J);
76fe346f9fSSanjay Patel 
77fe346f9fSSanjay Patel     for (User *KU : J->users()) {
78a1067d9bSSanjay Patel       // If all bits of a user are demanded, then we know that nothing below
79a1067d9bSSanjay Patel       // that in the def-use chain needs to be changed.
80fe346f9fSSanjay Patel       auto *K = dyn_cast<Instruction>(KU);
819e54b709SHal Finkel       if (K && !Visited.count(K) && K->getType()->isSized() &&
829e54b709SHal Finkel           !DB.getDemandedBits(K).isAllOnesValue())
83fe346f9fSSanjay Patel         WorkList.push_back(K);
84fe346f9fSSanjay Patel     }
85fe346f9fSSanjay Patel   }
86fe346f9fSSanjay Patel }
87fe346f9fSSanjay Patel 
88655a145eSDavide Italiano static bool bitTrackingDCE(Function &F, DemandedBits &DB) {
892bb61ba2SHal Finkel   SmallVector<Instruction*, 128> Worklist;
902bb61ba2SHal Finkel   bool Changed = false;
9178199518SNico Rieck   for (Instruction &I : instructions(F)) {
92043e6613SDavide Italiano     // If the instruction has side effects and no non-dbg uses,
931ed53963SDavide Italiano     // skip it. This way we avoid computing known bits on an instruction
941ed53963SDavide Italiano     // that will not help us.
95043e6613SDavide Italiano     if (I.mayHaveSideEffects() && I.use_empty())
96043e6613SDavide Italiano       continue;
97043e6613SDavide Italiano 
9887405c7fSJames Molloy     if (I.getType()->isIntegerTy() &&
9987405c7fSJames Molloy         !DB.getDemandedBits(&I).getBoolValue()) {
1002bb61ba2SHal Finkel       // For live instructions that have all dead bits, first make them dead by
1012bb61ba2SHal Finkel       // replacing all uses with something else. Then, if they don't need to
1022bb61ba2SHal Finkel       // remain live (because they have side effects, etc.) we can remove them.
103d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "BDCE: Trivializing: " << I << " (all bits dead)\n");
104fe346f9fSSanjay Patel 
105fe346f9fSSanjay Patel       clearAssumptionsOfUsers(&I, DB);
106fe346f9fSSanjay Patel 
1072bb61ba2SHal Finkel       // FIXME: In theory we could substitute undef here instead of zero.
1082bb61ba2SHal Finkel       // This should be reconsidered once we settle on the semantics of
1092bb61ba2SHal Finkel       // undef, poison, etc.
1102bb61ba2SHal Finkel       Value *Zero = ConstantInt::get(I.getType(), 0);
1112bb61ba2SHal Finkel       ++NumSimplified;
1121ed53963SDavide Italiano       I.replaceNonMetadataUsesWith(Zero);
1132bb61ba2SHal Finkel       Changed = true;
1142bb61ba2SHal Finkel     }
11587405c7fSJames Molloy     if (!DB.isInstructionDead(&I))
1162bb61ba2SHal Finkel       continue;
1172bb61ba2SHal Finkel 
11856492f91SVedant Kumar     salvageDebugInfo(I);
1192bb61ba2SHal Finkel     Worklist.push_back(&I);
1202bb61ba2SHal Finkel     I.dropAllReferences();
1212bb61ba2SHal Finkel     Changed = true;
1222bb61ba2SHal Finkel   }
1232bb61ba2SHal Finkel 
1242bb61ba2SHal Finkel   for (Instruction *&I : Worklist) {
1252bb61ba2SHal Finkel     ++NumRemoved;
1262bb61ba2SHal Finkel     I->eraseFromParent();
1272bb61ba2SHal Finkel   }
1282bb61ba2SHal Finkel 
1292bb61ba2SHal Finkel   return Changed;
1302bb61ba2SHal Finkel }
1312bb61ba2SHal Finkel 
132655a145eSDavide Italiano PreservedAnalyses BDCEPass::run(Function &F, FunctionAnalysisManager &AM) {
133655a145eSDavide Italiano   auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
134bdc29714SDavide Italiano   if (!bitTrackingDCE(F, DB))
135655a145eSDavide Italiano     return PreservedAnalyses::all();
136bdc29714SDavide Italiano 
137ca68a3ecSChandler Carruth   PreservedAnalyses PA;
138ca68a3ecSChandler Carruth   PA.preserveSet<CFGAnalyses>();
139bdc29714SDavide Italiano   PA.preserve<GlobalsAA>();
140bdc29714SDavide Italiano   return PA;
1412bb61ba2SHal Finkel }
1422bb61ba2SHal Finkel 
143655a145eSDavide Italiano namespace {
144655a145eSDavide Italiano struct BDCELegacyPass : public FunctionPass {
145655a145eSDavide Italiano   static char ID; // Pass identification, replacement for typeid
146655a145eSDavide Italiano   BDCELegacyPass() : FunctionPass(ID) {
147655a145eSDavide Italiano     initializeBDCELegacyPassPass(*PassRegistry::getPassRegistry());
148655a145eSDavide Italiano   }
149655a145eSDavide Italiano 
150655a145eSDavide Italiano   bool runOnFunction(Function &F) override {
151655a145eSDavide Italiano     if (skipFunction(F))
152655a145eSDavide Italiano       return false;
153655a145eSDavide Italiano     auto &DB = getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
154655a145eSDavide Italiano     return bitTrackingDCE(F, DB);
155655a145eSDavide Italiano   }
156655a145eSDavide Italiano 
157655a145eSDavide Italiano   void getAnalysisUsage(AnalysisUsage &AU) const override {
158655a145eSDavide Italiano     AU.setPreservesCFG();
159655a145eSDavide Italiano     AU.addRequired<DemandedBitsWrapperPass>();
160655a145eSDavide Italiano     AU.addPreserved<GlobalsAAWrapperPass>();
161655a145eSDavide Italiano   }
162655a145eSDavide Italiano };
163655a145eSDavide Italiano }
164655a145eSDavide Italiano 
165655a145eSDavide Italiano char BDCELegacyPass::ID = 0;
166655a145eSDavide Italiano INITIALIZE_PASS_BEGIN(BDCELegacyPass, "bdce",
167655a145eSDavide Italiano                       "Bit-Tracking Dead Code Elimination", false, false)
168655a145eSDavide Italiano INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
169655a145eSDavide Italiano INITIALIZE_PASS_END(BDCELegacyPass, "bdce",
170655a145eSDavide Italiano                     "Bit-Tracking Dead Code Elimination", false, false)
171655a145eSDavide Italiano 
172655a145eSDavide Italiano FunctionPass *llvm::createBitTrackingDCEPass() { return new BDCELegacyPass(); }
173