XCoreInstrInfo.cpp revision c23197a26f34f559ea9797de51e187087c039c42
1//===- XCoreInstrInfo.cpp - XCore 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 XCore implementation of the TargetInstrInfo class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "XCoreMachineFunctionInfo.h"
15#include "XCoreInstrInfo.h"
16#include "XCore.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineLocation.h"
21#include "llvm/CodeGen/MachineModuleInfo.h"
22#include "XCoreGenInstrInfo.inc"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/ErrorHandling.h"
25
26namespace llvm {
27namespace XCore {
28
29  // XCore Condition Codes
30  enum CondCode {
31    COND_TRUE,
32    COND_FALSE,
33    COND_INVALID
34  };
35}
36}
37
38using namespace llvm;
39
40XCoreInstrInfo::XCoreInstrInfo(void)
41  : TargetInstrInfoImpl(XCoreInsts, array_lengthof(XCoreInsts)),
42    RI(*this) {
43}
44
45static bool isZeroImm(const MachineOperand &op) {
46  return op.isImm() && op.getImm() == 0;
47}
48
49/// Return true if the instruction is a register to register move and
50/// leave the source and dest operands in the passed parameters.
51///
52bool XCoreInstrInfo::isMoveInstr(const MachineInstr &MI,
53                                 unsigned &SrcReg, unsigned &DstReg,
54                                 unsigned &SrcSR, unsigned &DstSR) const {
55  SrcSR = DstSR = 0; // No sub-registers.
56
57  // We look for 4 kinds of patterns here:
58  // add dst, src, 0
59  // sub dst, src, 0
60  // or dst, src, src
61  // and dst, src, src
62  if ((MI.getOpcode() == XCore::ADD_2rus || MI.getOpcode() == XCore::SUB_2rus)
63      && isZeroImm(MI.getOperand(2))) {
64    DstReg = MI.getOperand(0).getReg();
65    SrcReg = MI.getOperand(1).getReg();
66    return true;
67  } else if ((MI.getOpcode() == XCore::OR_3r || MI.getOpcode() == XCore::AND_3r)
68      && MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
69    DstReg = MI.getOperand(0).getReg();
70    SrcReg = MI.getOperand(1).getReg();
71    return true;
72  }
73  return false;
74}
75
76/// isLoadFromStackSlot - If the specified machine instruction is a direct
77/// load from a stack slot, return the virtual or physical register number of
78/// the destination along with the FrameIndex of the loaded stack slot.  If
79/// not, return 0.  This predicate must return 0 if the instruction has
80/// any side effects other than loading from the stack slot.
81unsigned
82XCoreInstrInfo::isLoadFromStackSlot(const MachineInstr *MI, int &FrameIndex) const{
83  int Opcode = MI->getOpcode();
84  if (Opcode == XCore::LDWFI)
85  {
86    if ((MI->getOperand(1).isFI()) && // is a stack slot
87        (MI->getOperand(2).isImm()) &&  // the imm is zero
88        (isZeroImm(MI->getOperand(2))))
89    {
90      FrameIndex = MI->getOperand(1).getIndex();
91      return MI->getOperand(0).getReg();
92    }
93  }
94  return 0;
95}
96
97  /// isStoreToStackSlot - If the specified machine instruction is a direct
98  /// store to a stack slot, return the virtual or physical register number of
99  /// the source reg along with the FrameIndex of the loaded stack slot.  If
100  /// not, return 0.  This predicate must return 0 if the instruction has
101  /// any side effects other than storing to the stack slot.
102unsigned
103XCoreInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
104                                   int &FrameIndex) const {
105  int Opcode = MI->getOpcode();
106  if (Opcode == XCore::STWFI)
107  {
108    if ((MI->getOperand(1).isFI()) && // is a stack slot
109        (MI->getOperand(2).isImm()) &&  // the imm is zero
110        (isZeroImm(MI->getOperand(2))))
111    {
112      FrameIndex = MI->getOperand(1).getIndex();
113      return MI->getOperand(0).getReg();
114    }
115  }
116  return 0;
117}
118
119/// isInvariantLoad - Return true if the specified instruction (which is marked
120/// mayLoad) is loading from a location whose value is invariant across the
121/// function.  For example, loading a value from the constant pool or from
122/// from the argument area of a function if it does not change.  This should
123/// only return true of *all* loads the instruction does are invariant (if it
124/// does multiple loads).
125bool
126XCoreInstrInfo::isInvariantLoad(const MachineInstr *MI) const {
127  // Loads from constants pools and loads from invariant argument slots are
128  // invariant
129  int Opcode = MI->getOpcode();
130  if (Opcode == XCore::LDWCP_ru6 || Opcode == XCore::LDWCP_lru6) {
131    return MI->getOperand(1).isCPI();
132  }
133  int FrameIndex;
134  if (isLoadFromStackSlot(MI, FrameIndex)) {
135    const MachineFrameInfo &MFI =
136      *MI->getParent()->getParent()->getFrameInfo();
137    return MFI.isFixedObjectIndex(FrameIndex) &&
138           MFI.isImmutableObjectIndex(FrameIndex);
139  }
140  return false;
141}
142
143//===----------------------------------------------------------------------===//
144// Branch Analysis
145//===----------------------------------------------------------------------===//
146
147static inline bool IsBRU(unsigned BrOpc) {
148  return BrOpc == XCore::BRFU_u6
149      || BrOpc == XCore::BRFU_lu6
150      || BrOpc == XCore::BRBU_u6
151      || BrOpc == XCore::BRBU_lu6;
152}
153
154static inline bool IsBRT(unsigned BrOpc) {
155  return BrOpc == XCore::BRFT_ru6
156      || BrOpc == XCore::BRFT_lru6
157      || BrOpc == XCore::BRBT_ru6
158      || BrOpc == XCore::BRBT_lru6;
159}
160
161static inline bool IsBRF(unsigned BrOpc) {
162  return BrOpc == XCore::BRFF_ru6
163      || BrOpc == XCore::BRFF_lru6
164      || BrOpc == XCore::BRBF_ru6
165      || BrOpc == XCore::BRBF_lru6;
166}
167
168static inline bool IsCondBranch(unsigned BrOpc) {
169  return IsBRF(BrOpc) || IsBRT(BrOpc);
170}
171
172/// GetCondFromBranchOpc - Return the XCore CC that matches
173/// the correspondent Branch instruction opcode.
174static XCore::CondCode GetCondFromBranchOpc(unsigned BrOpc)
175{
176  if (IsBRT(BrOpc)) {
177    return XCore::COND_TRUE;
178  } else if (IsBRF(BrOpc)) {
179    return XCore::COND_FALSE;
180  } else {
181    return XCore::COND_INVALID;
182  }
183}
184
185/// GetCondBranchFromCond - Return the Branch instruction
186/// opcode that matches the cc.
187static inline unsigned GetCondBranchFromCond(XCore::CondCode CC)
188{
189  switch (CC) {
190  default: llvm_unreachable("Illegal condition code!");
191  case XCore::COND_TRUE   : return XCore::BRFT_lru6;
192  case XCore::COND_FALSE  : return XCore::BRFF_lru6;
193  }
194}
195
196/// GetOppositeBranchCondition - Return the inverse of the specified
197/// condition, e.g. turning COND_E to COND_NE.
198static inline XCore::CondCode GetOppositeBranchCondition(XCore::CondCode CC)
199{
200  switch (CC) {
201  default: llvm_unreachable("Illegal condition code!");
202  case XCore::COND_TRUE   : return XCore::COND_FALSE;
203  case XCore::COND_FALSE  : return XCore::COND_TRUE;
204  }
205}
206
207/// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
208/// true if it cannot be understood (e.g. it's a switch dispatch or isn't
209/// implemented for a target).  Upon success, this returns false and returns
210/// with the following information in various cases:
211///
212/// 1. If this block ends with no branches (it just falls through to its succ)
213///    just return false, leaving TBB/FBB null.
214/// 2. If this block ends with only an unconditional branch, it sets TBB to be
215///    the destination block.
216/// 3. If this block ends with an conditional branch and it falls through to
217///    an successor block, it sets TBB to be the branch destination block and a
218///    list of operands that evaluate the condition. These
219///    operands can be passed to other TargetInstrInfo methods to create new
220///    branches.
221/// 4. If this block ends with an conditional branch and an unconditional
222///    block, it returns the 'true' destination in TBB, the 'false' destination
223///    in FBB, and a list of operands that evaluate the condition. These
224///    operands can be passed to other TargetInstrInfo methods to create new
225///    branches.
226///
227/// Note that RemoveBranch and InsertBranch must be implemented to support
228/// cases where this method returns success.
229///
230bool
231XCoreInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
232                              MachineBasicBlock *&FBB,
233                              SmallVectorImpl<MachineOperand> &Cond,
234                              bool AllowModify) const {
235  // If the block has no terminators, it just falls into the block after it.
236  MachineBasicBlock::iterator I = MBB.end();
237  if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
238    return false;
239
240  // Get the last instruction in the block.
241  MachineInstr *LastInst = I;
242
243  // If there is only one terminator instruction, process it.
244  if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
245    if (IsBRU(LastInst->getOpcode())) {
246      TBB = LastInst->getOperand(0).getMBB();
247      return false;
248    }
249
250    XCore::CondCode BranchCode = GetCondFromBranchOpc(LastInst->getOpcode());
251    if (BranchCode == XCore::COND_INVALID)
252      return true;  // Can't handle indirect branch.
253
254    // Conditional branch
255    // Block ends with fall-through condbranch.
256
257    TBB = LastInst->getOperand(1).getMBB();
258    Cond.push_back(MachineOperand::CreateImm(BranchCode));
259    Cond.push_back(LastInst->getOperand(0));
260    return false;
261  }
262
263  // Get the instruction before it if it's a terminator.
264  MachineInstr *SecondLastInst = I;
265
266  // If there are three terminators, we don't know what sort of block this is.
267  if (SecondLastInst && I != MBB.begin() &&
268      isUnpredicatedTerminator(--I))
269    return true;
270
271  unsigned SecondLastOpc    = SecondLastInst->getOpcode();
272  XCore::CondCode BranchCode = GetCondFromBranchOpc(SecondLastOpc);
273
274  // If the block ends with conditional branch followed by unconditional,
275  // handle it.
276  if (BranchCode != XCore::COND_INVALID
277    && IsBRU(LastInst->getOpcode())) {
278
279    TBB = SecondLastInst->getOperand(1).getMBB();
280    Cond.push_back(MachineOperand::CreateImm(BranchCode));
281    Cond.push_back(SecondLastInst->getOperand(0));
282
283    FBB = LastInst->getOperand(0).getMBB();
284    return false;
285  }
286
287  // If the block ends with two unconditional branches, handle it.  The second
288  // one is not executed, so remove it.
289  if (IsBRU(SecondLastInst->getOpcode()) &&
290      IsBRU(LastInst->getOpcode())) {
291    TBB = SecondLastInst->getOperand(0).getMBB();
292    I = LastInst;
293    if (AllowModify)
294      I->eraseFromParent();
295    return false;
296  }
297
298  // Otherwise, can't handle this.
299  return true;
300}
301
302unsigned
303XCoreInstrInfo::InsertBranch(MachineBasicBlock &MBB,MachineBasicBlock *TBB,
304                             MachineBasicBlock *FBB,
305                             const SmallVectorImpl<MachineOperand> &Cond)const{
306  // FIXME there should probably be a DebugLoc argument here
307  DebugLoc dl = DebugLoc::getUnknownLoc();
308  // Shouldn't be a fall through.
309  assert(TBB && "InsertBranch must not be told to insert a fallthrough");
310  assert((Cond.size() == 2 || Cond.size() == 0) &&
311         "Unexpected number of components!");
312
313  if (FBB == 0) { // One way branch.
314    if (Cond.empty()) {
315      // Unconditional branch
316      BuildMI(&MBB, dl, get(XCore::BRFU_lu6)).addMBB(TBB);
317    } else {
318      // Conditional branch.
319      unsigned Opc = GetCondBranchFromCond((XCore::CondCode)Cond[0].getImm());
320      BuildMI(&MBB, dl, get(Opc)).addReg(Cond[1].getReg())
321                             .addMBB(TBB);
322    }
323    return 1;
324  }
325
326  // Two-way Conditional branch.
327  assert(Cond.size() == 2 && "Unexpected number of components!");
328  unsigned Opc = GetCondBranchFromCond((XCore::CondCode)Cond[0].getImm());
329  BuildMI(&MBB, dl, get(Opc)).addReg(Cond[1].getReg())
330                         .addMBB(TBB);
331  BuildMI(&MBB, dl, get(XCore::BRFU_lu6)).addMBB(FBB);
332  return 2;
333}
334
335unsigned
336XCoreInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
337  MachineBasicBlock::iterator I = MBB.end();
338  if (I == MBB.begin()) return 0;
339  --I;
340  if (!IsBRU(I->getOpcode()) && !IsCondBranch(I->getOpcode()))
341    return 0;
342
343  // Remove the branch.
344  I->eraseFromParent();
345
346  I = MBB.end();
347
348  if (I == MBB.begin()) return 1;
349  --I;
350  if (!IsCondBranch(I->getOpcode()))
351    return 1;
352
353  // Remove the branch.
354  I->eraseFromParent();
355  return 2;
356}
357
358bool XCoreInstrInfo::copyRegToReg(MachineBasicBlock &MBB,
359                                  MachineBasicBlock::iterator I,
360                                  unsigned DestReg, unsigned SrcReg,
361                                  const TargetRegisterClass *DestRC,
362                                  const TargetRegisterClass *SrcRC) const {
363  DebugLoc DL = DebugLoc::getUnknownLoc();
364  if (I != MBB.end()) DL = I->getDebugLoc();
365
366  if (DestRC == SrcRC) {
367    if (DestRC == XCore::GRRegsRegisterClass) {
368      BuildMI(MBB, I, DL, get(XCore::ADD_2rus), DestReg)
369        .addReg(SrcReg)
370        .addImm(0);
371      return true;
372    } else {
373      return false;
374    }
375  }
376
377  if (SrcRC == XCore::RRegsRegisterClass && SrcReg == XCore::SP &&
378    DestRC == XCore::GRRegsRegisterClass) {
379    BuildMI(MBB, I, DL, get(XCore::LDAWSP_ru6), DestReg)
380      .addImm(0);
381    return true;
382  }
383  if (DestRC == XCore::RRegsRegisterClass && DestReg == XCore::SP &&
384    SrcRC == XCore::GRRegsRegisterClass) {
385    BuildMI(MBB, I, DL, get(XCore::SETSP_1r))
386      .addReg(SrcReg);
387    return true;
388  }
389  return false;
390}
391
392void XCoreInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
393                                         MachineBasicBlock::iterator I,
394                                         unsigned SrcReg, bool isKill,
395                                         int FrameIndex,
396                                         const TargetRegisterClass *RC) const
397{
398  DebugLoc DL = DebugLoc::getUnknownLoc();
399  if (I != MBB.end()) DL = I->getDebugLoc();
400  BuildMI(MBB, I, DL, get(XCore::STWFI))
401    .addReg(SrcReg, getKillRegState(isKill))
402    .addFrameIndex(FrameIndex)
403    .addImm(0);
404}
405
406void XCoreInstrInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
407                            bool isKill, SmallVectorImpl<MachineOperand> &Addr,
408                            const TargetRegisterClass *RC,
409                            SmallVectorImpl<MachineInstr*> &NewMIs) const
410{
411  llvm_unreachable("unimplemented");
412}
413
414void XCoreInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
415                                          MachineBasicBlock::iterator I,
416                                          unsigned DestReg, int FrameIndex,
417                                          const TargetRegisterClass *RC) const
418{
419  DebugLoc DL = DebugLoc::getUnknownLoc();
420  if (I != MBB.end()) DL = I->getDebugLoc();
421  BuildMI(MBB, I, DL, get(XCore::LDWFI), DestReg)
422    .addFrameIndex(FrameIndex)
423    .addImm(0);
424}
425
426void XCoreInstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
427                              SmallVectorImpl<MachineOperand> &Addr,
428                              const TargetRegisterClass *RC,
429                              SmallVectorImpl<MachineInstr*> &NewMIs) const
430{
431  llvm_unreachable("unimplemented");
432}
433
434bool XCoreInstrInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
435                                               MachineBasicBlock::iterator MI,
436                                  const std::vector<CalleeSavedInfo> &CSI) const
437{
438  if (CSI.empty()) {
439    return true;
440  }
441  MachineFunction *MF = MBB.getParent();
442  const MachineFrameInfo *MFI = MF->getFrameInfo();
443  MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
444  XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
445
446  bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(*MF);
447
448  DebugLoc DL = DebugLoc::getUnknownLoc();
449  if (MI != MBB.end()) DL = MI->getDebugLoc();
450
451  for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
452                                                    it != CSI.end(); ++it) {
453    // Add the callee-saved register as live-in. It's killed at the spill.
454    MBB.addLiveIn(it->getReg());
455
456    storeRegToStackSlot(MBB, MI, it->getReg(), true,
457                        it->getFrameIdx(), it->getRegClass());
458    if (emitFrameMoves) {
459      unsigned SaveLabelId = MMI->NextLabelID();
460      BuildMI(MBB, MI, DL, get(XCore::DBG_LABEL)).addImm(SaveLabelId);
461      XFI->getSpillLabels().push_back(
462          std::pair<unsigned, CalleeSavedInfo>(SaveLabelId, *it));
463    }
464  }
465  return true;
466}
467
468bool XCoreInstrInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
469                                         MachineBasicBlock::iterator MI,
470                               const std::vector<CalleeSavedInfo> &CSI) const
471{
472  bool AtStart = MI == MBB.begin();
473  MachineBasicBlock::iterator BeforeI = MI;
474  if (!AtStart)
475    --BeforeI;
476  for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
477                                                    it != CSI.end(); ++it) {
478
479    loadRegFromStackSlot(MBB, MI, it->getReg(),
480                                  it->getFrameIdx(),
481                                  it->getRegClass());
482    assert(MI != MBB.begin() &&
483           "loadRegFromStackSlot didn't insert any code!");
484    // Insert in reverse order.  loadRegFromStackSlot can insert multiple
485    // instructions.
486    if (AtStart)
487      MI = MBB.begin();
488    else {
489      MI = BeforeI;
490      ++MI;
491    }
492  }
493  return true;
494}
495
496/// BlockHasNoFallThrough - Analyse if MachineBasicBlock does not
497/// fall-through into its successor block.
498bool XCoreInstrInfo::
499BlockHasNoFallThrough(const MachineBasicBlock &MBB) const
500{
501  if (MBB.empty()) return false;
502
503  switch (MBB.back().getOpcode()) {
504  case XCore::RETSP_u6:     // Return.
505  case XCore::RETSP_lu6:
506  case XCore::BAU_1r:       // Indirect branch.
507  case XCore::BRFU_u6:      // Uncond branch.
508  case XCore::BRFU_lu6:
509  case XCore::BRBU_u6:
510  case XCore::BRBU_lu6:
511    return true;
512  default: return false;
513  }
514}
515
516/// ReverseBranchCondition - Return the inverse opcode of the
517/// specified Branch instruction.
518bool XCoreInstrInfo::
519ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const
520{
521  assert((Cond.size() == 2) &&
522          "Invalid XCore branch condition!");
523  Cond[0].setImm(GetOppositeBranchCondition((XCore::CondCode)Cond[0].getImm()));
524  return false;
525}
526