1
2//===-- Mips16InstrInfo.cpp - Mips16 Instruction Information --------------===//
3//
4//                     The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10//
11// This file contains the Mips16 implementation of the TargetInstrInfo class.
12//
13//===----------------------------------------------------------------------===//
14#include "Mips16InstrInfo.h"
15#include "InstPrinter/MipsInstPrinter.h"
16#include "MipsMachineFunction.h"
17#include "MipsTargetMachine.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/CodeGen/MachineInstrBuilder.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/RegisterScavenging.h"
23#include "llvm/MC/MCAsmInfo.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/TargetRegistry.h"
28#include <cctype>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "mips16-instrinfo"
33
34Mips16InstrInfo::Mips16InstrInfo(MipsTargetMachine &tm)
35  : MipsInstrInfo(tm, Mips::Bimm16),
36    RI(*tm.getSubtargetImpl()) {}
37
38const MipsRegisterInfo &Mips16InstrInfo::getRegisterInfo() const {
39  return RI;
40}
41
42/// isLoadFromStackSlot - If the specified machine instruction is a direct
43/// load from a stack slot, return the virtual or physical register number of
44/// the destination along with the FrameIndex of the loaded stack slot.  If
45/// not, return 0.  This predicate must return 0 if the instruction has
46/// any side effects other than loading from the stack slot.
47unsigned Mips16InstrInfo::
48isLoadFromStackSlot(const MachineInstr *MI, int &FrameIndex) const
49{
50  return 0;
51}
52
53/// isStoreToStackSlot - If the specified machine instruction is a direct
54/// store to a stack slot, return the virtual or physical register number of
55/// the source reg along with the FrameIndex of the loaded stack slot.  If
56/// not, return 0.  This predicate must return 0 if the instruction has
57/// any side effects other than storing to the stack slot.
58unsigned Mips16InstrInfo::
59isStoreToStackSlot(const MachineInstr *MI, int &FrameIndex) const
60{
61  return 0;
62}
63
64void Mips16InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
65                                  MachineBasicBlock::iterator I, DebugLoc DL,
66                                  unsigned DestReg, unsigned SrcReg,
67                                  bool KillSrc) const {
68  unsigned Opc = 0;
69
70  if (Mips::CPU16RegsRegClass.contains(DestReg) &&
71      Mips::GPR32RegClass.contains(SrcReg))
72    Opc = Mips::MoveR3216;
73  else if (Mips::GPR32RegClass.contains(DestReg) &&
74           Mips::CPU16RegsRegClass.contains(SrcReg))
75    Opc = Mips::Move32R16;
76  else if ((SrcReg == Mips::HI0) &&
77           (Mips::CPU16RegsRegClass.contains(DestReg)))
78    Opc = Mips::Mfhi16, SrcReg = 0;
79
80  else if ((SrcReg == Mips::LO0) &&
81           (Mips::CPU16RegsRegClass.contains(DestReg)))
82    Opc = Mips::Mflo16, SrcReg = 0;
83
84
85  assert(Opc && "Cannot copy registers");
86
87  MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc));
88
89  if (DestReg)
90    MIB.addReg(DestReg, RegState::Define);
91
92  if (SrcReg)
93    MIB.addReg(SrcReg, getKillRegState(KillSrc));
94}
95
96void Mips16InstrInfo::
97storeRegToStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
98                unsigned SrcReg, bool isKill, int FI,
99                const TargetRegisterClass *RC, const TargetRegisterInfo *TRI,
100                int64_t Offset) const {
101  DebugLoc DL;
102  if (I != MBB.end()) DL = I->getDebugLoc();
103  MachineMemOperand *MMO = GetMemOperand(MBB, FI, MachineMemOperand::MOStore);
104  unsigned Opc = 0;
105  if (Mips::CPU16RegsRegClass.hasSubClassEq(RC))
106    Opc = Mips::SwRxSpImmX16;
107  assert(Opc && "Register class not handled!");
108  BuildMI(MBB, I, DL, get(Opc)).addReg(SrcReg, getKillRegState(isKill)).
109      addFrameIndex(FI).addImm(Offset)
110      .addMemOperand(MMO);
111}
112
113void Mips16InstrInfo::
114loadRegFromStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
115                 unsigned DestReg, int FI, const TargetRegisterClass *RC,
116                 const TargetRegisterInfo *TRI, int64_t Offset) const {
117  DebugLoc DL;
118  if (I != MBB.end()) DL = I->getDebugLoc();
119  MachineMemOperand *MMO = GetMemOperand(MBB, FI, MachineMemOperand::MOLoad);
120  unsigned Opc = 0;
121
122  if (Mips::CPU16RegsRegClass.hasSubClassEq(RC))
123    Opc = Mips::LwRxSpImmX16;
124  assert(Opc && "Register class not handled!");
125  BuildMI(MBB, I, DL, get(Opc), DestReg).addFrameIndex(FI).addImm(Offset)
126    .addMemOperand(MMO);
127}
128
129bool Mips16InstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
130  MachineBasicBlock &MBB = *MI->getParent();
131  switch(MI->getDesc().getOpcode()) {
132  default:
133    return false;
134  case Mips::RetRA16:
135    ExpandRetRA16(MBB, MI, Mips::JrcRa16);
136    break;
137  }
138
139  MBB.erase(MI);
140  return true;
141}
142
143/// GetOppositeBranchOpc - Return the inverse of the specified
144/// opcode, e.g. turning BEQ to BNE.
145unsigned Mips16InstrInfo::getOppositeBranchOpc(unsigned Opc) const {
146  switch (Opc) {
147  default:  llvm_unreachable("Illegal opcode!");
148  case Mips::BeqzRxImmX16: return Mips::BnezRxImmX16;
149  case Mips::BnezRxImmX16: return Mips::BeqzRxImmX16;
150  case Mips::BeqzRxImm16: return Mips::BnezRxImm16;
151  case Mips::BnezRxImm16: return Mips::BeqzRxImm16;
152  case Mips::BteqzT8CmpX16: return Mips::BtnezT8CmpX16;
153  case Mips::BteqzT8SltX16: return Mips::BtnezT8SltX16;
154  case Mips::BteqzT8SltiX16: return Mips::BtnezT8SltiX16;
155  case Mips::Btnez16: return Mips::Bteqz16;
156  case Mips::BtnezX16: return Mips::BteqzX16;
157  case Mips::BtnezT8CmpiX16: return Mips::BteqzT8CmpiX16;
158  case Mips::BtnezT8SltuX16: return Mips::BteqzT8SltuX16;
159  case Mips::BtnezT8SltiuX16: return Mips::BteqzT8SltiuX16;
160  case Mips::Bteqz16: return Mips::Btnez16;
161  case Mips::BteqzX16: return Mips::BtnezX16;
162  case Mips::BteqzT8CmpiX16: return Mips::BtnezT8CmpiX16;
163  case Mips::BteqzT8SltuX16: return Mips::BtnezT8SltuX16;
164  case Mips::BteqzT8SltiuX16: return Mips::BtnezT8SltiuX16;
165  case Mips::BtnezT8CmpX16: return Mips::BteqzT8CmpX16;
166  case Mips::BtnezT8SltX16: return Mips::BteqzT8SltX16;
167  case Mips::BtnezT8SltiX16: return Mips::BteqzT8SltiX16;
168  }
169  assert(false && "Implement this function.");
170  return 0;
171}
172
173static void addSaveRestoreRegs(MachineInstrBuilder &MIB,
174                          const std::vector<CalleeSavedInfo> &CSI, unsigned Flags=0) {
175  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
176    // Add the callee-saved register as live-in. Do not add if the register is
177    // RA and return address is taken, because it has already been added in
178    // method MipsTargetLowering::LowerRETURNADDR.
179    // It's killed at the spill, unless the register is RA and return address
180    // is taken.
181    unsigned Reg = CSI[e-i-1].getReg();
182    switch (Reg) {
183    case Mips::RA:
184    case Mips::S0:
185    case Mips::S1:
186      MIB.addReg(Reg, Flags);
187      break;
188    case Mips::S2:
189      break;
190    default:
191      llvm_unreachable("unexpected mips16 callee saved register");
192
193    }
194  }
195}
196// Adjust SP by FrameSize bytes. Save RA, S0, S1
197void Mips16InstrInfo::makeFrame(unsigned SP, int64_t FrameSize,
198                    MachineBasicBlock &MBB,
199                    MachineBasicBlock::iterator I) const {
200  DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
201  MachineFunction &MF = *MBB.getParent();
202  MachineFrameInfo *MFI    = MF.getFrameInfo();
203  const BitVector Reserved = RI.getReservedRegs(MF);
204  bool SaveS2 = Reserved[Mips::S2];
205  MachineInstrBuilder MIB;
206  unsigned Opc = ((FrameSize <= 128) && !SaveS2)? Mips::Save16:Mips::SaveX16;
207  MIB = BuildMI(MBB, I, DL, get(Opc));
208  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
209  addSaveRestoreRegs(MIB, CSI);
210  if (SaveS2)
211    MIB.addReg(Mips::S2);
212  if (isUInt<11>(FrameSize))
213    MIB.addImm(FrameSize);
214  else {
215    int Base = 2040; // should create template function like isUInt that
216                     // returns largest possible n bit unsigned integer
217    int64_t Remainder = FrameSize - Base;
218    MIB.addImm(Base);
219    if (isInt<16>(-Remainder))
220      BuildAddiuSpImm(MBB, I, -Remainder);
221    else
222      adjustStackPtrBig(SP, -Remainder, MBB, I, Mips::V0, Mips::V1);
223  }
224}
225
226// Adjust SP by FrameSize bytes. Restore RA, S0, S1
227void Mips16InstrInfo::restoreFrame(unsigned SP, int64_t FrameSize,
228                                   MachineBasicBlock &MBB,
229                                   MachineBasicBlock::iterator I) const {
230  DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
231  MachineFunction *MF = MBB.getParent();
232  MachineFrameInfo *MFI    = MF->getFrameInfo();
233  const BitVector Reserved = RI.getReservedRegs(*MF);
234  bool SaveS2 = Reserved[Mips::S2];
235  MachineInstrBuilder MIB;
236  unsigned Opc = ((FrameSize <= 128) && !SaveS2)?
237    Mips::Restore16:Mips::RestoreX16;
238
239  if (!isUInt<11>(FrameSize)) {
240    unsigned Base = 2040;
241    int64_t Remainder = FrameSize - Base;
242    FrameSize = Base; // should create template function like isUInt that
243                     // returns largest possible n bit unsigned integer
244
245    if (isInt<16>(Remainder))
246      BuildAddiuSpImm(MBB, I, Remainder);
247    else
248      adjustStackPtrBig(SP, Remainder, MBB, I, Mips::A0, Mips::A1);
249  }
250  MIB = BuildMI(MBB, I, DL, get(Opc));
251  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
252  addSaveRestoreRegs(MIB, CSI, RegState::Define);
253  if (SaveS2)
254    MIB.addReg(Mips::S2, RegState::Define);
255  MIB.addImm(FrameSize);
256}
257
258// Adjust SP by Amount bytes where bytes can be up to 32bit number.
259// This can only be called at times that we know that there is at least one free
260// register.
261// This is clearly safe at prologue and epilogue.
262//
263void Mips16InstrInfo::adjustStackPtrBig(unsigned SP, int64_t Amount,
264                                        MachineBasicBlock &MBB,
265                                        MachineBasicBlock::iterator I,
266                                        unsigned Reg1, unsigned Reg2) const {
267  DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
268//  MachineRegisterInfo &RegInfo = MBB.getParent()->getRegInfo();
269//  unsigned Reg1 = RegInfo.createVirtualRegister(&Mips::CPU16RegsRegClass);
270//  unsigned Reg2 = RegInfo.createVirtualRegister(&Mips::CPU16RegsRegClass);
271  //
272  // li reg1, constant
273  // move reg2, sp
274  // add reg1, reg1, reg2
275  // move sp, reg1
276  //
277  //
278  MachineInstrBuilder MIB1 = BuildMI(MBB, I, DL, get(Mips::LwConstant32), Reg1);
279  MIB1.addImm(Amount).addImm(-1);
280  MachineInstrBuilder MIB2 = BuildMI(MBB, I, DL, get(Mips::MoveR3216), Reg2);
281  MIB2.addReg(Mips::SP, RegState::Kill);
282  MachineInstrBuilder MIB3 = BuildMI(MBB, I, DL, get(Mips::AdduRxRyRz16), Reg1);
283  MIB3.addReg(Reg1);
284  MIB3.addReg(Reg2, RegState::Kill);
285  MachineInstrBuilder MIB4 = BuildMI(MBB, I, DL, get(Mips::Move32R16),
286                                                     Mips::SP);
287  MIB4.addReg(Reg1, RegState::Kill);
288}
289
290void Mips16InstrInfo::adjustStackPtrBigUnrestricted(unsigned SP, int64_t Amount,
291                    MachineBasicBlock &MBB,
292                    MachineBasicBlock::iterator I) const {
293   assert(false && "adjust stack pointer amount exceeded");
294}
295
296/// Adjust SP by Amount bytes.
297void Mips16InstrInfo::adjustStackPtr(unsigned SP, int64_t Amount,
298                                     MachineBasicBlock &MBB,
299                                     MachineBasicBlock::iterator I) const {
300  if (isInt<16>(Amount))  // need to change to addiu sp, ....and isInt<16>
301    BuildAddiuSpImm(MBB, I, Amount);
302  else
303    adjustStackPtrBigUnrestricted(SP, Amount, MBB, I);
304}
305
306/// This function generates the sequence of instructions needed to get the
307/// result of adding register REG and immediate IMM.
308unsigned
309Mips16InstrInfo::loadImmediate(unsigned FrameReg,
310                               int64_t Imm, MachineBasicBlock &MBB,
311                               MachineBasicBlock::iterator II, DebugLoc DL,
312                               unsigned &NewImm) const {
313  //
314  // given original instruction is:
315  // Instr rx, T[offset] where offset is too big.
316  //
317  // lo = offset & 0xFFFF
318  // hi = ((offset >> 16) + (lo >> 15)) & 0xFFFF;
319  //
320  // let T = temporary register
321  // li T, hi
322  // shl T, 16
323  // add T, Rx, T
324  //
325  RegScavenger rs;
326  int32_t lo = Imm & 0xFFFF;
327  NewImm = lo;
328  int Reg =0;
329  int SpReg = 0;
330
331  rs.enterBasicBlock(&MBB);
332  rs.forward(II);
333  //
334  // We need to know which registers can be used, in the case where there
335  // are not enough free registers. We exclude all registers that
336  // are used in the instruction that we are helping.
337  //  // Consider all allocatable registers in the register class initially
338  BitVector Candidates =
339      RI.getAllocatableSet
340      (*II->getParent()->getParent(), &Mips::CPU16RegsRegClass);
341  // Exclude all the registers being used by the instruction.
342  for (unsigned i = 0, e = II->getNumOperands(); i != e; ++i) {
343    MachineOperand &MO = II->getOperand(i);
344    if (MO.isReg() && MO.getReg() != 0 && !MO.isDef() &&
345        !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
346      Candidates.reset(MO.getReg());
347  }
348  //
349  // If the same register was used and defined in an instruction, then
350  // it will not be in the list of candidates.
351  //
352  // we need to analyze the instruction that we are helping.
353  // we need to know if it defines register x but register x is not
354  // present as an operand of the instruction. this tells
355  // whether the register is live before the instruction. if it's not
356  // then we don't need to save it in case there are no free registers.
357  //
358  int DefReg = 0;
359  for (unsigned i = 0, e = II->getNumOperands(); i != e; ++i) {
360    MachineOperand &MO = II->getOperand(i);
361    if (MO.isReg() && MO.isDef()) {
362      DefReg = MO.getReg();
363      break;
364    }
365  }
366  //
367  BitVector Available = rs.getRegsAvailable(&Mips::CPU16RegsRegClass);
368
369  Available &= Candidates;
370  //
371  // we use T0 for the first register, if we need to save something away.
372  // we use T1 for the second register, if we need to save something away.
373  //
374  unsigned FirstRegSaved =0, SecondRegSaved=0;
375  unsigned FirstRegSavedTo = 0, SecondRegSavedTo = 0;
376
377
378  Reg = Available.find_first();
379
380  if (Reg == -1) {
381    Reg = Candidates.find_first();
382    Candidates.reset(Reg);
383    if (DefReg != Reg) {
384      FirstRegSaved = Reg;
385      FirstRegSavedTo = Mips::T0;
386      copyPhysReg(MBB, II, DL, FirstRegSavedTo, FirstRegSaved, true);
387    }
388  }
389  else
390    Available.reset(Reg);
391  BuildMI(MBB, II, DL, get(Mips::LwConstant32), Reg).addImm(Imm).addImm(-1);
392  NewImm = 0;
393  if (FrameReg == Mips::SP) {
394    SpReg = Available.find_first();
395    if (SpReg == -1) {
396      SpReg = Candidates.find_first();
397      // Candidates.reset(SpReg); // not really needed
398      if (DefReg!= SpReg) {
399        SecondRegSaved = SpReg;
400        SecondRegSavedTo = Mips::T1;
401      }
402      if (SecondRegSaved)
403        copyPhysReg(MBB, II, DL, SecondRegSavedTo, SecondRegSaved, true);
404    }
405   else
406     Available.reset(SpReg);
407    copyPhysReg(MBB, II, DL, SpReg, Mips::SP, false);
408    BuildMI(MBB, II, DL, get(Mips::  AdduRxRyRz16), Reg).addReg(SpReg, RegState::Kill)
409      .addReg(Reg);
410  }
411  else
412    BuildMI(MBB, II, DL, get(Mips::  AdduRxRyRz16), Reg).addReg(FrameReg)
413      .addReg(Reg, RegState::Kill);
414  if (FirstRegSaved || SecondRegSaved) {
415    II = std::next(II);
416    if (FirstRegSaved)
417      copyPhysReg(MBB, II, DL, FirstRegSaved, FirstRegSavedTo, true);
418    if (SecondRegSaved)
419      copyPhysReg(MBB, II, DL, SecondRegSaved, SecondRegSavedTo, true);
420  }
421  return Reg;
422}
423
424unsigned Mips16InstrInfo::getAnalyzableBrOpc(unsigned Opc) const {
425  return (Opc == Mips::BeqzRxImmX16   || Opc == Mips::BimmX16  ||
426          Opc == Mips::Bimm16  ||
427          Opc == Mips::Bteqz16        || Opc == Mips::Btnez16 ||
428          Opc == Mips::BeqzRxImm16    || Opc == Mips::BnezRxImm16   ||
429          Opc == Mips::BnezRxImmX16   || Opc == Mips::BteqzX16 ||
430          Opc == Mips::BteqzT8CmpX16  || Opc == Mips::BteqzT8CmpiX16 ||
431          Opc == Mips::BteqzT8SltX16  || Opc == Mips::BteqzT8SltuX16  ||
432          Opc == Mips::BteqzT8SltiX16 || Opc == Mips::BteqzT8SltiuX16 ||
433          Opc == Mips::BtnezX16       || Opc == Mips::BtnezT8CmpX16 ||
434          Opc == Mips::BtnezT8CmpiX16 || Opc == Mips::BtnezT8SltX16 ||
435          Opc == Mips::BtnezT8SltuX16 || Opc == Mips::BtnezT8SltiX16 ||
436          Opc == Mips::BtnezT8SltiuX16 ) ? Opc : 0;
437}
438
439void Mips16InstrInfo::ExpandRetRA16(MachineBasicBlock &MBB,
440                                  MachineBasicBlock::iterator I,
441                                  unsigned Opc) const {
442  BuildMI(MBB, I, I->getDebugLoc(), get(Opc));
443}
444
445
446const MCInstrDesc &Mips16InstrInfo::AddiuSpImm(int64_t Imm) const {
447  if (validSpImm8(Imm))
448    return get(Mips::AddiuSpImm16);
449  else
450    return get(Mips::AddiuSpImmX16);
451}
452
453void Mips16InstrInfo::BuildAddiuSpImm
454  (MachineBasicBlock &MBB, MachineBasicBlock::iterator I, int64_t Imm) const {
455  DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
456  BuildMI(MBB, I, DL, AddiuSpImm(Imm)).addImm(Imm);
457}
458
459const MipsInstrInfo *llvm::createMips16InstrInfo(MipsTargetMachine &TM) {
460  return new Mips16InstrInfo(TM);
461}
462
463bool Mips16InstrInfo::validImmediate(unsigned Opcode, unsigned Reg,
464                                     int64_t Amount) {
465  switch (Opcode) {
466  case Mips::LbRxRyOffMemX16:
467  case Mips::LbuRxRyOffMemX16:
468  case Mips::LhRxRyOffMemX16:
469  case Mips::LhuRxRyOffMemX16:
470  case Mips::SbRxRyOffMemX16:
471  case Mips::ShRxRyOffMemX16:
472  case Mips::LwRxRyOffMemX16:
473  case Mips::SwRxRyOffMemX16:
474  case Mips::SwRxSpImmX16:
475  case Mips::LwRxSpImmX16:
476    return isInt<16>(Amount);
477  case Mips::AddiuRxRyOffMemX16:
478    if ((Reg == Mips::PC) || (Reg == Mips::SP))
479      return isInt<16>(Amount);
480    return isInt<15>(Amount);
481  }
482  llvm_unreachable("unexpected Opcode in validImmediate");
483}
484
485/// Measure the specified inline asm to determine an approximation of its
486/// length.
487/// Comments (which run till the next SeparatorString or newline) do not
488/// count as an instruction.
489/// Any other non-whitespace text is considered an instruction, with
490/// multiple instructions separated by SeparatorString or newlines.
491/// Variable-length instructions are not handled here; this function
492/// may be overloaded in the target code to do that.
493/// We implement the special case of the .space directive taking only an
494/// integer argument, which is the size in bytes. This is used for creating
495/// inline code spacing for testing purposes using inline assembly.
496///
497unsigned Mips16InstrInfo::getInlineAsmLength(const char *Str,
498                                             const MCAsmInfo &MAI) const {
499
500
501  // Count the number of instructions in the asm.
502  bool atInsnStart = true;
503  unsigned Length = 0;
504  for (; *Str; ++Str) {
505    if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
506                                strlen(MAI.getSeparatorString())) == 0)
507      atInsnStart = true;
508    if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
509      if (strncmp(Str, ".space", 6)==0) {
510        char *EStr; int Sz;
511        Sz = strtol(Str+6, &EStr, 10);
512        while (isspace(*EStr)) ++EStr;
513        if (*EStr=='\0') {
514          DEBUG(dbgs() << "parsed .space " << Sz << '\n');
515          return Sz;
516        }
517      }
518      Length += MAI.getMaxInstLength();
519      atInsnStart = false;
520    }
521    if (atInsnStart && strncmp(Str, MAI.getCommentString(),
522                               strlen(MAI.getCommentString())) == 0)
523      atInsnStart = false;
524  }
525
526  return Length;
527}
528