LLVM 22.0.0git
RemoveLoadsIntoFakeUses.cpp
Go to the documentation of this file.
1//===---- RemoveLoadsIntoFakeUses.cpp - Remove loads with no real uses ----===//
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/// \file
10/// The FAKE_USE instruction is used to preserve certain values through
11/// optimizations for the sake of debugging. This may result in spilled values
12/// being loaded into registers that are only used by FAKE_USEs; this is not
13/// necessary for debugging purposes, because at that point the value must be on
14/// the stack and hence available for debugging. Therefore, this pass removes
15/// loads that are only used by FAKE_USEs.
16///
17/// This pass should run very late, to ensure that we don't inadvertently
18/// shorten stack lifetimes by removing these loads, since the FAKE_USEs will
19/// also no longer be in effect. Running immediately before LiveDebugValues
20/// ensures that LDV will have accurate information of the machine location of
21/// debug values.
22///
23//===----------------------------------------------------------------------===//
24
27#include "llvm/ADT/Statistic.h"
34#include "llvm/IR/Function.h"
36#include "llvm/Support/Debug.h"
38
39using namespace llvm;
40
41#define DEBUG_TYPE "remove-loads-into-fake-uses"
42
43STATISTIC(NumLoadsDeleted, "Number of dead load instructions deleted");
44STATISTIC(NumFakeUsesDeleted, "Number of FAKE_USE instructions deleted");
45
47public:
48 static char ID;
49
53 }
54
55 void getAnalysisUsage(AnalysisUsage &AU) const override {
56 AU.setPreservesCFG();
58 }
59
61 return MachineFunctionProperties().setNoVRegs();
62 }
63
64 StringRef getPassName() const override {
65 return "Remove Loads Into Fake Uses";
66 }
67
68 bool runOnMachineFunction(MachineFunction &MF) override;
69};
70
72 bool run(MachineFunction &MF);
73};
74
77
79 "Remove Loads Into Fake Uses", false, false)
81 "Remove Loads Into Fake Uses", false, false)
82
83bool RemoveLoadsIntoFakeUsesLegacy::runOnMachineFunction(MachineFunction &MF) {
84 if (skipFunction(MF.getFunction()))
85 return false;
86
87 return RemoveLoadsIntoFakeUses().run(MF);
88}
89
93 MFPropsModifier _(*this, MF);
94
97
99 PA.preserveSet<CFGAnalyses>();
100 return PA;
101}
102
104 // Skip this pass if we would use VarLoc-based LDV, as there may be DBG_VALUE
105 // instructions of the restored values that would become invalid.
106 if (!MF.useDebugInstrRef())
107 return false;
108 // Only run this for functions that have fake uses.
109 if (!MF.hasFakeUses())
110 return false;
111
112 bool AnyChanges = false;
113
115 const MachineRegisterInfo *MRI = &MF.getRegInfo();
116 const TargetSubtargetInfo &ST = MF.getSubtarget();
117 const TargetInstrInfo *TII = ST.getInstrInfo();
118 const TargetRegisterInfo *TRI = ST.getRegisterInfo();
119
120 SmallVector<MachineInstr *> RegFakeUses;
122 for (MachineBasicBlock *MBB : post_order(&MF)) {
123 RegFakeUses.clear();
125
127 if (MI.isFakeUse()) {
128 if (MI.getNumOperands() == 0 || !MI.getOperand(0).isReg())
129 continue;
130 // Track the Fake Uses that use these register units so that we can
131 // delete them if we delete the corresponding load.
132 RegFakeUses.push_back(&MI);
133 // Do not record FAKE_USE uses in LivePhysRegs so that we can recognize
134 // otherwise-unused loads.
135 continue;
136 }
137
138 // If the restore size is not std::nullopt then we are dealing with a
139 // reload of a spilled register.
140 if (MI.getRestoreSize(TII)) {
141 Register Reg = MI.getOperand(0).getReg();
142 // Don't delete live physreg defs, or any reserved register defs.
143 if (!LivePhysRegs.available(Reg) || MRI->isReserved(Reg))
144 continue;
145 // There should typically be an exact match between the loaded register
146 // and the FAKE_USE, but sometimes regalloc will choose to load a larger
147 // value than is needed. Therefore, as long as the load isn't used by
148 // anything except at least one FAKE_USE, we will delete it. If it isn't
149 // used by any fake uses, it should still be safe to delete but we
150 // choose to ignore it so that this pass has no side effects unrelated
151 // to fake uses.
152 SmallDenseSet<MachineInstr *> FakeUsesToDelete;
153 for (MachineInstr *&FakeUse : reverse(RegFakeUses)) {
154 if (FakeUse->readsRegister(Reg, TRI)) {
155 FakeUsesToDelete.insert(FakeUse);
156 RegFakeUses.erase(&FakeUse);
157 }
158 }
159 if (!FakeUsesToDelete.empty()) {
160 LLVM_DEBUG(dbgs() << "RemoveLoadsIntoFakeUses: DELETING: " << MI);
161 // Since this load only exists to restore a spilled register and we
162 // haven't, run LiveDebugValues yet, there shouldn't be any DBG_VALUEs
163 // for this load; otherwise, deleting this would be incorrect.
164 MI.eraseFromParent();
165 AnyChanges = true;
166 ++NumLoadsDeleted;
167 for (MachineInstr *FakeUse : FakeUsesToDelete) {
169 << "RemoveLoadsIntoFakeUses: DELETING: " << *FakeUse);
170 FakeUse->eraseFromParent();
171 }
172 NumFakeUsesDeleted += FakeUsesToDelete.size();
173 }
174 continue;
175 }
176
177 // In addition to tracking LivePhysRegs, we need to clear RegFakeUses each
178 // time a register is defined, as existing FAKE_USEs no longer apply to
179 // that register.
180 if (!RegFakeUses.empty()) {
181 for (const MachineOperand &MO : MI.operands()) {
182 if (!MO.isReg())
183 continue;
184 Register Reg = MO.getReg();
185 // We clear RegFakeUses for this register and all subregisters,
186 // because any such FAKE_USE encountered prior is no longer relevant
187 // for later encountered loads.
188 for (MachineInstr *&FakeUse : reverse(RegFakeUses))
189 if (FakeUse->readsRegister(Reg, TRI))
190 RegFakeUses.erase(&FakeUse);
191 }
192 }
194 }
195 }
196
197 return AnyChanges;
198}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
A set of register units.
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
Remove Loads Into Fake Uses
#define DEBUG_TYPE
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
#define LLVM_DEBUG(...)
Definition: Debug.h:119
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
MachineFunctionProperties getRequiredProperties() const override
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:270
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:73
A set of physical registers with utility functions to track liveness when walking backward/forward th...
Definition: LivePhysRegs.h:52
void stepBackward(const MachineInstr &MI)
Simulates liveness when stepping backwards over an instruction(bundle).
void init(const TargetRegisterInfo &TRI)
(re-)initializes and clears the set.
Definition: LivePhysRegs.h:70
bool available(const MachineRegisterInfo &MRI, MCRegister Reg) const
Returns true if register Reg and no aliasing register is in the set.
void addLiveOuts(const MachineBasicBlock &MBB)
Adds all live-out registers of basic block MBB.
A set of register units used to track register liveness.
Definition: LiveRegUnits.h:31
An RAII based helper class to modify MachineFunctionProperties when running pass.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Representation of each machine instruction.
Definition: MachineInstr.h:72
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:283
bool empty() const
Definition: SmallVector.h:82
iterator erase(const_iterator CI)
Definition: SmallVector.h:738
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:663
LLVM_ABI char & RemoveLoadsIntoFakeUsesID
RemoveLoadsIntoFakeUses pass.
iterator_range< po_iterator< T > > post_order(const T &G)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
LLVM_ABI void initializeRemoveLoadsIntoFakeUsesLegacyPass(PassRegistry &)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
bool run(MachineFunction &MF)