LLVM 23.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
51
56
58 return MachineFunctionProperties().setNoVRegs();
59 }
60
61 StringRef getPassName() const override {
62 return "Remove Loads Into Fake Uses";
63 }
64
65 bool runOnMachineFunction(MachineFunction &MF) override;
66};
67
69 bool run(MachineFunction &MF);
70};
71
74
76 "Remove Loads Into Fake Uses", false, false)
78 "Remove Loads Into Fake Uses", false, false)
79
81 if (skipFunction(MF.getFunction()))
82 return false;
83
84 return RemoveLoadsIntoFakeUses().run(MF);
85}
86
90 MFPropsModifier _(*this, MF);
91
94
96 PA.preserveSet<CFGAnalyses>();
97 return PA;
98}
99
101 // Skip this pass if we would use VarLoc-based LDV, as there may be DBG_VALUE
102 // instructions of the restored values that would become invalid.
103 if (!MF.useDebugInstrRef())
104 return false;
105 // Only run this for functions that have fake uses.
106 if (!MF.hasFakeUses())
107 return false;
108
109 bool AnyChanges = false;
110
112 const MachineRegisterInfo *MRI = &MF.getRegInfo();
113 const TargetSubtargetInfo &ST = MF.getSubtarget();
114 const TargetInstrInfo *TII = ST.getInstrInfo();
115 const TargetRegisterInfo *TRI = ST.getRegisterInfo();
116
117 SmallVector<MachineInstr *> RegFakeUses;
119 for (MachineBasicBlock *MBB : post_order(&MF)) {
120 RegFakeUses.clear();
122
124 if (MI.isFakeUse()) {
125 if (MI.getNumOperands() == 0 || !MI.getOperand(0).isReg())
126 continue;
127 // Track the Fake Uses that use these register units so that we can
128 // delete them if we delete the corresponding load.
129 RegFakeUses.push_back(&MI);
130 // Do not record FAKE_USE uses in LivePhysRegs so that we can recognize
131 // otherwise-unused loads.
132 continue;
133 }
134
135 // If the restore size is not std::nullopt then we are dealing with a
136 // reload of a spilled register.
137 if (MI.getRestoreSize(TII)) {
138 Register Reg = MI.getOperand(0).getReg();
139 // Don't delete live physreg defs, or any reserved register defs.
140 if (!LivePhysRegs.available(Reg) || MRI->isReserved(Reg))
141 continue;
142 // There should typically be an exact match between the loaded register
143 // and the FAKE_USE, but sometimes regalloc will choose to load a larger
144 // value than is needed. Therefore, as long as the load isn't used by
145 // anything except at least one FAKE_USE, we will delete it. If it isn't
146 // used by any fake uses, it should still be safe to delete but we
147 // choose to ignore it so that this pass has no side effects unrelated
148 // to fake uses.
149 SmallDenseSet<MachineInstr *> FakeUsesToDelete;
150 for (MachineInstr *&FakeUse : reverse(RegFakeUses)) {
151 if (FakeUse->readsRegister(Reg, TRI)) {
152 FakeUsesToDelete.insert(FakeUse);
153 RegFakeUses.erase(&FakeUse);
154 }
155 }
156 if (!FakeUsesToDelete.empty()) {
157 LLVM_DEBUG(dbgs() << "RemoveLoadsIntoFakeUses: DELETING: " << MI);
158 // Since this load only exists to restore a spilled register and we
159 // haven't, run LiveDebugValues yet, there shouldn't be any DBG_VALUEs
160 // for this load; otherwise, deleting this would be incorrect.
161 MI.eraseFromParent();
162 AnyChanges = true;
163 ++NumLoadsDeleted;
164 for (MachineInstr *FakeUse : FakeUsesToDelete) {
166 << "RemoveLoadsIntoFakeUses: DELETING: " << *FakeUse);
167 FakeUse->eraseFromParent();
168 }
169 NumFakeUsesDeleted += FakeUsesToDelete.size();
170 }
171 continue;
172 }
173
174 // In addition to tracking LivePhysRegs, we need to clear RegFakeUses each
175 // time a register is defined, as existing FAKE_USEs no longer apply to
176 // that register.
177 if (!RegFakeUses.empty()) {
178 for (const MachineOperand &MO : MI.operands()) {
179 if (!MO.isReg())
180 continue;
181 Register Reg = MO.getReg();
182 // We clear RegFakeUses for this register and all subregisters,
183 // because any such FAKE_USE encountered prior is no longer relevant
184 // for later encountered loads.
185 for (MachineInstr *&FakeUse : reverse(RegFakeUses))
186 if (FakeUse->readsRegister(Reg, TRI))
187 RegFakeUses.erase(&FakeUse);
188 }
189 }
191 }
192 }
193
194 return AnyChanges;
195}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
#define DEBUG_TYPE
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.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
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.
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
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:188
A set of physical registers with utility functions to track liveness when walking backward/forward th...
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.
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.
An RAII based helper class to modify MachineFunctionProperties when running pass.
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.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
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:20
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:291
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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:202
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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:632
LLVM_ABI char & RemoveLoadsIntoFakeUsesID
RemoveLoadsIntoFakeUses pass.
iterator_range< po_iterator< T > > post_order(const T &G)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
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)