LLVM  12.0.0git
Go to the documentation of this file.
1 //===- InstSimplifyPass.cpp -----------------------------------------------===//
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 //===----------------------------------------------------------------------===//
11 #include "llvm/ADT/SmallPtrSet.h"
12 #include "llvm/ADT/Statistic.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/InitializePasses.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Transforms/Utils.h"
25 using namespace llvm;
27 #define DEBUG_TYPE "instsimplify"
29 STATISTIC(NumSimplified, "Number of redundant instructions removed");
31 static bool runImpl(Function &F, const SimplifyQuery &SQ,
33  SmallPtrSet<const Instruction *, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
34  bool Changed = false;
36  do {
37  for (BasicBlock &BB : F) {
38  // Unreachable code can take on strange forms that we are not prepared to
39  // handle. For example, an instruction may have itself as an operand.
40  if (!SQ.DT->isReachableFromEntry(&BB))
41  continue;
43  SmallVector<WeakTrackingVH, 8> DeadInstsInBB;
44  for (Instruction &I : BB) {
45  // The first time through the loop, ToSimplify is empty and we try to
46  // simplify all instructions. On later iterations, ToSimplify is not
47  // empty and we only bother simplifying instructions that are in it.
48  if (!ToSimplify->empty() && !ToSimplify->count(&I))
49  continue;
51  // Don't waste time simplifying dead/unused instructions.
53  DeadInstsInBB.push_back(&I);
54  Changed = true;
55  } else if (!I.use_empty()) {
56  if (Value *V = SimplifyInstruction(&I, SQ, ORE)) {
57  // Mark all uses for resimplification next time round the loop.
58  for (User *U : I.users())
59  Next->insert(cast<Instruction>(U));
60  I.replaceAllUsesWith(V);
61  ++NumSimplified;
62  Changed = true;
63  // A call can get simplified, but it may not be trivially dead.
65  DeadInstsInBB.push_back(&I);
66  }
67  }
68  }
70  }
72  // Place the list of instructions to simplify on the next loop iteration
73  // into ToSimplify.
74  std::swap(ToSimplify, Next);
75  Next->clear();
76  } while (!ToSimplify->empty());
78  return Changed;
79 }
81 namespace {
82 struct InstSimplifyLegacyPass : public FunctionPass {
83  static char ID; // Pass identification, replacement for typeid
84  InstSimplifyLegacyPass() : FunctionPass(ID) {
86  }
88  void getAnalysisUsage(AnalysisUsage &AU) const override {
89  AU.setPreservesCFG();
94  }
96  /// Remove instructions that simplify.
97  bool runOnFunction(Function &F) override {
98  if (skipFunction(F))
99  return false;
101  const DominatorTree *DT =
102  &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
103  const TargetLibraryInfo *TLI =
104  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
105  AssumptionCache *AC =
106  &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
108  &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
109  const DataLayout &DL = F.getParent()->getDataLayout();
110  const SimplifyQuery SQ(DL, TLI, DT, AC);
111  return runImpl(F, SQ, ORE);
112  }
113 };
114 } // namespace
117 INITIALIZE_PASS_BEGIN(InstSimplifyLegacyPass, "instsimplify",
118  "Remove redundant instructions", false, false)
123 INITIALIZE_PASS_END(InstSimplifyLegacyPass, "instsimplify",
124  "Remove redundant instructions", false, false)
126 // Public interface to the simplify instructions pass.
128  return new InstSimplifyLegacyPass();
129 }
133  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
134  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
135  auto &AC = AM.getResult<AssumptionAnalysis>(F);
137  const DataLayout &DL = F.getParent()->getDataLayout();
138  const SimplifyQuery SQ(DL, &TLI, &DT, &AC);
139  bool Changed = runImpl(F, SQ, &ORE);
140  if (!Changed)
141  return PreservedAnalyses::all();
144  PA.preserveSet<CFGAnalyses>();
145  return PA;
146 }
Defines passes for running instruction simplification across chunks of IR.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
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:769
This class represents lattice values for constants.
Definition: AllocatorList.h:23
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:233
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const TargetLibraryInfo * TLI
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:304
AnalysisUsage & addRequired()
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:397
static bool runImpl(Function &F, const SimplifyQuery &SQ, OptimizationRemarkEmitter *ORE)
FunctionPass * createInstSimplifyLegacyPass()
Create a legacy pass that does instruction simplification on each instruction in a function...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
static bool runOnFunction(Function &F, bool PostInlining)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
LLVM_NODISCARD bool empty() const
Definition: SmallPtrSet.h:91
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:375
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
A function analysis which provides an AssumptionCache.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:439
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:883
Provides information about what library functions are available for the current target.
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:455
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:253
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:962
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:115
void initializeInstSimplifyLegacyPassPass(PassRegistry &)
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:190
#define I(x, y, z)
Definition: MD5.cpp:59
Analysis pass providing the TargetLibraryInfo.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:572
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
Definition: Local.cpp:360
LLVM Value Representation.
Definition: Value.h:74
OptimizationRemarkEmitter legacy analysis pass.
const DominatorTree * DT
inst_range instructions(Function *F)
Definition: InstIterator.h:133
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:262
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
The optimization diagnostic interface.
INITIALIZE_PASS_BEGIN(InstSimplifyLegacyPass, "instsimplify", "Remove redundant instructions", false, false) INITIALIZE_PASS_END(InstSimplifyLegacyPass
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL