LLVM 24.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"
36#include "llvm/IR/Analysis.h"
40#include <cassert>
41#include <utility>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "optimize-mips-pic-call"
46
47namespace {
48
50using CntRegP = std::pair<unsigned, unsigned>;
51using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
53using ScopedHTType = ScopedHashTable<ValueType, CntRegP,
54 DenseMapInfo<ValueType>, AllocatorTy>;
55
56class MBBInfo {
57public:
58 MBBInfo(MachineDomTreeNode *N);
59
60 const MachineDomTreeNode *getNode() const;
61 bool isVisited() const;
62 void preVisit(ScopedHTType &ScopedHT);
63 void postVisit();
64
65private:
67 ScopedHTType::ScopeTy *HTScope;
68};
69
70class MipsOptimizePICCallLegacy : public MachineFunctionPass {
71public:
72 MipsOptimizePICCallLegacy() : MachineFunctionPass(ID) {}
73
74 StringRef getPassName() const override { return "Mips OptimizePICCall"; }
75
76 bool runOnMachineFunction(MachineFunction &F) override;
77
78 void getAnalysisUsage(AnalysisUsage &AU) const override {
80 AU.setPreservesCFG();
82 }
83
84private:
85 static char ID;
86};
87
88} // end of anonymous namespace
89
90char MipsOptimizePICCallLegacy::ID = 0;
91
92/// Return the first MachineOperand of MI if it is a used virtual register.
94 if (MI.getNumOperands() == 0)
95 return nullptr;
96
97 MachineOperand &MO = MI.getOperand(0);
98
99 if (!MO.isReg() || !MO.isUse() || !MO.getReg().isVirtual())
100 return nullptr;
101
102 return &MO;
103}
104
105/// Return type of register Reg.
109 assert(TRI.legalclasstypes_end(*RC) - TRI.legalclasstypes_begin(*RC) == 1);
110 return *TRI.legalclasstypes_begin(*RC);
111}
112
113/// Do the following transformation:
114///
115/// jalr $vreg
116/// =>
117/// copy $t9, $vreg
118/// jalr $t9
121 MachineFunction &MF = *MBB->getParent();
123 Register SrcReg = I->getOperand(0).getReg();
124 MCRegister DstReg = MF.getSubtarget<MipsSubtarget>().getABI().getTempReg(
125 9, getRegTy(SrcReg, MF) != MVT::i32);
126 BuildMI(*MBB, I, I->getDebugLoc(), TII.get(TargetOpcode::COPY), DstReg)
127 .addReg(SrcReg);
128 I->getOperand(0).setReg(DstReg);
129}
130
131/// Search MI's operands for register GP and erase it.
132static bool eraseGPOpnd(const MipsOptions &CLOpts, MachineInstr &MI) {
133 if (!CLOpts.erase_gp_opnd)
134 return false;
135
136 MachineFunction &MF = *MI.getParent()->getParent();
137 MVT::SimpleValueType Ty = getRegTy(MI.getOperand(0).getReg(), MF);
138 unsigned Reg = Ty == MVT::i32 ? Mips::GP : Mips::GP_64;
139
140 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
141 MachineOperand &MO = MI.getOperand(I);
142 if (MO.isReg() && MO.getReg() == Reg) {
143 MI.removeOperand(I);
144 return true;
145 }
146 }
147
148 llvm_unreachable(nullptr);
149}
150
151MBBInfo::MBBInfo(MachineDomTreeNode *N) : Node(N), HTScope(nullptr) {}
152
153const MachineDomTreeNode *MBBInfo::getNode() const { return Node; }
154
155bool MBBInfo::isVisited() const { return HTScope; }
156
157void MBBInfo::preVisit(ScopedHTType &ScopedHT) {
158 HTScope = new ScopedHTType::ScopeTy(ScopedHT);
159}
160
161void MBBInfo::postVisit() {
162 delete HTScope;
163}
164
165/// Return the number of instructions that dominate the current
166/// instruction and load the function address from object Entry.
167static unsigned getCount(ValueType Entry, ScopedHTType &ScopedHT) {
168 return ScopedHT.lookup(Entry).first;
169}
170
171/// Return the destination virtual register of the last instruction
172/// that loads from object Entry.
173static unsigned getReg(ValueType Entry, ScopedHTType &ScopedHT) {
174 unsigned Reg = ScopedHT.lookup(Entry).second;
175 assert(Reg);
176 return Reg;
177}
178
179/// Update ScopedHT.
180static void incCntAndSetReg(ValueType Entry, unsigned Reg,
181 ScopedHTType &ScopedHT) {
182 CntRegP P = ScopedHT.lookup(Entry);
183 ScopedHT.insert(Entry, std::make_pair(P.first + 1, Reg));
184}
185
186/// Test if MI jumps to a function via a register.
187///
188/// Also, return the virtual register containing the target function's address
189/// and the underlying object in Reg and Val respectively, if the function's
190/// address can be resolved lazily.
191static bool isCallViaRegister(MachineInstr &MI, unsigned &Reg, ValueType &Val) {
192 if (!MI.isCall())
193 return false;
194
196
197 // Return if MI is not a function call via a register.
198 if (!MO)
199 return false;
200
201 // Get the instruction that loads the function address from the GOT.
202 Reg = MO->getReg();
203 Val = nullptr;
204 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
205 MachineInstr *DefMI = MRI.getVRegDef(Reg);
206
207 assert(DefMI);
208
209 // See if DefMI is an instruction that loads from a GOT entry that holds the
210 // address of a lazy binding stub.
211 if (!DefMI->mayLoad() || DefMI->getNumOperands() < 3)
212 return true;
213
214 unsigned Flags = DefMI->getOperand(2).getTargetFlags();
215
216 if (Flags != MipsII::MO_GOT_CALL && Flags != MipsII::MO_CALL_LO16)
217 return true;
218
219 // Return the underlying object for the GOT entry in Val.
220 assert(DefMI->hasOneMemOperand());
221 Val = (*DefMI->memoperands_begin())->getValue();
222 if (!Val)
223 Val = (*DefMI->memoperands_begin())->getPseudoValue();
224 return true;
225}
226
227/// Visit MBB.
228static bool visitNode(MBBInfo &MBBI, ScopedHTType &ScopedHT) {
229 bool Changed = false;
230 MachineBasicBlock *MBB = MBBI.getNode()->getBlock();
231 const MipsSubtarget &STI = MBB->getParent()->getSubtarget<MipsSubtarget>();
232 const MipsOptions &CLOpts = STI.getCLOpts();
233 const MipsRegisterInfo &TRI = *STI.getRegisterInfo();
234
235 // Definition of $gp reaching the current instruction.
236 MachineOperand *GPDef = nullptr;
237
238 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
239 ++I) {
240 unsigned Reg;
241 ValueType Entry;
242
243 // Handle call instructions via registers.
244 if (isCallViaRegister(*I, Reg, Entry)) {
245 Changed = true;
246 unsigned N = getCount(Entry, ScopedHT);
247
248 if (N != 0) {
249 // If a function has been called more than twice, we do not have to emit
250 // a load instruction to get the function address from the GOT, but can
251 // instead reuse the address that has been loaded before.
252 if (N >= 2 && !CLOpts.load_target_from_got)
254
255 // Erase the $gp operand if this isn't the first time a function has
256 // been called. $gp needs to be set up only if the function call can go
257 // through a lazy binding stub.
258 if (eraseGPOpnd(CLOpts, *I) && GPDef)
259 GPDef->setIsDead();
260 }
261
262 if (Entry)
264
266 }
267
268 if (MachineOperand *Def = I->findRegisterDefOperand(Mips::GP, &TRI))
269 GPDef = Def;
270 else if (I->readsRegister(Mips::GP, &TRI))
271 GPDef = nullptr;
272 }
273
274 return Changed;
275}
276
277// OptimizePICCall methods.
278static bool
281 if (F.getSubtarget<MipsSubtarget>().inMips16Mode())
282 return false;
283
284 // Do a pre-order traversal of the dominator tree.
285 MachineDominatorTree *MDT = GetMDT();
286 bool Changed = false;
287
288 SmallVector<MBBInfo, 8> WorkList(1, MBBInfo(MDT->getRootNode()));
289 ScopedHTType ScopedHT;
290
291 while (!WorkList.empty()) {
292 MBBInfo &MBBI = WorkList.back();
293
294 // If this MBB has already been visited, destroy the scope for the MBB and
295 // pop it from the work list.
296 if (MBBI.isVisited()) {
297 MBBI.postVisit();
298 WorkList.pop_back();
299 continue;
300 }
301
302 // Visit the MBB and add its children to the work list.
303 MBBI.preVisit(ScopedHT);
305 const MachineDomTreeNode *Node = MBBI.getNode();
306 WorkList.append(Node->begin(), Node->end());
307 }
308
309 return Changed;
310}
311
312/// Return an OptimizeCall object.
314 return new MipsOptimizePICCallLegacy();
315}
316
317bool MipsOptimizePICCallLegacy::runOnMachineFunction(MachineFunction &MF) {
318 return optimizePICCallsInFunction(MF, [&]() {
319 return &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
320 });
321}
322
323PreservedAnalyses
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
ScopedHashTable< Value *, Align, DenseMapInfo< Value * >, BumpPtrAllocator > ScopedHT
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static void setCallTargetReg(MachineBasicBlock *MBB, MachineBasicBlock::iterator I)
Do the following transformation:
static MachineOperand * getCallTargetRegOpnd(MachineInstr &MI)
Return the first MachineOperand of MI if it is a used virtual register.
static bool isCallViaRegister(MachineInstr &MI, unsigned &Reg, ValueType &Val)
Test if MI jumps to a function via a register.
static void incCntAndSetReg(ValueType Entry, unsigned Reg, ScopedHTType &ScopedHT)
Update ScopedHT.
static bool visitNode(MBBInfo &MBBI, ScopedHTType &ScopedHT)
Visit MBB.
static MVT::SimpleValueType getRegTy(unsigned Reg, MachineFunction &MF)
Return type of register Reg.
static bool optimizePICCallsInFunction(MachineFunction &F, function_ref< MachineDominatorTree *()> GetMDT)
static unsigned getCount(ValueType Entry, ScopedHTType &ScopedHT)
Return the number of instructions that dominate the current instruction and load the function address...
static bool eraseGPOpnd(const MipsOptions &CLOpts, MachineInstr &MI)
Search MI's operands for register GP and erase it.
#define P(N)
This file defines the PointerUnion class, which is a discriminated union of pointer types.
MachineRegisterInfo & MRI
This file defines the SmallVector class.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
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, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
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.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool inMips16Mode() const
const MipsOptions & getCLOpts() const
const MipsRegisterInfo * getRegisterInfo() const override
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
RecyclingAllocator - This class wraps an Allocator, adding the functionality of recycling deleted obj...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
An efficient, type-erasing, non-owning reference to a callable.
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr MCPhysReg GP_64
constexpr MCPhysReg GP
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
FunctionPass * createMipsOptimizePICCallLegacyPass()
Return an OptimizeCall object.
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
An information struct used to provide DenseMap with the various necessary components for a given valu...