LLVM  9.0.0svn
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"
18 #include "llvm/ADT/PointerUnion.h"
20 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/Support/Allocator.h"
38 #include <cassert>
39 #include <utility>
40 #include <vector>
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "optimize-mips-pic-call"
45 
46 static cl::opt<bool> LoadTargetFromGOT("mips-load-target-from-got",
47  cl::init(true),
48  cl::desc("Load target address from GOT"),
49  cl::Hidden);
50 
51 static cl::opt<bool> EraseGPOpnd("mips-erase-gp-opnd",
52  cl::init(true), cl::desc("Erase GP Operand"),
53  cl::Hidden);
54 
55 namespace {
56 
58 using CntRegP = std::pair<unsigned, unsigned>;
59 using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
61 using ScopedHTType = ScopedHashTable<ValueType, CntRegP,
62  DenseMapInfo<ValueType>, AllocatorTy>;
63 
64 class MBBInfo {
65 public:
66  MBBInfo(MachineDomTreeNode *N);
67 
68  const MachineDomTreeNode *getNode() const;
69  bool isVisited() const;
70  void preVisit(ScopedHTType &ScopedHT);
71  void postVisit();
72 
73 private:
74  MachineDomTreeNode *Node;
75  ScopedHTType::ScopeTy *HTScope;
76 };
77 
78 class OptimizePICCall : public MachineFunctionPass {
79 public:
80  OptimizePICCall() : MachineFunctionPass(ID) {}
81 
82  StringRef getPassName() const override { return "Mips OptimizePICCall"; }
83 
84  bool runOnMachineFunction(MachineFunction &F) override;
85 
86  void getAnalysisUsage(AnalysisUsage &AU) const override {
89  }
90 
91 private:
92  /// Visit MBB.
93  bool visitNode(MBBInfo &MBBI);
94 
95  /// Test if MI jumps to a function via a register.
96  ///
97  /// Also, return the virtual register containing the target function's address
98  /// and the underlying object in Reg and Val respectively, if the function's
99  /// address can be resolved lazily.
100  bool isCallViaRegister(MachineInstr &MI, unsigned &Reg,
101  ValueType &Val) const;
102 
103  /// Return the number of instructions that dominate the current
104  /// instruction and load the function address from object Entry.
105  unsigned getCount(ValueType Entry);
106 
107  /// Return the destination virtual register of the last instruction
108  /// that loads from object Entry.
109  unsigned getReg(ValueType Entry);
110 
111  /// Update ScopedHT.
112  void incCntAndSetReg(ValueType Entry, unsigned Reg);
113 
114  ScopedHTType ScopedHT;
115 
116  static char ID;
117 };
118 
119 } // end of anonymous namespace
120 
121 char OptimizePICCall::ID = 0;
122 
123 /// Return the first MachineOperand of MI if it is a used virtual register.
125  if (MI.getNumOperands() == 0)
126  return nullptr;
127 
128  MachineOperand &MO = MI.getOperand(0);
129 
130  if (!MO.isReg() || !MO.isUse() ||
132  return nullptr;
133 
134  return &MO;
135 }
136 
137 /// Return type of register Reg.
140  const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
141  assert(TRI.legalclasstypes_end(*RC) - TRI.legalclasstypes_begin(*RC) == 1);
142  return *TRI.legalclasstypes_begin(*RC);
143 }
144 
145 /// Do the following transformation:
146 ///
147 /// jalr $vreg
148 /// =>
149 /// copy $t9, $vreg
150 /// jalr $t9
153  MachineFunction &MF = *MBB->getParent();
154  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
155  unsigned SrcReg = I->getOperand(0).getReg();
156  unsigned DstReg = getRegTy(SrcReg, MF) == MVT::i32 ? Mips::T9 : Mips::T9_64;
157  BuildMI(*MBB, I, I->getDebugLoc(), TII.get(TargetOpcode::COPY), DstReg)
158  .addReg(SrcReg);
159  I->getOperand(0).setReg(DstReg);
160 }
161 
162 /// Search MI's operands for register GP and erase it.
163 static void eraseGPOpnd(MachineInstr &MI) {
164  if (!EraseGPOpnd)
165  return;
166 
167  MachineFunction &MF = *MI.getParent()->getParent();
169  unsigned Reg = Ty == MVT::i32 ? Mips::GP : Mips::GP_64;
170 
171  for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
172  MachineOperand &MO = MI.getOperand(I);
173  if (MO.isReg() && MO.getReg() == Reg) {
174  MI.RemoveOperand(I);
175  return;
176  }
177  }
178 
179  llvm_unreachable(nullptr);
180 }
181 
182 MBBInfo::MBBInfo(MachineDomTreeNode *N) : Node(N), HTScope(nullptr) {}
183 
184 const MachineDomTreeNode *MBBInfo::getNode() const { return Node; }
185 
186 bool MBBInfo::isVisited() const { return HTScope; }
187 
188 void MBBInfo::preVisit(ScopedHTType &ScopedHT) {
189  HTScope = new ScopedHTType::ScopeTy(ScopedHT);
190 }
191 
192 void MBBInfo::postVisit() {
193  delete HTScope;
194 }
195 
196 // OptimizePICCall methods.
197 bool OptimizePICCall::runOnMachineFunction(MachineFunction &F) {
198  if (static_cast<const MipsSubtarget &>(F.getSubtarget()).inMips16Mode())
199  return false;
200 
201  // Do a pre-order traversal of the dominator tree.
202  MachineDominatorTree *MDT = &getAnalysis<MachineDominatorTree>();
203  bool Changed = false;
204 
205  SmallVector<MBBInfo, 8> WorkList(1, MBBInfo(MDT->getRootNode()));
206 
207  while (!WorkList.empty()) {
208  MBBInfo &MBBI = WorkList.back();
209 
210  // If this MBB has already been visited, destroy the scope for the MBB and
211  // pop it from the work list.
212  if (MBBI.isVisited()) {
213  MBBI.postVisit();
214  WorkList.pop_back();
215  continue;
216  }
217 
218  // Visit the MBB and add its children to the work list.
219  MBBI.preVisit(ScopedHT);
220  Changed |= visitNode(MBBI);
221  const MachineDomTreeNode *Node = MBBI.getNode();
222  const std::vector<MachineDomTreeNode *> &Children = Node->getChildren();
223  WorkList.append(Children.begin(), Children.end());
224  }
225 
226  return Changed;
227 }
228 
229 bool OptimizePICCall::visitNode(MBBInfo &MBBI) {
230  bool Changed = false;
231  MachineBasicBlock *MBB = MBBI.getNode()->getBlock();
232 
233  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
234  ++I) {
235  unsigned Reg;
236  ValueType Entry;
237 
238  // Skip instructions that are not call instructions via registers.
239  if (!isCallViaRegister(*I, Reg, Entry))
240  continue;
241 
242  Changed = true;
243  unsigned N = getCount(Entry);
244 
245  if (N != 0) {
246  // If a function has been called more than twice, we do not have to emit a
247  // load instruction to get the function address from the GOT, but can
248  // instead reuse the address that has been loaded before.
249  if (N >= 2 && !LoadTargetFromGOT)
250  getCallTargetRegOpnd(*I)->setReg(getReg(Entry));
251 
252  // Erase the $gp operand if this isn't the first time a function has
253  // been called. $gp needs to be set up only if the function call can go
254  // through a lazy binding stub.
255  eraseGPOpnd(*I);
256  }
257 
258  if (Entry)
259  incCntAndSetReg(Entry, Reg);
260 
261  setCallTargetReg(MBB, I);
262  }
263 
264  return Changed;
265 }
266 
267 bool OptimizePICCall::isCallViaRegister(MachineInstr &MI, unsigned &Reg,
268  ValueType &Val) const {
269  if (!MI.isCall())
270  return false;
271 
273 
274  // Return if MI is not a function call via a register.
275  if (!MO)
276  return false;
277 
278  // Get the instruction that loads the function address from the GOT.
279  Reg = MO->getReg();
280  Val = nullptr;
282  MachineInstr *DefMI = MRI.getVRegDef(Reg);
283 
284  assert(DefMI);
285 
286  // See if DefMI is an instruction that loads from a GOT entry that holds the
287  // address of a lazy binding stub.
288  if (!DefMI->mayLoad() || DefMI->getNumOperands() < 3)
289  return true;
290 
291  unsigned Flags = DefMI->getOperand(2).getTargetFlags();
292 
293  if (Flags != MipsII::MO_GOT_CALL && Flags != MipsII::MO_CALL_LO16)
294  return true;
295 
296  // Return the underlying object for the GOT entry in Val.
297  assert(DefMI->hasOneMemOperand());
298  Val = (*DefMI->memoperands_begin())->getValue();
299  if (!Val)
300  Val = (*DefMI->memoperands_begin())->getPseudoValue();
301  return true;
302 }
303 
304 unsigned OptimizePICCall::getCount(ValueType Entry) {
305  return ScopedHT.lookup(Entry).first;
306 }
307 
308 unsigned OptimizePICCall::getReg(ValueType Entry) {
309  unsigned Reg = ScopedHT.lookup(Entry).second;
310  assert(Reg);
311  return Reg;
312 }
313 
314 void OptimizePICCall::incCntAndSetReg(ValueType Entry, unsigned Reg) {
315  CntRegP P = ScopedHT.lookup(Entry);
316  ScopedHT.insert(Entry, std::make_pair(P.first + 1, Reg));
317 }
318 
319 /// Return an OptimizeCall object.
321  return new OptimizePICCall();
322 }
unsigned getTargetFlags() const
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:632
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
unsigned Reg
static MachineOperand * getCallTargetRegOpnd(MachineInstr &MI)
Return the first MachineOperand of MI if it is a used virtual register.
unsigned const TargetRegisterInfo * TRI
F(f)
static void setCallTargetReg(MachineBasicBlock *MBB, MachineBasicBlock::iterator I)
Do the following transformation:
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
AnalysisUsage & addRequired()
vt_iterator legalclasstypes_end(const TargetRegisterClass &RC) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
RecyclingAllocator - This class wraps an Allocator, adding the functionality of recycling deleted obj...
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
Base class for the actual dominator tree node.
const std::vector< DomTreeNodeBase * > & getChildren() const
virtual const TargetInstrInfo * getInstrInfo() const
TargetInstrInfo - Interface to description of machine instruction set.
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition: Allocator.h:434
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
MO_GOT_CALL - Represents the offset into the global offset table at which the address of a call site ...
Definition: MipsBaseInfo.h:43
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
FunctionPass * createMipsOptimizePICCallPass()
Return an OptimizeCall object.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Represent the analysis usage information of a pass.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
Definition: MachineInstr.h:548
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
static cl::opt< bool > LoadTargetFromGOT("mips-load-target-from-got", cl::init(true), cl::desc("Load target address from GOT"), cl::Hidden)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:533
MachineDomTreeNode * getRootNode() const
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
MachineInstrBuilder MachineInstrBuilder & DefMI
static cl::opt< bool > EraseGPOpnd("mips-erase-gp-opnd", cl::init(true), cl::desc("Erase GP Operand"), cl::Hidden)
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:386
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:63
static void eraseGPOpnd(MachineInstr &MI)
Search MI&#39;s operands for register GP and erase it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Definition: MachineInstr.h:806
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static MVT::SimpleValueType getRegTy(unsigned Reg, MachineFunction &MF)
Return type of register Reg.
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
void RemoveOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with...
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:86
vt_iterator legalclasstypes_begin(const TargetRegisterClass &RC) const
Loop over all of the value types that can be represented by values in the given register class...