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