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 "InstPrinter/MipsInstPrinter.h"
16 #include "MipsMachineFunction.h"
17 #include "MipsSubtarget.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/TargetRegistry.h"
23 
24 using namespace llvm;
25 
26 #define GET_INSTRINFO_CTOR_DTOR
27 #include "MipsGenInstrInfo.inc"
28 
29 // Pin the vtable to this file.
30 void MipsInstrInfo::anchor() {}
31 
32 MipsInstrInfo::MipsInstrInfo(const MipsSubtarget &STI, unsigned UncondBr)
33     : MipsGenInstrInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),
34       Subtarget(STI), UncondBrOpc(UncondBr) {}
35 
36 const MipsInstrInfo *MipsInstrInfo::create(MipsSubtarget &STI) {
37   if (STI.inMips16Mode())
38     return llvm::createMips16InstrInfo(STI);
39 
40   return llvm::createMipsSEInstrInfo(STI);
41 }
42 
43 bool MipsInstrInfo::isZeroImm(const MachineOperand &op) const {
44   return op.isImm() && op.getImm() == 0;
45 }
46 
47 /// insertNoop - If data hazard condition is found insert the target nop
48 /// instruction.
49 // FIXME: This appears to be dead code.
50 void MipsInstrInfo::
51 insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
52 {
53   DebugLoc DL;
54   BuildMI(MBB, MI, DL, get(Mips::NOP));
55 }
56 
57 MachineMemOperand *
58 MipsInstrInfo::GetMemOperand(MachineBasicBlock &MBB, int FI,
59                              MachineMemOperand::Flags Flags) const {
60   MachineFunction &MF = *MBB.getParent();
61   MachineFrameInfo &MFI = MF.getFrameInfo();
62   unsigned Align = MFI.getObjectAlignment(FI);
63 
64   return MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
65                                  Flags, MFI.getObjectSize(FI), Align);
66 }
67 
68 //===----------------------------------------------------------------------===//
69 // Branch Analysis
70 //===----------------------------------------------------------------------===//
71 
72 void MipsInstrInfo::AnalyzeCondBr(const MachineInstr *Inst, unsigned Opc,
73                                   MachineBasicBlock *&BB,
74                                   SmallVectorImpl<MachineOperand> &Cond) const {
75   assert(getAnalyzableBrOpc(Opc) && "Not an analyzable branch");
76   int NumOp = Inst->getNumExplicitOperands();
77 
78   // for both int and fp branches, the last explicit operand is the
79   // MBB.
80   BB = Inst->getOperand(NumOp-1).getMBB();
81   Cond.push_back(MachineOperand::CreateImm(Opc));
82 
83   for (int i=0; i<NumOp-1; i++)
84     Cond.push_back(Inst->getOperand(i));
85 }
86 
87 bool MipsInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
88                                   MachineBasicBlock *&TBB,
89                                   MachineBasicBlock *&FBB,
90                                   SmallVectorImpl<MachineOperand> &Cond,
91                                   bool AllowModify) const {
92   SmallVector<MachineInstr*, 2> BranchInstrs;
93   BranchType BT = analyzeBranch(MBB, TBB, FBB, Cond, AllowModify, BranchInstrs);
94 
95   return (BT == BT_None) || (BT == BT_Indirect);
96 }
97 
98 void MipsInstrInfo::BuildCondBr(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
99                                 const DebugLoc &DL,
100                                 ArrayRef<MachineOperand> Cond) const {
101   unsigned Opc = Cond[0].getImm();
102   const MCInstrDesc &MCID = get(Opc);
103   MachineInstrBuilder MIB = BuildMI(&MBB, DL, MCID);
104 
105   for (unsigned i = 1; i < Cond.size(); ++i) {
106     if (Cond[i].isReg())
107       MIB.addReg(Cond[i].getReg());
108     else if (Cond[i].isImm())
109       MIB.addImm(Cond[i].getImm());
110     else
111        assert(false && "Cannot copy operand");
112   }
113   MIB.addMBB(TBB);
114 }
115 
116 unsigned MipsInstrInfo::InsertBranch(MachineBasicBlock &MBB,
117                                      MachineBasicBlock *TBB,
118                                      MachineBasicBlock *FBB,
119                                      ArrayRef<MachineOperand> Cond,
120                                      const DebugLoc &DL) const {
121   // Shouldn't be a fall through.
122   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
123 
124   // # of condition operands:
125   //  Unconditional branches: 0
126   //  Floating point branches: 1 (opc)
127   //  Int BranchZero: 2 (opc, reg)
128   //  Int Branch: 3 (opc, reg0, reg1)
129   assert((Cond.size() <= 3) &&
130          "# of Mips branch conditions must be <= 3!");
131 
132   // Two-way Conditional branch.
133   if (FBB) {
134     BuildCondBr(MBB, TBB, DL, Cond);
135     BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(FBB);
136     return 2;
137   }
138 
139   // One way branch.
140   // Unconditional branch.
141   if (Cond.empty())
142     BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(TBB);
143   else // Conditional branch.
144     BuildCondBr(MBB, TBB, DL, Cond);
145   return 1;
146 }
147 
148 unsigned MipsInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
149   MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
150   MachineBasicBlock::reverse_iterator FirstBr;
151   unsigned removed;
152 
153   // Skip all the debug instructions.
154   while (I != REnd && I->isDebugValue())
155     ++I;
156 
157   FirstBr = I;
158 
159   // Up to 2 branches are removed.
160   // Note that indirect branches are not removed.
161   for (removed = 0; I != REnd && removed < 2; ++I, ++removed)
162     if (!getAnalyzableBrOpc(I->getOpcode()))
163       break;
164 
165   MBB.erase(I.base(), FirstBr.base());
166 
167   return removed;
168 }
169 
170 /// ReverseBranchCondition - Return the inverse opcode of the
171 /// specified Branch instruction.
172 bool MipsInstrInfo::ReverseBranchCondition(
173     SmallVectorImpl<MachineOperand> &Cond) const {
174   assert( (Cond.size() && Cond.size() <= 3) &&
175           "Invalid Mips branch condition!");
176   Cond[0].setImm(getOppositeBranchOpc(Cond[0].getImm()));
177   return false;
178 }
179 
180 MipsInstrInfo::BranchType MipsInstrInfo::analyzeBranch(
181     MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB,
182     SmallVectorImpl<MachineOperand> &Cond, bool AllowModify,
183     SmallVectorImpl<MachineInstr *> &BranchInstrs) const {
184 
185   MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
186 
187   // Skip all the debug instructions.
188   while (I != REnd && I->isDebugValue())
189     ++I;
190 
191   if (I == REnd || !isUnpredicatedTerminator(*I)) {
192     // This block ends with no branches (it just falls through to its succ).
193     // Leave TBB/FBB null.
194     TBB = FBB = nullptr;
195     return BT_NoBranch;
196   }
197 
198   MachineInstr *LastInst = &*I;
199   unsigned LastOpc = LastInst->getOpcode();
200   BranchInstrs.push_back(LastInst);
201 
202   // Not an analyzable branch (e.g., indirect jump).
203   if (!getAnalyzableBrOpc(LastOpc))
204     return LastInst->isIndirectBranch() ? BT_Indirect : BT_None;
205 
206   // Get the second to last instruction in the block.
207   unsigned SecondLastOpc = 0;
208   MachineInstr *SecondLastInst = nullptr;
209 
210   if (++I != REnd) {
211     SecondLastInst = &*I;
212     SecondLastOpc = getAnalyzableBrOpc(SecondLastInst->getOpcode());
213 
214     // Not an analyzable branch (must be an indirect jump).
215     if (isUnpredicatedTerminator(*SecondLastInst) && !SecondLastOpc)
216       return BT_None;
217   }
218 
219   // If there is only one terminator instruction, process it.
220   if (!SecondLastOpc) {
221     // Unconditional branch.
222     if (LastInst->isUnconditionalBranch()) {
223       TBB = LastInst->getOperand(0).getMBB();
224       return BT_Uncond;
225     }
226 
227     // Conditional branch
228     AnalyzeCondBr(LastInst, LastOpc, TBB, Cond);
229     return BT_Cond;
230   }
231 
232   // If we reached here, there are two branches.
233   // If there are three terminators, we don't know what sort of block this is.
234   if (++I != REnd && isUnpredicatedTerminator(*I))
235     return BT_None;
236 
237   BranchInstrs.insert(BranchInstrs.begin(), SecondLastInst);
238 
239   // If second to last instruction is an unconditional branch,
240   // analyze it and remove the last instruction.
241   if (SecondLastInst->isUnconditionalBranch()) {
242     // Return if the last instruction cannot be removed.
243     if (!AllowModify)
244       return BT_None;
245 
246     TBB = SecondLastInst->getOperand(0).getMBB();
247     LastInst->eraseFromParent();
248     BranchInstrs.pop_back();
249     return BT_Uncond;
250   }
251 
252   // Conditional branch followed by an unconditional branch.
253   // The last one must be unconditional.
254   if (!LastInst->isUnconditionalBranch())
255     return BT_None;
256 
257   AnalyzeCondBr(SecondLastInst, SecondLastOpc, TBB, Cond);
258   FBB = LastInst->getOperand(0).getMBB();
259 
260   return BT_CondUncond;
261 }
262 
263 /// Return the corresponding compact (no delay slot) form of a branch.
264 unsigned MipsInstrInfo::getEquivalentCompactForm(
265     const MachineBasicBlock::iterator I) const {
266   unsigned Opcode = I->getOpcode();
267   bool canUseShortMicroMipsCTI = false;
268 
269   if (Subtarget.inMicroMipsMode()) {
270     switch (Opcode) {
271     case Mips::BNE:
272     case Mips::BNE_MM:
273     case Mips::BEQ:
274     case Mips::BEQ_MM:
275     // microMIPS has NE,EQ branches that do not have delay slots provided one
276     // of the operands is zero.
277       if (I->getOperand(1).getReg() == Subtarget.getABI().GetZeroReg())
278         canUseShortMicroMipsCTI = true;
279       break;
280     // For microMIPS the PseudoReturn and PseudoIndirectBranch are always
281     // expanded to JR_MM, so they can be replaced with JRC16_MM.
282     case Mips::JR:
283     case Mips::PseudoReturn:
284     case Mips::PseudoIndirectBranch:
285     case Mips::TAILCALLREG:
286       canUseShortMicroMipsCTI = true;
287       break;
288     }
289   }
290 
291   // MIPSR6 forbids both operands being the zero register.
292   if (Subtarget.hasMips32r6() && (I->getNumOperands() > 1) &&
293       (I->getOperand(0).isReg() &&
294        (I->getOperand(0).getReg() == Mips::ZERO ||
295         I->getOperand(0).getReg() == Mips::ZERO_64)) &&
296       (I->getOperand(1).isReg() &&
297        (I->getOperand(1).getReg() == Mips::ZERO ||
298         I->getOperand(1).getReg() == Mips::ZERO_64)))
299     return 0;
300 
301   if (Subtarget.hasMips32r6() || canUseShortMicroMipsCTI) {
302     switch (Opcode) {
303     case Mips::B:
304       return Mips::BC;
305     case Mips::BAL:
306       return Mips::BALC;
307     case Mips::BEQ:
308     case Mips::BEQ_MM:
309       if (canUseShortMicroMipsCTI)
310         return Mips::BEQZC_MM;
311       else if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
312         return 0;
313       return Mips::BEQC;
314     case Mips::BNE:
315     case Mips::BNE_MM:
316       if (canUseShortMicroMipsCTI)
317         return Mips::BNEZC_MM;
318       else if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
319         return 0;
320       return Mips::BNEC;
321     case Mips::BGE:
322       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
323         return 0;
324       return Mips::BGEC;
325     case Mips::BGEU:
326       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
327         return 0;
328       return Mips::BGEUC;
329     case Mips::BGEZ:
330       return Mips::BGEZC;
331     case Mips::BGTZ:
332       return Mips::BGTZC;
333     case Mips::BLEZ:
334       return Mips::BLEZC;
335     case Mips::BLT:
336       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
337         return 0;
338       return Mips::BLTC;
339     case Mips::BLTU:
340       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
341         return 0;
342       return Mips::BLTUC;
343     case Mips::BLTZ:
344       return Mips::BLTZC;
345     case Mips::BEQ64:
346       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
347         return 0;
348       return Mips::BEQC64;
349     case Mips::BNE64:
350       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
351         return 0;
352       return Mips::BNEC64;
353     case Mips::BGTZ64:
354       return Mips::BGTZC64;
355     case Mips::BGEZ64:
356       return Mips::BGEZC64;
357     case Mips::BLTZ64:
358       return Mips::BLTZC64;
359     case Mips::BLEZ64:
360       return Mips::BLEZC64;
361     // For MIPSR6, the instruction 'jic' can be used for these cases. Some
362     // tools will accept 'jrc reg' as an alias for 'jic 0, $reg'.
363     case Mips::JR:
364     case Mips::PseudoReturn:
365     case Mips::PseudoIndirectBranch:
366     case Mips::TAILCALLREG:
367       if (canUseShortMicroMipsCTI)
368         return Mips::JRC16_MM;
369       return Mips::JIC;
370     case Mips::JALRPseudo:
371       return Mips::JIALC;
372     case Mips::JR64:
373     case Mips::PseudoReturn64:
374     case Mips::PseudoIndirectBranch64:
375     case Mips::TAILCALLREG64:
376       return Mips::JIC64;
377     case Mips::JALR64Pseudo:
378       return Mips::JIALC64;
379     default:
380       return 0;
381     }
382   }
383 
384   return 0;
385 }
386 
387 /// Predicate for distingushing between control transfer instructions and all
388 /// other instructions for handling forbidden slots. Consider inline assembly
389 /// as unsafe as well.
390 bool MipsInstrInfo::SafeInForbiddenSlot(const MachineInstr &MI) const {
391   if (MI.isInlineAsm())
392     return false;
393 
394   return (MI.getDesc().TSFlags & MipsII::IsCTI) == 0;
395 
396 }
397 
398 /// Predicate for distingushing instructions that have forbidden slots.
399 bool MipsInstrInfo::HasForbiddenSlot(const MachineInstr &MI) const {
400   return (MI.getDesc().TSFlags & MipsII::HasForbiddenSlot) != 0;
401 }
402 
403 /// Return the number of bytes of code the specified instruction may be.
404 unsigned MipsInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
405   switch (MI.getOpcode()) {
406   default:
407     return MI.getDesc().getSize();
408   case  TargetOpcode::INLINEASM: {       // Inline Asm: Variable size.
409     const MachineFunction *MF = MI.getParent()->getParent();
410     const char *AsmStr = MI.getOperand(0).getSymbolName();
411     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
412   }
413   case Mips::CONSTPOOL_ENTRY:
414     // If this machine instr is a constant pool entry, its size is recorded as
415     // operand #2.
416     return MI.getOperand(2).getImm();
417   }
418 }
419 
420 MachineInstrBuilder
421 MipsInstrInfo::genInstrWithNewOpc(unsigned NewOpc,
422                                   MachineBasicBlock::iterator I) const {
423   MachineInstrBuilder MIB;
424 
425   // Certain branches have two forms: e.g beq $1, $zero, dest vs beqz $1, dest
426   // Pick the zero form of the branch for readable assembly and for greater
427   // branch distance in non-microMIPS mode.
428   // Additional MIPSR6 does not permit the use of register $zero for compact
429   // branches.
430   // FIXME: Certain atomic sequences on mips64 generate 32bit references to
431   // Mips::ZERO, which is incorrect. This test should be updated to use
432   // Subtarget.getABI().GetZeroReg() when those atomic sequences and others
433   // are fixed.
434   int ZeroOperandPosition = -1;
435   bool BranchWithZeroOperand = false;
436   if (I->isBranch() && !I->isPseudo()) {
437     auto TRI = I->getParent()->getParent()->getSubtarget().getRegisterInfo();
438     ZeroOperandPosition = I->findRegisterUseOperandIdx(Mips::ZERO, false, TRI);
439     BranchWithZeroOperand = ZeroOperandPosition != -1;
440   }
441 
442   if (BranchWithZeroOperand) {
443     switch (NewOpc) {
444     case Mips::BEQC:
445       NewOpc = Mips::BEQZC;
446       break;
447     case Mips::BNEC:
448       NewOpc = Mips::BNEZC;
449       break;
450     case Mips::BGEC:
451       NewOpc = Mips::BGEZC;
452       break;
453     case Mips::BLTC:
454       NewOpc = Mips::BLTZC;
455       break;
456     case Mips::BEQC64:
457       NewOpc = Mips::BEQZC64;
458       break;
459     case Mips::BNEC64:
460       NewOpc = Mips::BNEZC64;
461       break;
462     }
463   }
464 
465   MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), get(NewOpc));
466 
467   // For MIPSR6 JI*C requires an immediate 0 as an operand, JIALC(64) an
468   // immediate 0 as an operand and requires the removal of it's %RA<imp-def>
469   // implicit operand as copying the implicit operations of the instructio we're
470   // looking at will give us the correct flags.
471   if (NewOpc == Mips::JIC || NewOpc == Mips::JIALC || NewOpc == Mips::JIC64 ||
472       NewOpc == Mips::JIALC64) {
473 
474     if (NewOpc == Mips::JIALC || NewOpc == Mips::JIALC64)
475       MIB->RemoveOperand(0);
476 
477     for (unsigned J = 0, E = I->getDesc().getNumOperands(); J < E; ++J) {
478       MIB.addOperand(I->getOperand(J));
479     }
480 
481     MIB.addImm(0);
482 
483   } else {
484     for (unsigned J = 0, E = I->getDesc().getNumOperands(); J < E; ++J) {
485       if (BranchWithZeroOperand && (unsigned)ZeroOperandPosition == J)
486         continue;
487 
488       MIB.addOperand(I->getOperand(J));
489     }
490   }
491 
492   MIB.copyImplicitOps(*I);
493 
494   MIB.setMemRefs(I->memoperands_begin(), I->memoperands_end());
495   return MIB;
496 }
497