LLVM 17.0.0git
Go to the documentation of this file.
1//===- InstSimplifyPass.cpp -----------------------------------------------===//
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
11#include "llvm/ADT/Statistic.h"
16#include "llvm/IR/Dominators.h"
17#include "llvm/IR/Function.h"
19#include "llvm/Pass.h"
23using namespace llvm;
25#define DEBUG_TYPE "instsimplify"
27STATISTIC(NumSimplified, "Number of redundant instructions removed");
29static bool runImpl(Function &F, const SimplifyQuery &SQ,
31 SmallPtrSet<const Instruction *, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
32 bool Changed = false;
34 do {
35 for (BasicBlock &BB : F) {
36 // Unreachable code can take on strange forms that we are not prepared to
37 // handle. For example, an instruction may have itself as an operand.
38 if (!SQ.DT->isReachableFromEntry(&BB))
39 continue;
42 for (Instruction &I : BB) {
43 // The first time through the loop, ToSimplify is empty and we try to
44 // simplify all instructions. On later iterations, ToSimplify is not
45 // empty and we only bother simplifying instructions that are in it.
46 if (!ToSimplify->empty() && !ToSimplify->count(&I))
47 continue;
49 // Don't waste time simplifying dead/unused instructions.
51 DeadInstsInBB.push_back(&I);
52 Changed = true;
53 } else if (!I.use_empty()) {
54 if (Value *V = simplifyInstruction(&I, SQ, ORE)) {
55 // Mark all uses for resimplification next time round the loop.
56 for (User *U : I.users())
57 Next->insert(cast<Instruction>(U));
58 I.replaceAllUsesWith(V);
59 ++NumSimplified;
60 Changed = true;
61 // A call can get simplified, but it may not be trivially dead.
63 DeadInstsInBB.push_back(&I);
64 }
65 }
66 }
68 }
70 // Place the list of instructions to simplify on the next loop iteration
71 // into ToSimplify.
72 std::swap(ToSimplify, Next);
73 Next->clear();
74 } while (!ToSimplify->empty());
76 return Changed;
79namespace {
80struct InstSimplifyLegacyPass : public FunctionPass {
81 static char ID; // Pass identification, replacement for typeid
82 InstSimplifyLegacyPass() : FunctionPass(ID) {
84 }
86 void getAnalysisUsage(AnalysisUsage &AU) const override {
87 AU.setPreservesCFG();
92 }
94 /// Remove instructions that simplify.
95 bool runOnFunction(Function &F) override {
96 if (skipFunction(F))
97 return false;
99 const DominatorTree *DT =
100 &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
101 const TargetLibraryInfo *TLI =
102 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
103 AssumptionCache *AC =
104 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
106 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
107 const DataLayout &DL = F.getParent()->getDataLayout();
108 const SimplifyQuery SQ(DL, TLI, DT, AC);
109 return runImpl(F, SQ, ORE);
110 }
112} // namespace
114char InstSimplifyLegacyPass::ID = 0;
115INITIALIZE_PASS_BEGIN(InstSimplifyLegacyPass, "instsimplify",
116 "Remove redundant instructions", false, false)
121INITIALIZE_PASS_END(InstSimplifyLegacyPass, "instsimplify",
122 "Remove redundant instructions", false, false)
124// Public interface to the simplify instructions pass.
126 return new InstSimplifyLegacyPass();
131 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
132 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
133 auto &AC = AM.getResult<AssumptionAnalysis>(F);
135 const DataLayout &DL = F.getParent()->getDataLayout();
136 const SimplifyQuery SQ(DL, &TLI, &DT, &AC);
137 bool Changed = runImpl(F, SQ, &ORE);
138 if (!Changed)
139 return PreservedAnalyses::all();
143 return PA;
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool runImpl(Function &F, const TargetLowering &TLI)
static bool runImpl(Function &F, const SimplifyQuery &SQ, OptimizationRemarkEmitter *ORE)
Remove redundant instructions
Defines passes for running instruction simplification across chunks of IR.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
Definition: Statistic.h:167
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:265
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:113
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:314
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition: Pass.cpp:174
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:188
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LLVM Value Representation.
Definition: Value.h:74
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition: Local.cpp:537
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition: Local.cpp:398
void initializeInstSimplifyLegacyPassPass(PassRegistry &)
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
FunctionPass * createInstSimplifyLegacyPass()
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
const DominatorTree * DT
const TargetLibraryInfo * TLI