MipsInstrInfo.cpp revision 0bf3dfbef60e36827df9c7e12b62503f1e345cd0
1//===- MipsInstrInfo.cpp - Mips Instruction Information --------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9//
10// This file contains the Mips implementation of the TargetInstrInfo class.
11//
12//===---------------------------------------------------------------------===//
13
14#include "MipsInstrInfo.h"
15#include "MipsTargetMachine.h"
16#include "MipsMachineFunction.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/CodeGen/MachineRegisterInfo.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "MipsGenInstrInfo.inc"
22
23using namespace llvm;
24
25MipsInstrInfo::MipsInstrInfo(MipsTargetMachine &tm)
26  : TargetInstrInfoImpl(MipsInsts, array_lengthof(MipsInsts)),
27    TM(tm), RI(*TM.getSubtargetImpl(), *this) {}
28
29static bool isZeroImm(const MachineOperand &op) {
30  return op.isImm() && op.getImm() == 0;
31}
32
33/// isLoadFromStackSlot - If the specified machine instruction is a direct
34/// load from a stack slot, return the virtual or physical register number of
35/// the destination along with the FrameIndex of the loaded stack slot.  If
36/// not, return 0.  This predicate must return 0 if the instruction has
37/// any side effects other than loading from the stack slot.
38unsigned MipsInstrInfo::
39isLoadFromStackSlot(const MachineInstr *MI, int &FrameIndex) const
40{
41  if ((MI->getOpcode() == Mips::LW) || (MI->getOpcode() == Mips::LWC1) ||
42      (MI->getOpcode() == Mips::LDC1)) {
43    if ((MI->getOperand(2).isFI()) && // is a stack slot
44        (MI->getOperand(1).isImm()) &&  // the imm is zero
45        (isZeroImm(MI->getOperand(1)))) {
46      FrameIndex = MI->getOperand(2).getIndex();
47      return MI->getOperand(0).getReg();
48    }
49  }
50
51  return 0;
52}
53
54/// isStoreToStackSlot - If the specified machine instruction is a direct
55/// store to a stack slot, return the virtual or physical register number of
56/// the source reg along with the FrameIndex of the loaded stack slot.  If
57/// not, return 0.  This predicate must return 0 if the instruction has
58/// any side effects other than storing to the stack slot.
59unsigned MipsInstrInfo::
60isStoreToStackSlot(const MachineInstr *MI, int &FrameIndex) const
61{
62  if ((MI->getOpcode() == Mips::SW) || (MI->getOpcode() == Mips::SWC1) ||
63      (MI->getOpcode() == Mips::SDC1)) {
64    if ((MI->getOperand(2).isFI()) && // is a stack slot
65        (MI->getOperand(1).isImm()) &&  // the imm is zero
66        (isZeroImm(MI->getOperand(1)))) {
67      FrameIndex = MI->getOperand(2).getIndex();
68      return MI->getOperand(0).getReg();
69    }
70  }
71  return 0;
72}
73
74/// insertNoop - If data hazard condition is found insert the target nop
75/// instruction.
76void MipsInstrInfo::
77insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
78{
79  DebugLoc DL;
80  BuildMI(MBB, MI, DL, get(Mips::NOP));
81}
82
83void MipsInstrInfo::
84copyPhysReg(MachineBasicBlock &MBB,
85            MachineBasicBlock::iterator I, DebugLoc DL,
86            unsigned DestReg, unsigned SrcReg,
87            bool KillSrc) const {
88  bool DestCPU = Mips::CPURegsRegClass.contains(DestReg);
89  bool SrcCPU  = Mips::CPURegsRegClass.contains(SrcReg);
90
91  // CPU-CPU is the most common.
92  if (DestCPU && SrcCPU) {
93    BuildMI(MBB, I, DL, get(Mips::ADDu), DestReg).addReg(Mips::ZERO)
94      .addReg(SrcReg, getKillRegState(KillSrc));
95    return;
96  }
97
98  // Copy to CPU from other registers.
99  if (DestCPU) {
100    if (Mips::CCRRegClass.contains(SrcReg))
101      BuildMI(MBB, I, DL, get(Mips::CFC1), DestReg)
102        .addReg(SrcReg, getKillRegState(KillSrc));
103    else if (Mips::FGR32RegClass.contains(SrcReg))
104      BuildMI(MBB, I, DL, get(Mips::MFC1), DestReg)
105        .addReg(SrcReg, getKillRegState(KillSrc));
106    else if (SrcReg == Mips::HI)
107      BuildMI(MBB, I, DL, get(Mips::MFHI), DestReg);
108    else if (SrcReg == Mips::LO)
109      BuildMI(MBB, I, DL, get(Mips::MFLO), DestReg);
110    else
111      llvm_unreachable("Copy to CPU from invalid register");
112    return;
113  }
114
115  // Copy to other registers from CPU.
116  if (SrcCPU) {
117    if (Mips::CCRRegClass.contains(DestReg))
118      BuildMI(MBB, I, DL, get(Mips::CTC1), DestReg)
119        .addReg(SrcReg, getKillRegState(KillSrc));
120    else if (Mips::FGR32RegClass.contains(DestReg))
121      BuildMI(MBB, I, DL, get(Mips::MTC1), DestReg)
122        .addReg(SrcReg, getKillRegState(KillSrc));
123    else if (DestReg == Mips::HI)
124      BuildMI(MBB, I, DL, get(Mips::MTHI))
125        .addReg(SrcReg, getKillRegState(KillSrc));
126    else if (DestReg == Mips::LO)
127      BuildMI(MBB, I, DL, get(Mips::MTLO))
128        .addReg(SrcReg, getKillRegState(KillSrc));
129    else
130      llvm_unreachable("Copy from CPU to invalid register");
131    return;
132  }
133
134  if (Mips::FGR32RegClass.contains(DestReg, SrcReg)) {
135    BuildMI(MBB, I, DL, get(Mips::FMOV_S32), DestReg)
136      .addReg(SrcReg, getKillRegState(KillSrc));
137    return;
138  }
139
140  if (Mips::AFGR64RegClass.contains(DestReg, SrcReg)) {
141    BuildMI(MBB, I, DL, get(Mips::FMOV_D32), DestReg)
142      .addReg(SrcReg, getKillRegState(KillSrc));
143    return;
144  }
145
146  if (Mips::CCRRegClass.contains(DestReg, SrcReg)) {
147    BuildMI(MBB, I, DL, get(Mips::MOVCCRToCCR), DestReg)
148      .addReg(SrcReg, getKillRegState(KillSrc));
149    return;
150  }
151  llvm_unreachable("Cannot copy registers");
152}
153
154void MipsInstrInfo::
155storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
156                    unsigned SrcReg, bool isKill, int FI,
157                    const TargetRegisterClass *RC,
158                    const TargetRegisterInfo *TRI) const {
159  DebugLoc DL;
160  if (I != MBB.end()) DL = I->getDebugLoc();
161
162  if (RC == Mips::CPURegsRegisterClass)
163    BuildMI(MBB, I, DL, get(Mips::SW)).addReg(SrcReg, getKillRegState(isKill))
164      .addImm(0).addFrameIndex(FI);
165  else if (RC == Mips::FGR32RegisterClass)
166    BuildMI(MBB, I, DL, get(Mips::SWC1))
167      .addReg(SrcReg, getKillRegState(isKill)).addImm(0).addFrameIndex(FI);
168  else if (RC == Mips::AFGR64RegisterClass) {
169    if (!TM.getSubtarget<MipsSubtarget>().isMips1()) {
170      BuildMI(MBB, I, DL, get(Mips::SDC1))
171        .addReg(SrcReg, getKillRegState(isKill))
172        .addImm(0).addFrameIndex(FI);
173    } else {
174      const TargetRegisterInfo *TRI =
175        MBB.getParent()->getTarget().getRegisterInfo();
176      const unsigned *SubSet = TRI->getSubRegisters(SrcReg);
177      BuildMI(MBB, I, DL, get(Mips::SWC1))
178        .addReg(SubSet[0], getKillRegState(isKill))
179        .addImm(0).addFrameIndex(FI);
180      BuildMI(MBB, I, DL, get(Mips::SWC1))
181        .addReg(SubSet[1], getKillRegState(isKill))
182        .addImm(4).addFrameIndex(FI);
183    }
184  } else
185    llvm_unreachable("Register class not handled!");
186}
187
188void MipsInstrInfo::
189loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
190                     unsigned DestReg, int FI,
191                     const TargetRegisterClass *RC,
192                     const TargetRegisterInfo *TRI) const
193{
194  DebugLoc DL;
195  if (I != MBB.end()) DL = I->getDebugLoc();
196
197  if (RC == Mips::CPURegsRegisterClass)
198    BuildMI(MBB, I, DL, get(Mips::LW), DestReg).addImm(0).addFrameIndex(FI);
199  else if (RC == Mips::FGR32RegisterClass)
200    BuildMI(MBB, I, DL, get(Mips::LWC1), DestReg).addImm(0).addFrameIndex(FI);
201  else if (RC == Mips::AFGR64RegisterClass) {
202    if (!TM.getSubtarget<MipsSubtarget>().isMips1()) {
203      BuildMI(MBB, I, DL, get(Mips::LDC1), DestReg)
204        .addImm(0).addFrameIndex(FI);
205    } else {
206      const TargetRegisterInfo *TRI =
207        MBB.getParent()->getTarget().getRegisterInfo();
208      const unsigned *SubSet = TRI->getSubRegisters(DestReg);
209      BuildMI(MBB, I, DL, get(Mips::LWC1), SubSet[0])
210        .addImm(0).addFrameIndex(FI);
211      BuildMI(MBB, I, DL, get(Mips::LWC1), SubSet[1])
212        .addImm(4).addFrameIndex(FI);
213    }
214  } else
215    llvm_unreachable("Register class not handled!");
216}
217
218//===---------------------------------------------------------------------===//
219// Branch Analysis
220//===---------------------------------------------------------------------===//
221
222static unsigned GetAnalyzableBrOpc(unsigned Opc) {
223  return (Opc == Mips::BEQ  || Opc == Mips::BNE  || Opc == Mips::BGTZ ||
224          Opc == Mips::BGEZ || Opc == Mips::BLTZ || Opc == Mips::BLEZ ||
225          Opc == Mips::BC1T || Opc == Mips::BC1F || Opc == Mips::J) ? Opc : 0;
226}
227
228/// GetOppositeBranchOpc - Return the inverse of the specified
229/// opcode, e.g. turning BEQ to BNE.
230unsigned Mips::GetOppositeBranchOpc(unsigned Opc)
231{
232  switch (Opc) {
233  default: llvm_unreachable("Illegal opcode!");
234  case Mips::BEQ  : return Mips::BNE;
235  case Mips::BNE  : return Mips::BEQ;
236  case Mips::BGTZ : return Mips::BLEZ;
237  case Mips::BGEZ : return Mips::BLTZ;
238  case Mips::BLTZ : return Mips::BGEZ;
239  case Mips::BLEZ : return Mips::BGTZ;
240  case Mips::BC1T : return Mips::BC1F;
241  case Mips::BC1F : return Mips::BC1T;
242  }
243}
244
245static void AnalyzeCondBr(const MachineInstr* Inst, unsigned Opc,
246                          MachineBasicBlock *&BB,
247                          SmallVectorImpl<MachineOperand>& Cond) {
248  assert(GetAnalyzableBrOpc(Opc) && "Not an analyzable branch");
249  int NumOp = Inst->getNumExplicitOperands();
250
251  // for both int and fp branches, the last explicit operand is the
252  // MBB.
253  BB = Inst->getOperand(NumOp-1).getMBB();
254  Cond.push_back(MachineOperand::CreateImm(Opc));
255
256  for (int i=0; i<NumOp-1; i++)
257    Cond.push_back(Inst->getOperand(i));
258}
259
260bool MipsInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
261                                  MachineBasicBlock *&TBB,
262                                  MachineBasicBlock *&FBB,
263                                  SmallVectorImpl<MachineOperand> &Cond,
264                                  bool AllowModify) const
265{
266  MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
267
268  // Skip all the debug instructions.
269  while (I != REnd && I->isDebugValue())
270    ++I;
271
272  if (I == REnd || !isUnpredicatedTerminator(&*I)) {
273    // If this block ends with no branches (it just falls through to its succ)
274    // just return false, leaving TBB/FBB null.
275    TBB = FBB = NULL;
276    return false;
277  }
278
279  MachineInstr *LastInst = &*I;
280  unsigned LastOpc = LastInst->getOpcode();
281
282  // Not an analyzable branch (must be an indirect jump).
283  if (!GetAnalyzableBrOpc(LastOpc))
284    return true;
285
286  // Get the second to last instruction in the block.
287  unsigned SecondLastOpc = 0;
288  MachineInstr *SecondLastInst = NULL;
289
290  if (++I != REnd) {
291    SecondLastInst = &*I;
292    SecondLastOpc = GetAnalyzableBrOpc(SecondLastInst->getOpcode());
293
294    // Not an analyzable branch (must be an indirect jump).
295    if (isUnpredicatedTerminator(SecondLastInst) && !SecondLastOpc)
296      return true;
297  }
298
299  // If there is only one terminator instruction, process it.
300  if (!SecondLastOpc) {
301    // Unconditional branch
302    if (LastOpc == Mips::J) {
303      TBB = LastInst->getOperand(0).getMBB();
304      return false;
305    }
306
307    // Conditional branch
308    AnalyzeCondBr(LastInst, LastOpc, TBB, Cond);
309    return false;
310  }
311
312  // If we reached here, there are two branches.
313  // If there are three terminators, we don't know what sort of block this is.
314  if (++I != REnd && isUnpredicatedTerminator(&*I))
315    return true;
316
317  // If second to last instruction is an unconditional branch,
318  // analyze it and remove the last instruction.
319  if (SecondLastOpc == Mips::J) {
320    // Return if the last instruction cannot be removed.
321    if (!AllowModify)
322      return true;
323
324    TBB = SecondLastInst->getOperand(0).getMBB();
325    LastInst->eraseFromParent();
326    return false;
327  }
328
329  // Conditional branch followed by an unconditional branch.
330  // The last one must be unconditional.
331  if (LastOpc != Mips::J)
332    return true;
333
334  AnalyzeCondBr(SecondLastInst, SecondLastOpc, TBB, Cond);
335  FBB = LastInst->getOperand(0).getMBB();
336
337  return false;
338}
339
340void MipsInstrInfo::BuildCondBr(MachineBasicBlock &MBB,
341                                MachineBasicBlock *TBB, DebugLoc DL,
342                                const SmallVectorImpl<MachineOperand>& Cond)
343  const {
344  unsigned Opc = Cond[0].getImm();
345  const TargetInstrDesc &TID = get(Opc);
346  MachineInstrBuilder MIB = BuildMI(&MBB, DL, TID);
347
348  for (unsigned i = 1; i < Cond.size(); ++i)
349    MIB.addReg(Cond[i].getReg());
350
351  MIB.addMBB(TBB);
352}
353
354unsigned MipsInstrInfo::
355InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
356             MachineBasicBlock *FBB,
357             const SmallVectorImpl<MachineOperand> &Cond,
358             DebugLoc DL) const {
359  // Shouldn't be a fall through.
360  assert(TBB && "InsertBranch must not be told to insert a fallthrough");
361
362  // # of condition operands:
363  //  Unconditional branches: 0
364  //  Floating point branches: 1 (opc)
365  //  Int BranchZero: 2 (opc, reg)
366  //  Int Branch: 3 (opc, reg0, reg1)
367  assert((Cond.size() <= 3) &&
368         "# of Mips branch conditions must be <= 3!");
369
370  // Two-way Conditional branch.
371  if (FBB) {
372    BuildCondBr(MBB, TBB, DL, Cond);
373    BuildMI(&MBB, DL, get(Mips::J)).addMBB(FBB);
374    return 2;
375  }
376
377  // One way branch.
378  // Unconditional branch.
379  if (Cond.empty())
380    BuildMI(&MBB, DL, get(Mips::J)).addMBB(TBB);
381  else // Conditional branch.
382    BuildCondBr(MBB, TBB, DL, Cond);
383  return 1;
384}
385
386unsigned MipsInstrInfo::
387RemoveBranch(MachineBasicBlock &MBB) const
388{
389  MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
390  MachineBasicBlock::reverse_iterator FirstBr;
391  unsigned removed;
392
393  // Skip all the debug instructions.
394  while (I != REnd && I->isDebugValue())
395    ++I;
396
397  FirstBr = I;
398
399  // Up to 2 branches are removed.
400  // Note that indirect branches are not removed.
401  for(removed = 0; I != REnd && removed < 2; ++I, ++removed)
402    if (!GetAnalyzableBrOpc(I->getOpcode()))
403      break;
404
405  MBB.erase(I.base(), FirstBr.base());
406
407  return removed;
408}
409
410/// ReverseBranchCondition - Return the inverse opcode of the
411/// specified Branch instruction.
412bool MipsInstrInfo::
413ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const
414{
415  assert( (Cond.size() && Cond.size() <= 3) &&
416          "Invalid Mips branch condition!");
417  Cond[0].setImm(Mips::GetOppositeBranchOpc(Cond[0].getImm()));
418  return false;
419}
420
421/// getGlobalBaseReg - Return a virtual register initialized with the
422/// the global base register value. Output instructions required to
423/// initialize the register in the function entry block, if necessary.
424///
425unsigned MipsInstrInfo::getGlobalBaseReg(MachineFunction *MF) const {
426  MipsFunctionInfo *MipsFI = MF->getInfo<MipsFunctionInfo>();
427  unsigned GlobalBaseReg = MipsFI->getGlobalBaseReg();
428  if (GlobalBaseReg != 0)
429    return GlobalBaseReg;
430
431  // Insert the set of GlobalBaseReg into the first MBB of the function
432  MachineBasicBlock &FirstMBB = MF->front();
433  MachineBasicBlock::iterator MBBI = FirstMBB.begin();
434  MachineRegisterInfo &RegInfo = MF->getRegInfo();
435  const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
436
437  GlobalBaseReg = RegInfo.createVirtualRegister(Mips::CPURegsRegisterClass);
438  BuildMI(FirstMBB, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY),
439          GlobalBaseReg).addReg(Mips::GP);
440  RegInfo.addLiveIn(Mips::GP);
441
442  MipsFI->setGlobalBaseReg(GlobalBaseReg);
443  return GlobalBaseReg;
444}
445