LLVM 19.0.0git
MipsOptimizePICCall.cpp
Go to the documentation of this file.
1//===- MipsOptimizePICCall.cpp - Optimize PIC Calls -----------------------===//
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// This pass eliminates unnecessary instructions that set up $gp and replace
10// instructions that load target function addresses with copy instructions.
11//
12//===----------------------------------------------------------------------===//
13
15#include "Mips.h"
16#include "MipsRegisterInfo.h"
17#include "MipsSubtarget.h"
38#include <cassert>
39#include <utility>
40
41using namespace llvm;
42
43#define DEBUG_TYPE "optimize-mips-pic-call"
44
45static cl::opt<bool> LoadTargetFromGOT("mips-load-target-from-got",
46 cl::init(true),
47 cl::desc("Load target address from GOT"),
49
50static cl::opt<bool> EraseGPOpnd("mips-erase-gp-opnd",
51 cl::init(true), cl::desc("Erase GP Operand"),
53
54namespace {
55
57using CntRegP = std::pair<unsigned, unsigned>;
58using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
60using ScopedHTType = ScopedHashTable<ValueType, CntRegP,
61 DenseMapInfo<ValueType>, AllocatorTy>;
62
63class MBBInfo {
64public:
65 MBBInfo(MachineDomTreeNode *N);
66
67 const MachineDomTreeNode *getNode() const;
68 bool isVisited() const;
69 void preVisit(ScopedHTType &ScopedHT);
70 void postVisit();
71
72private:
74 ScopedHTType::ScopeTy *HTScope;
75};
76
77class OptimizePICCall : public MachineFunctionPass {
78public:
79 OptimizePICCall() : MachineFunctionPass(ID) {}
80
81 StringRef getPassName() const override { return "Mips OptimizePICCall"; }
82
84
85 void getAnalysisUsage(AnalysisUsage &AU) const override {
88 }
89
90private:
91 /// Visit MBB.
92 bool visitNode(MBBInfo &MBBI);
93
94 /// Test if MI jumps to a function via a register.
95 ///
96 /// Also, return the virtual register containing the target function's address
97 /// and the underlying object in Reg and Val respectively, if the function's
98 /// address can be resolved lazily.
99 bool isCallViaRegister(MachineInstr &MI, unsigned &Reg,
100 ValueType &Val) const;
101
102 /// Return the number of instructions that dominate the current
103 /// instruction and load the function address from object Entry.
104 unsigned getCount(ValueType Entry);
105
106 /// Return the destination virtual register of the last instruction
107 /// that loads from object Entry.
108 unsigned getReg(ValueType Entry);
109
110 /// Update ScopedHT.
111 void incCntAndSetReg(ValueType Entry, unsigned Reg);
112
113 ScopedHTType ScopedHT;
114
115 static char ID;
116};
117
118} // end of anonymous namespace
119
120char OptimizePICCall::ID = 0;
121
122/// Return the first MachineOperand of MI if it is a used virtual register.
124 if (MI.getNumOperands() == 0)
125 return nullptr;
126
127 MachineOperand &MO = MI.getOperand(0);
128
129 if (!MO.isReg() || !MO.isUse() || !MO.getReg().isVirtual())
130 return nullptr;
131
132 return &MO;
133}
134
135/// Return type of register Reg.
138 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
139 assert(TRI.legalclasstypes_end(*RC) - TRI.legalclasstypes_begin(*RC) == 1);
140 return *TRI.legalclasstypes_begin(*RC);
141}
142
143/// Do the following transformation:
144///
145/// jalr $vreg
146/// =>
147/// copy $t9, $vreg
148/// jalr $t9
151 MachineFunction &MF = *MBB->getParent();
153 Register SrcReg = I->getOperand(0).getReg();
154 unsigned DstReg = getRegTy(SrcReg, MF) == MVT::i32 ? Mips::T9 : Mips::T9_64;
155 BuildMI(*MBB, I, I->getDebugLoc(), TII.get(TargetOpcode::COPY), DstReg)
156 .addReg(SrcReg);
157 I->getOperand(0).setReg(DstReg);
158}
159
160/// Search MI's operands for register GP and erase it.
162 if (!EraseGPOpnd)
163 return;
164
165 MachineFunction &MF = *MI.getParent()->getParent();
166 MVT::SimpleValueType Ty = getRegTy(MI.getOperand(0).getReg(), MF);
167 unsigned Reg = Ty == MVT::i32 ? Mips::GP : Mips::GP_64;
168
169 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
170 MachineOperand &MO = MI.getOperand(I);
171 if (MO.isReg() && MO.getReg() == Reg) {
172 MI.removeOperand(I);
173 return;
174 }
175 }
176
177 llvm_unreachable(nullptr);
178}
179
180MBBInfo::MBBInfo(MachineDomTreeNode *N) : Node(N), HTScope(nullptr) {}
181
182const MachineDomTreeNode *MBBInfo::getNode() const { return Node; }
183
184bool MBBInfo::isVisited() const { return HTScope; }
185
186void MBBInfo::preVisit(ScopedHTType &ScopedHT) {
187 HTScope = new ScopedHTType::ScopeTy(ScopedHT);
188}
189
190void MBBInfo::postVisit() {
191 delete HTScope;
192}
193
194// OptimizePICCall methods.
195bool OptimizePICCall::runOnMachineFunction(MachineFunction &F) {
196 if (F.getSubtarget<MipsSubtarget>().inMips16Mode())
197 return false;
198
199 // Do a pre-order traversal of the dominator tree.
201 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
202 bool Changed = false;
203
204 SmallVector<MBBInfo, 8> WorkList(1, MBBInfo(MDT->getRootNode()));
205
206 while (!WorkList.empty()) {
207 MBBInfo &MBBI = WorkList.back();
208
209 // If this MBB has already been visited, destroy the scope for the MBB and
210 // pop it from the work list.
211 if (MBBI.isVisited()) {
212 MBBI.postVisit();
213 WorkList.pop_back();
214 continue;
215 }
216
217 // Visit the MBB and add its children to the work list.
218 MBBI.preVisit(ScopedHT);
219 Changed |= visitNode(MBBI);
220 const MachineDomTreeNode *Node = MBBI.getNode();
221 WorkList.append(Node->begin(), Node->end());
222 }
223
224 return Changed;
225}
226
227bool OptimizePICCall::visitNode(MBBInfo &MBBI) {
228 bool Changed = false;
229 MachineBasicBlock *MBB = MBBI.getNode()->getBlock();
230
231 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
232 ++I) {
233 unsigned Reg;
235
236 // Skip instructions that are not call instructions via registers.
237 if (!isCallViaRegister(*I, Reg, Entry))
238 continue;
239
240 Changed = true;
241 unsigned N = getCount(Entry);
242
243 if (N != 0) {
244 // If a function has been called more than twice, we do not have to emit a
245 // load instruction to get the function address from the GOT, but can
246 // instead reuse the address that has been loaded before.
247 if (N >= 2 && !LoadTargetFromGOT)
249
250 // Erase the $gp operand if this isn't the first time a function has
251 // been called. $gp needs to be set up only if the function call can go
252 // through a lazy binding stub.
253 eraseGPOpnd(*I);
254 }
255
256 if (Entry)
257 incCntAndSetReg(Entry, Reg);
258
260 }
261
262 return Changed;
263}
264
265bool OptimizePICCall::isCallViaRegister(MachineInstr &MI, unsigned &Reg,
266 ValueType &Val) const {
267 if (!MI.isCall())
268 return false;
269
271
272 // Return if MI is not a function call via a register.
273 if (!MO)
274 return false;
275
276 // Get the instruction that loads the function address from the GOT.
277 Reg = MO->getReg();
278 Val = nullptr;
279 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
280 MachineInstr *DefMI = MRI.getVRegDef(Reg);
281
282 assert(DefMI);
283
284 // See if DefMI is an instruction that loads from a GOT entry that holds the
285 // address of a lazy binding stub.
286 if (!DefMI->mayLoad() || DefMI->getNumOperands() < 3)
287 return true;
288
289 unsigned Flags = DefMI->getOperand(2).getTargetFlags();
290
291 if (Flags != MipsII::MO_GOT_CALL && Flags != MipsII::MO_CALL_LO16)
292 return true;
293
294 // Return the underlying object for the GOT entry in Val.
296 Val = (*DefMI->memoperands_begin())->getValue();
297 if (!Val)
298 Val = (*DefMI->memoperands_begin())->getPseudoValue();
299 return true;
300}
301
302unsigned OptimizePICCall::getCount(ValueType Entry) {
303 return ScopedHT.lookup(Entry).first;
304}
305
306unsigned OptimizePICCall::getReg(ValueType Entry) {
307 unsigned Reg = ScopedHT.lookup(Entry).second;
308 assert(Reg);
309 return Reg;
310}
311
312void OptimizePICCall::incCntAndSetReg(ValueType Entry, unsigned Reg) {
313 CntRegP P = ScopedHT.lookup(Entry);
314 ScopedHT.insert(Entry, std::make_pair(P.first + 1, Reg));
315}
316
317/// Return an OptimizeCall object.
319 return new OptimizePICCall();
320}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder MachineInstrBuilder & DefMI
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file defines the BumpPtrAllocator interface.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static cl::opt< bool > LoadTargetFromGOT("mips-load-target-from-got", cl::init(true), cl::desc("Load target address from GOT"), cl::Hidden)
static void setCallTargetReg(MachineBasicBlock *MBB, MachineBasicBlock::iterator I)
Do the following transformation:
static void eraseGPOpnd(MachineInstr &MI)
Search MI's operands for register GP and erase it.
static MachineOperand * getCallTargetRegOpnd(MachineInstr &MI)
Return the first MachineOperand of MI if it is a used virtual register.
static cl::opt< bool > EraseGPOpnd("mips-erase-gp-opnd", cl::init(true), cl::desc("Erase GP Operand"), cl::Hidden)
static MVT::SimpleValueType getRegTy(unsigned Reg, MachineFunction &MF)
Return type of register Reg.
#define P(N)
This file defines the PointerUnion class, which is a discriminated union of pointer types.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
Base class for the actual dominator tree node.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineDomTreeNode * getRootNode() const
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
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.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:572
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
Definition: MachineInstr.h:815
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:800
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:579
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
unsigned getTargetFlags() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
bool inMips16Mode() const
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
RecyclingAllocator - This class wraps an Allocator, adding the functionality of recycling deleted obj...
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition: COFF.h:811
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ MO_GOT_CALL
MO_GOT_CALL - Represents the offset into the global offset table at which the address of a call site ...
Definition: MipsBaseInfo.h:44
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createMipsOptimizePICCallPass()
Return an OptimizeCall object.
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition: Allocator.h:380
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
#define N
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:52