Fix some -march=thumb regressions. tBR_JTr is not predicable.
[oota-llvm.git] / lib / Target / ARM / ARMInstrInfo.cpp
1 //===- ARMInstrInfo.cpp - ARM Instruction Information -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the "Instituto Nokia de Tecnologia" and
6 // is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file contains the ARM implementation of the TargetInstrInfo class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMInstrInfo.h"
16 #include "ARM.h"
17 #include "ARMAddressingModes.h"
18 #include "ARMGenInstrInfo.inc"
19 #include "ARMMachineFunctionInfo.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/Target/TargetAsmInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 using namespace llvm;
26
27 static cl::opt<bool> EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
28                                   cl::desc("Enable ARM 2-addr to 3-addr conv"));
29
30 ARMInstrInfo::ARMInstrInfo(const ARMSubtarget &STI)
31   : TargetInstrInfo(ARMInsts, sizeof(ARMInsts)/sizeof(ARMInsts[0])),
32     RI(*this, STI) {
33 }
34
35 const TargetRegisterClass *ARMInstrInfo::getPointerRegClass() const {
36   return &ARM::GPRRegClass;
37 }
38
39 /// Return true if the instruction is a register to register move and
40 /// leave the source and dest operands in the passed parameters.
41 ///
42 bool ARMInstrInfo::isMoveInstr(const MachineInstr &MI,
43                                unsigned &SrcReg, unsigned &DstReg) const {
44   MachineOpCode oc = MI.getOpcode();
45   switch (oc) {
46   default:
47     return false;
48   case ARM::FCPYS:
49   case ARM::FCPYD:
50     SrcReg = MI.getOperand(1).getReg();
51     DstReg = MI.getOperand(0).getReg();
52     return true;
53   case ARM::MOVr:
54   case ARM::tMOVr:
55     assert(MI.getInstrDescriptor()->numOperands >= 2 &&
56            MI.getOperand(0).isRegister() &&
57            MI.getOperand(1).isRegister() &&
58            "Invalid ARM MOV instruction");
59     SrcReg = MI.getOperand(1).getReg();
60     DstReg = MI.getOperand(0).getReg();
61     return true;
62   }
63 }
64
65 unsigned ARMInstrInfo::isLoadFromStackSlot(MachineInstr *MI, int &FrameIndex) const{
66   switch (MI->getOpcode()) {
67   default: break;
68   case ARM::LDR:
69     if (MI->getOperand(1).isFrameIndex() &&
70         MI->getOperand(2).isReg() &&
71         MI->getOperand(3).isImmediate() && 
72         MI->getOperand(2).getReg() == 0 &&
73         MI->getOperand(3).getImmedValue() == 0) {
74       FrameIndex = MI->getOperand(1).getFrameIndex();
75       return MI->getOperand(0).getReg();
76     }
77     break;
78   case ARM::FLDD:
79   case ARM::FLDS:
80     if (MI->getOperand(1).isFrameIndex() &&
81         MI->getOperand(2).isImmediate() && 
82         MI->getOperand(2).getImmedValue() == 0) {
83       FrameIndex = MI->getOperand(1).getFrameIndex();
84       return MI->getOperand(0).getReg();
85     }
86     break;
87   case ARM::tRestore:
88     if (MI->getOperand(1).isFrameIndex() &&
89         MI->getOperand(2).isImmediate() && 
90         MI->getOperand(2).getImmedValue() == 0) {
91       FrameIndex = MI->getOperand(1).getFrameIndex();
92       return MI->getOperand(0).getReg();
93     }
94     break;
95   }
96   return 0;
97 }
98
99 unsigned ARMInstrInfo::isStoreToStackSlot(MachineInstr *MI, int &FrameIndex) const {
100   switch (MI->getOpcode()) {
101   default: break;
102   case ARM::STR:
103     if (MI->getOperand(1).isFrameIndex() &&
104         MI->getOperand(2).isReg() &&
105         MI->getOperand(3).isImmediate() && 
106         MI->getOperand(2).getReg() == 0 &&
107         MI->getOperand(3).getImmedValue() == 0) {
108       FrameIndex = MI->getOperand(1).getFrameIndex();
109       return MI->getOperand(0).getReg();
110     }
111     break;
112   case ARM::FSTD:
113   case ARM::FSTS:
114     if (MI->getOperand(1).isFrameIndex() &&
115         MI->getOperand(2).isImmediate() && 
116         MI->getOperand(2).getImmedValue() == 0) {
117       FrameIndex = MI->getOperand(1).getFrameIndex();
118       return MI->getOperand(0).getReg();
119     }
120     break;
121   case ARM::tSpill:
122     if (MI->getOperand(1).isFrameIndex() &&
123         MI->getOperand(2).isImmediate() && 
124         MI->getOperand(2).getImmedValue() == 0) {
125       FrameIndex = MI->getOperand(1).getFrameIndex();
126       return MI->getOperand(0).getReg();
127     }
128     break;
129   }
130   return 0;
131 }
132
133 static unsigned getUnindexedOpcode(unsigned Opc) {
134   switch (Opc) {
135   default: break;
136   case ARM::LDR_PRE:
137   case ARM::LDR_POST:
138     return ARM::LDR;
139   case ARM::LDRH_PRE:
140   case ARM::LDRH_POST:
141     return ARM::LDRH;
142   case ARM::LDRB_PRE:
143   case ARM::LDRB_POST:
144     return ARM::LDRB;
145   case ARM::LDRSH_PRE:
146   case ARM::LDRSH_POST:
147     return ARM::LDRSH;
148   case ARM::LDRSB_PRE:
149   case ARM::LDRSB_POST:
150     return ARM::LDRSB;
151   case ARM::STR_PRE:
152   case ARM::STR_POST:
153     return ARM::STR;
154   case ARM::STRH_PRE:
155   case ARM::STRH_POST:
156     return ARM::STRH;
157   case ARM::STRB_PRE:
158   case ARM::STRB_POST:
159     return ARM::STRB;
160   }
161   return 0;
162 }
163
164 MachineInstr *
165 ARMInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
166                                     MachineBasicBlock::iterator &MBBI,
167                                     LiveVariables &LV) const {
168   if (!EnableARM3Addr)
169     return NULL;
170
171   MachineInstr *MI = MBBI;
172   unsigned TSFlags = MI->getInstrDescriptor()->TSFlags;
173   bool isPre = false;
174   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
175   default: return NULL;
176   case ARMII::IndexModePre:
177     isPre = true;
178     break;
179   case ARMII::IndexModePost:
180     break;
181   }
182
183   // Try spliting an indexed load / store to a un-indexed one plus an add/sub
184   // operation.
185   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
186   if (MemOpc == 0)
187     return NULL;
188
189   MachineInstr *UpdateMI = NULL;
190   MachineInstr *MemMI = NULL;
191   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
192   const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
193   unsigned NumOps = TID->numOperands;
194   bool isLoad = (TID->Flags & M_LOAD_FLAG) != 0;
195   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
196   const MachineOperand &Base = MI->getOperand(2);
197   const MachineOperand &Offset = MI->getOperand(NumOps-3);
198   unsigned WBReg = WB.getReg();
199   unsigned BaseReg = Base.getReg();
200   unsigned OffReg = Offset.getReg();
201   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
202   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
203   switch (AddrMode) {
204   default:
205     assert(false && "Unknown indexed op!");
206     return NULL;
207   case ARMII::AddrMode2: {
208     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
209     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
210     if (OffReg == 0) {
211       int SOImmVal = ARM_AM::getSOImmVal(Amt);
212       if (SOImmVal == -1)
213         // Can't encode it in a so_imm operand. This transformation will
214         // add more than 1 instruction. Abandon!
215         return NULL;
216       UpdateMI = BuildMI(get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
217         .addReg(BaseReg).addImm(SOImmVal).addImm(Pred);
218     } else if (Amt != 0) {
219       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
220       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
221       UpdateMI = BuildMI(get(isSub ? ARM::SUBrs : ARM::ADDrs), WBReg)
222         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc).addImm(Pred);
223     } else 
224       UpdateMI = BuildMI(get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
225         .addReg(BaseReg).addReg(OffReg).addImm(Pred);
226     break;
227   }
228   case ARMII::AddrMode3 : {
229     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
230     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
231     if (OffReg == 0)
232       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
233       UpdateMI = BuildMI(get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
234         .addReg(BaseReg).addImm(Amt).addImm(Pred);
235     else
236       UpdateMI = BuildMI(get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
237         .addReg(BaseReg).addReg(OffReg).addImm(Pred);
238     break;
239   }
240   }
241
242   std::vector<MachineInstr*> NewMIs;
243   if (isPre) {
244     if (isLoad)
245       MemMI = BuildMI(get(MemOpc), MI->getOperand(0).getReg())
246         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
247     else
248       MemMI = BuildMI(get(MemOpc)).addReg(MI->getOperand(1).getReg())
249         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
250     NewMIs.push_back(MemMI);
251     NewMIs.push_back(UpdateMI);
252   } else {
253     if (isLoad)
254       MemMI = BuildMI(get(MemOpc), MI->getOperand(0).getReg())
255         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
256     else
257       MemMI = BuildMI(get(MemOpc)).addReg(MI->getOperand(1).getReg())
258         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
259     if (WB.isDead())
260       UpdateMI->getOperand(0).setIsDead();
261     NewMIs.push_back(UpdateMI);
262     NewMIs.push_back(MemMI);
263   }
264   
265   // Transfer LiveVariables states, kill / dead info.
266   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
267     MachineOperand &MO = MI->getOperand(i);
268     if (MO.isRegister() && MO.getReg() &&
269         MRegisterInfo::isVirtualRegister(MO.getReg())) {
270       unsigned Reg = MO.getReg();
271       LiveVariables::VarInfo &VI = LV.getVarInfo(Reg);
272       if (MO.isDef()) {
273         MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
274         if (MO.isDead())
275           LV.addVirtualRegisterDead(Reg, NewMI);
276         // Update the defining instruction.
277         if (VI.DefInst == MI)
278           VI.DefInst = NewMI;
279       }
280       if (MO.isUse() && MO.isKill()) {
281         for (unsigned j = 0; j < 2; ++j) {
282           // Look at the two new MI's in reverse order.
283           MachineInstr *NewMI = NewMIs[j];
284           int NIdx = NewMI->findRegisterUseOperandIdx(Reg);
285           if (NIdx == -1)
286             continue;
287           LV.addVirtualRegisterKilled(Reg, NewMI);
288           if (VI.removeKill(MI))
289             VI.Kills.push_back(NewMI);
290           break;
291         }
292       }
293     }
294   }
295
296   MFI->insert(MBBI, NewMIs[1]);
297   MFI->insert(MBBI, NewMIs[0]);
298   return NewMIs[0];
299 }
300
301 static bool isPredicated(MachineInstr *MI) {
302   MachineOperand *PMO = MI->findFirstPredOperand();
303   return PMO && PMO->getImmedValue() != ARMCC::AL;
304 }
305
306 // Branch analysis.
307 bool ARMInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
308                                  MachineBasicBlock *&FBB,
309                                  std::vector<MachineOperand> &Cond) const {
310   // If the block has no terminators, it just falls into the block after it.
311   MachineBasicBlock::iterator I = MBB.end();
312   if (I == MBB.begin() || !isTerminatorInstr((--I)->getOpcode()))
313     return false;
314   
315   // Get the last instruction in the block.
316   MachineInstr *LastInst = I;
317   
318   // If there is only one terminator instruction, process it.
319   unsigned LastOpc = LastInst->getOpcode();
320   if (I == MBB.begin() ||
321       isPredicated(--I) || !isTerminatorInstr(I->getOpcode())) {
322     if (LastOpc == ARM::B || LastOpc == ARM::tB) {
323       TBB = LastInst->getOperand(0).getMachineBasicBlock();
324       return false;
325     }
326     if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {
327       // Block ends with fall-through condbranch.
328       TBB = LastInst->getOperand(0).getMachineBasicBlock();
329       Cond.push_back(LastInst->getOperand(1));
330       return false;
331     }
332     return true;  // Can't handle indirect branch.
333   }
334   
335   // Get the instruction before it if it is a terminator.
336   MachineInstr *SecondLastInst = I;
337   
338   // If there are three terminators, we don't know what sort of block this is.
339   if (SecondLastInst && I != MBB.begin() &&
340       !isPredicated(--I) && isTerminatorInstr(I->getOpcode()))
341     return true;
342   
343   // If the block ends with ARM::B/ARM::tB and a ARM::Bcc/ARM::tBcc, handle it.
344   unsigned SecondLastOpc = SecondLastInst->getOpcode();
345   if ((SecondLastOpc == ARM::Bcc && LastOpc == ARM::B) ||
346       (SecondLastOpc == ARM::tBcc && LastOpc == ARM::tB)) {
347     TBB =  SecondLastInst->getOperand(0).getMachineBasicBlock();
348     Cond.push_back(SecondLastInst->getOperand(1));
349     FBB = LastInst->getOperand(0).getMachineBasicBlock();
350     return false;
351   }
352   
353   // Otherwise, can't handle this.
354   return true;
355 }
356
357
358 unsigned ARMInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
359   MachineFunction &MF = *MBB.getParent();
360   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
361   int BOpc   = AFI->isThumbFunction() ? ARM::tB : ARM::B;
362   int BccOpc = AFI->isThumbFunction() ? ARM::tBcc : ARM::Bcc;
363
364   MachineBasicBlock::iterator I = MBB.end();
365   if (I == MBB.begin()) return 0;
366   --I;
367   if (I->getOpcode() != BOpc && I->getOpcode() != BccOpc)
368     return 0;
369   
370   // Remove the branch.
371   I->eraseFromParent();
372   
373   I = MBB.end();
374   
375   if (I == MBB.begin()) return 1;
376   --I;
377   if (I->getOpcode() != BccOpc)
378     return 1;
379   
380   // Remove the branch.
381   I->eraseFromParent();
382   return 2;
383 }
384
385 unsigned ARMInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
386                                 MachineBasicBlock *FBB,
387                                 const std::vector<MachineOperand> &Cond) const {
388   MachineFunction &MF = *MBB.getParent();
389   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
390   int BOpc   = AFI->isThumbFunction() ? ARM::tB : ARM::B;
391   int BccOpc = AFI->isThumbFunction() ? ARM::tBcc : ARM::Bcc;
392
393   // Shouldn't be a fall through.
394   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
395   assert((Cond.size() == 1 || Cond.size() == 0) &&
396          "ARM branch conditions have two components!");
397   
398   if (FBB == 0) {
399     if (Cond.empty()) // Unconditional branch?
400       BuildMI(&MBB, get(BOpc)).addMBB(TBB);
401     else
402       BuildMI(&MBB, get(BccOpc)).addMBB(TBB).addImm(Cond[0].getImm());
403     return 1;
404   }
405   
406   // Two-way conditional branch.
407   BuildMI(&MBB, get(BccOpc)).addMBB(TBB).addImm(Cond[0].getImm());
408   BuildMI(&MBB, get(BOpc)).addMBB(FBB);
409   return 2;
410 }
411
412 bool ARMInstrInfo::BlockHasNoFallThrough(MachineBasicBlock &MBB) const {
413   if (MBB.empty()) return false;
414   
415   switch (MBB.back().getOpcode()) {
416   case ARM::BX_RET:   // Return.
417   case ARM::LDM_RET:
418   case ARM::tBX_RET:
419   case ARM::tBX_RET_vararg:
420   case ARM::tPOP_RET:
421   case ARM::B:
422   case ARM::tB:       // Uncond branch.
423   case ARM::tBR_JTr:
424   case ARM::BR_JTr:   // Jumptable branch.
425   case ARM::BR_JTm:   // Jumptable branch through mem.
426   case ARM::BR_JTadd: // Jumptable branch add to pc.
427     return true;
428   default: return false;
429   }
430 }
431
432 bool ARMInstrInfo::
433 ReverseBranchCondition(std::vector<MachineOperand> &Cond) const {
434   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
435   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
436   return false;
437 }
438
439 bool ARMInstrInfo::PredicateInstruction(MachineInstr *MI,
440                                       std::vector<MachineOperand> &Cond) const {
441   unsigned Opc = MI->getOpcode();
442   if (Opc == ARM::B || Opc == ARM::tB) {
443     MI->setInstrDescriptor(get(Opc == ARM::B ? ARM::Bcc : ARM::tBcc));
444     MI->addImmOperand(Cond[0].getImmedValue());
445     return true;
446   }
447
448   MachineOperand *PMO = MI->findFirstPredOperand();
449   if (PMO) {
450     PMO->setImm(Cond[0].getImmedValue());
451     return true;
452   }
453   return false;
454 }
455
456
457 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
458 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
459                                 unsigned JTI) DISABLE_INLINE;
460 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
461                                 unsigned JTI) {
462   return JT[JTI].MBBs.size();
463 }
464
465 /// GetInstSize - Return the size of the specified MachineInstr.
466 ///
467 unsigned ARM::GetInstSize(MachineInstr *MI) {
468   MachineBasicBlock &MBB = *MI->getParent();
469   const MachineFunction *MF = MBB.getParent();
470   const TargetAsmInfo *TAI = MF->getTarget().getTargetAsmInfo();
471
472   // Basic size info comes from the TSFlags field.
473   const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
474   unsigned TSFlags = TID->TSFlags;
475   
476   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
477   default:
478     // If this machine instr is an inline asm, measure it.
479     if (MI->getOpcode() == ARM::INLINEASM)
480       return TAI->getInlineAsmLength(MI->getOperand(0).getSymbolName());
481     if (MI->getOpcode() == ARM::LABEL)
482       return 0;
483     assert(0 && "Unknown or unset size field for instr!");
484     break;
485   case ARMII::Size8Bytes: return 8;          // Arm instruction x 2.
486   case ARMII::Size4Bytes: return 4;          // Arm instruction.
487   case ARMII::Size2Bytes: return 2;          // Thumb instruction.
488   case ARMII::SizeSpecial: {
489     switch (MI->getOpcode()) {
490     case ARM::CONSTPOOL_ENTRY:
491       // If this machine instr is a constant pool entry, its size is recorded as
492       // operand #2.
493       return MI->getOperand(2).getImm();
494     case ARM::BR_JTr:
495     case ARM::BR_JTm:
496     case ARM::BR_JTadd:
497     case ARM::tBR_JTr: {
498       // These are jumptable branches, i.e. a branch followed by an inlined
499       // jumptable. The size is 4 + 4 * number of entries.
500       unsigned NumOps = TID->numOperands;
501       MachineOperand JTOP =
502         MI->getOperand(NumOps - ((TID->Flags & M_PREDICABLE) ? 3 : 2));
503       unsigned JTI = JTOP.getJumpTableIndex();
504       MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
505       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
506       assert(JTI < JT.size());
507       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
508       // 4 aligned. The assembler / linker may add 2 byte padding just before
509       // the JT entries.  The size does not include this padding; the
510       // constant islands pass does separate bookkeeping for it.
511       // FIXME: If we know the size of the function is less than (1 << 16) *2
512       // bytes, we can use 16-bit entries instead. Then there won't be an
513       // alignment issue.
514       return getNumJTEntries(JT, JTI) * 4 + 
515              (MI->getOpcode()==ARM::tBR_JTr ? 2 : 4);
516     }
517     default:
518       // Otherwise, pseudo-instruction sizes are zero.
519       return 0;
520     }
521   }
522   }
523 }
524
525 /// GetFunctionSize - Returns the size of the specified MachineFunction.
526 ///
527 unsigned ARM::GetFunctionSize(MachineFunction &MF) {
528   unsigned FnSize = 0;
529   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
530        MBBI != E; ++MBBI) {
531     MachineBasicBlock &MBB = *MBBI;
532     for (MachineBasicBlock::iterator I = MBB.begin(),E = MBB.end(); I != E; ++I)
533       FnSize += ARM::GetInstSize(I);
534   }
535   return FnSize;
536 }