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