- Remove calls to copyKillDeadInfo which is an N^2 function. Instead, propagate kill...
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the ARM implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMInstrInfo.h"
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMGenInstrInfo.inc"
18 #include "ARMMachineFunctionInfo.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Support/CommandLine.h"
26 using namespace llvm;
27
28 static cl::opt<bool> EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
29                                   cl::desc("Enable ARM 2-addr to 3-addr conv"));
30
31 static inline
32 const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
33   return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
34 }
35
36 static inline
37 const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
38   return MIB.addReg(0);
39 }
40
41 ARMInstrInfo::ARMInstrInfo(const ARMSubtarget &STI)
42   : TargetInstrInfoImpl(ARMInsts, array_lengthof(ARMInsts)),
43     RI(*this, STI) {
44 }
45
46 const TargetRegisterClass *ARMInstrInfo::getPointerRegClass() const {
47   return &ARM::GPRRegClass;
48 }
49
50 /// Return true if the instruction is a register to register move and
51 /// leave the source and dest operands in the passed parameters.
52 ///
53 bool ARMInstrInfo::isMoveInstr(const MachineInstr &MI,
54                                unsigned &SrcReg, unsigned &DstReg) const {
55   unsigned oc = MI.getOpcode();
56   switch (oc) {
57   default:
58     return false;
59   case ARM::FCPYS:
60   case ARM::FCPYD:
61     SrcReg = MI.getOperand(1).getReg();
62     DstReg = MI.getOperand(0).getReg();
63     return true;
64   case ARM::MOVr:
65   case ARM::tMOVr:
66     assert(MI.getDesc().getNumOperands() >= 2 &&
67            MI.getOperand(0).isRegister() &&
68            MI.getOperand(1).isRegister() &&
69            "Invalid ARM MOV instruction");
70     SrcReg = MI.getOperand(1).getReg();
71     DstReg = MI.getOperand(0).getReg();
72     return true;
73   }
74 }
75
76 unsigned ARMInstrInfo::isLoadFromStackSlot(MachineInstr *MI, int &FrameIndex) const{
77   switch (MI->getOpcode()) {
78   default: break;
79   case ARM::LDR:
80     if (MI->getOperand(1).isFrameIndex() &&
81         MI->getOperand(2).isRegister() &&
82         MI->getOperand(3).isImmediate() && 
83         MI->getOperand(2).getReg() == 0 &&
84         MI->getOperand(3).getImm() == 0) {
85       FrameIndex = MI->getOperand(1).getIndex();
86       return MI->getOperand(0).getReg();
87     }
88     break;
89   case ARM::FLDD:
90   case ARM::FLDS:
91     if (MI->getOperand(1).isFrameIndex() &&
92         MI->getOperand(2).isImmediate() && 
93         MI->getOperand(2).getImm() == 0) {
94       FrameIndex = MI->getOperand(1).getIndex();
95       return MI->getOperand(0).getReg();
96     }
97     break;
98   case ARM::tRestore:
99     if (MI->getOperand(1).isFrameIndex() &&
100         MI->getOperand(2).isImmediate() && 
101         MI->getOperand(2).getImm() == 0) {
102       FrameIndex = MI->getOperand(1).getIndex();
103       return MI->getOperand(0).getReg();
104     }
105     break;
106   }
107   return 0;
108 }
109
110 unsigned ARMInstrInfo::isStoreToStackSlot(MachineInstr *MI, int &FrameIndex) const {
111   switch (MI->getOpcode()) {
112   default: break;
113   case ARM::STR:
114     if (MI->getOperand(1).isFrameIndex() &&
115         MI->getOperand(2).isRegister() &&
116         MI->getOperand(3).isImmediate() && 
117         MI->getOperand(2).getReg() == 0 &&
118         MI->getOperand(3).getImm() == 0) {
119       FrameIndex = MI->getOperand(1).getIndex();
120       return MI->getOperand(0).getReg();
121     }
122     break;
123   case ARM::FSTD:
124   case ARM::FSTS:
125     if (MI->getOperand(1).isFrameIndex() &&
126         MI->getOperand(2).isImmediate() && 
127         MI->getOperand(2).getImm() == 0) {
128       FrameIndex = MI->getOperand(1).getIndex();
129       return MI->getOperand(0).getReg();
130     }
131     break;
132   case ARM::tSpill:
133     if (MI->getOperand(1).isFrameIndex() &&
134         MI->getOperand(2).isImmediate() && 
135         MI->getOperand(2).getImm() == 0) {
136       FrameIndex = MI->getOperand(1).getIndex();
137       return MI->getOperand(0).getReg();
138     }
139     break;
140   }
141   return 0;
142 }
143
144 void ARMInstrInfo::reMaterialize(MachineBasicBlock &MBB,
145                                  MachineBasicBlock::iterator I,
146                                  unsigned DestReg,
147                                  const MachineInstr *Orig) const {
148   if (Orig->getOpcode() == ARM::MOVi2pieces) {
149     RI.emitLoadConstPool(MBB, I, DestReg, Orig->getOperand(1).getImm(),
150                          Orig->getOperand(2).getImm(),
151                          Orig->getOperand(3).getReg(), this, false);
152     return;
153   }
154
155   MachineInstr *MI = Orig->clone();
156   MI->getOperand(0).setReg(DestReg);
157   MBB.insert(I, MI);
158 }
159
160 static unsigned getUnindexedOpcode(unsigned Opc) {
161   switch (Opc) {
162   default: break;
163   case ARM::LDR_PRE:
164   case ARM::LDR_POST:
165     return ARM::LDR;
166   case ARM::LDRH_PRE:
167   case ARM::LDRH_POST:
168     return ARM::LDRH;
169   case ARM::LDRB_PRE:
170   case ARM::LDRB_POST:
171     return ARM::LDRB;
172   case ARM::LDRSH_PRE:
173   case ARM::LDRSH_POST:
174     return ARM::LDRSH;
175   case ARM::LDRSB_PRE:
176   case ARM::LDRSB_POST:
177     return ARM::LDRSB;
178   case ARM::STR_PRE:
179   case ARM::STR_POST:
180     return ARM::STR;
181   case ARM::STRH_PRE:
182   case ARM::STRH_POST:
183     return ARM::STRH;
184   case ARM::STRB_PRE:
185   case ARM::STRB_POST:
186     return ARM::STRB;
187   }
188   return 0;
189 }
190
191 MachineInstr *
192 ARMInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
193                                     MachineBasicBlock::iterator &MBBI,
194                                     LiveVariables *LV) const {
195   if (!EnableARM3Addr)
196     return NULL;
197
198   MachineInstr *MI = MBBI;
199   unsigned TSFlags = MI->getDesc().TSFlags;
200   bool isPre = false;
201   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
202   default: return NULL;
203   case ARMII::IndexModePre:
204     isPre = true;
205     break;
206   case ARMII::IndexModePost:
207     break;
208   }
209
210   // Try spliting an indexed load / store to a un-indexed one plus an add/sub
211   // operation.
212   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
213   if (MemOpc == 0)
214     return NULL;
215
216   MachineInstr *UpdateMI = NULL;
217   MachineInstr *MemMI = NULL;
218   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
219   const TargetInstrDesc &TID = MI->getDesc();
220   unsigned NumOps = TID.getNumOperands();
221   bool isLoad = !TID.mayStore();
222   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
223   const MachineOperand &Base = MI->getOperand(2);
224   const MachineOperand &Offset = MI->getOperand(NumOps-3);
225   unsigned WBReg = WB.getReg();
226   unsigned BaseReg = Base.getReg();
227   unsigned OffReg = Offset.getReg();
228   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
229   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
230   switch (AddrMode) {
231   default:
232     assert(false && "Unknown indexed op!");
233     return NULL;
234   case ARMII::AddrMode2: {
235     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
236     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
237     if (OffReg == 0) {
238       int SOImmVal = ARM_AM::getSOImmVal(Amt);
239       if (SOImmVal == -1)
240         // Can't encode it in a so_imm operand. This transformation will
241         // add more than 1 instruction. Abandon!
242         return NULL;
243       UpdateMI = BuildMI(get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
244         .addReg(BaseReg).addImm(SOImmVal)
245         .addImm(Pred).addReg(0).addReg(0);
246     } else if (Amt != 0) {
247       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
248       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
249       UpdateMI = BuildMI(get(isSub ? ARM::SUBrs : ARM::ADDrs), WBReg)
250         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
251         .addImm(Pred).addReg(0).addReg(0);
252     } else 
253       UpdateMI = BuildMI(get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
254         .addReg(BaseReg).addReg(OffReg)
255         .addImm(Pred).addReg(0).addReg(0);
256     break;
257   }
258   case ARMII::AddrMode3 : {
259     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
260     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
261     if (OffReg == 0)
262       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
263       UpdateMI = BuildMI(get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
264         .addReg(BaseReg).addImm(Amt)
265         .addImm(Pred).addReg(0).addReg(0);
266     else
267       UpdateMI = BuildMI(get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
268         .addReg(BaseReg).addReg(OffReg)
269         .addImm(Pred).addReg(0).addReg(0);
270     break;
271   }
272   }
273
274   std::vector<MachineInstr*> NewMIs;
275   if (isPre) {
276     if (isLoad)
277       MemMI = BuildMI(get(MemOpc), MI->getOperand(0).getReg())
278         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
279     else
280       MemMI = BuildMI(get(MemOpc)).addReg(MI->getOperand(1).getReg())
281         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
282     NewMIs.push_back(MemMI);
283     NewMIs.push_back(UpdateMI);
284   } else {
285     if (isLoad)
286       MemMI = BuildMI(get(MemOpc), MI->getOperand(0).getReg())
287         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
288     else
289       MemMI = BuildMI(get(MemOpc)).addReg(MI->getOperand(1).getReg())
290         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
291     if (WB.isDead())
292       UpdateMI->getOperand(0).setIsDead();
293     NewMIs.push_back(UpdateMI);
294     NewMIs.push_back(MemMI);
295   }
296   
297   // Transfer LiveVariables states, kill / dead info.
298   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
299     MachineOperand &MO = MI->getOperand(i);
300     if (MO.isRegister() && MO.getReg() &&
301         TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
302       unsigned Reg = MO.getReg();
303       
304       if (LV) {
305         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
306         if (MO.isDef()) {
307           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
308           if (MO.isDead())
309             LV->addVirtualRegisterDead(Reg, NewMI);
310         }
311         if (MO.isUse() && MO.isKill()) {
312           for (unsigned j = 0; j < 2; ++j) {
313             // Look at the two new MI's in reverse order.
314             MachineInstr *NewMI = NewMIs[j];
315             if (!NewMI->readsRegister(Reg))
316               continue;
317             LV->addVirtualRegisterKilled(Reg, NewMI);
318             if (VI.removeKill(MI))
319               VI.Kills.push_back(NewMI);
320             break;
321           }
322         }
323       }
324     }
325   }
326
327   MFI->insert(MBBI, NewMIs[1]);
328   MFI->insert(MBBI, NewMIs[0]);
329   return NewMIs[0];
330 }
331
332 // Branch analysis.
333 bool ARMInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
334                                  MachineBasicBlock *&FBB,
335                                  std::vector<MachineOperand> &Cond) const {
336   // If the block has no terminators, it just falls into the block after it.
337   MachineBasicBlock::iterator I = MBB.end();
338   if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
339     return false;
340   
341   // Get the last instruction in the block.
342   MachineInstr *LastInst = I;
343   
344   // If there is only one terminator instruction, process it.
345   unsigned LastOpc = LastInst->getOpcode();
346   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
347     if (LastOpc == ARM::B || LastOpc == ARM::tB) {
348       TBB = LastInst->getOperand(0).getMBB();
349       return false;
350     }
351     if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {
352       // Block ends with fall-through condbranch.
353       TBB = LastInst->getOperand(0).getMBB();
354       Cond.push_back(LastInst->getOperand(1));
355       Cond.push_back(LastInst->getOperand(2));
356       return false;
357     }
358     return true;  // Can't handle indirect branch.
359   }
360   
361   // Get the instruction before it if it is a terminator.
362   MachineInstr *SecondLastInst = I;
363   
364   // If there are three terminators, we don't know what sort of block this is.
365   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
366     return true;
367   
368   // If the block ends with ARM::B/ARM::tB and a ARM::Bcc/ARM::tBcc, handle it.
369   unsigned SecondLastOpc = SecondLastInst->getOpcode();
370   if ((SecondLastOpc == ARM::Bcc && LastOpc == ARM::B) ||
371       (SecondLastOpc == ARM::tBcc && LastOpc == ARM::tB)) {
372     TBB =  SecondLastInst->getOperand(0).getMBB();
373     Cond.push_back(SecondLastInst->getOperand(1));
374     Cond.push_back(SecondLastInst->getOperand(2));
375     FBB = LastInst->getOperand(0).getMBB();
376     return false;
377   }
378   
379   // If the block ends with two unconditional branches, handle it.  The second 
380   // one is not executed, so remove it.
381   if ((SecondLastOpc == ARM::B || SecondLastOpc==ARM::tB) &&
382       (LastOpc == ARM::B || LastOpc == ARM::tB)) {
383     TBB = SecondLastInst->getOperand(0).getMBB();
384     I = LastInst;
385     I->eraseFromParent();
386     return false;
387   }
388
389   // Likewise if it ends with a branch table followed by an unconditional branch.
390   // The branch folder can create these, and we must get rid of them for
391   // correctness of Thumb constant islands.
392   if ((SecondLastOpc == ARM::BR_JTr || SecondLastOpc==ARM::BR_JTm ||
393        SecondLastOpc == ARM::BR_JTadd || SecondLastOpc==ARM::tBR_JTr) &&
394       (LastOpc == ARM::B || LastOpc == ARM::tB)) {
395     I = LastInst;
396     I->eraseFromParent();
397     return true;
398   } 
399
400   // Otherwise, can't handle this.
401   return true;
402 }
403
404
405 unsigned ARMInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
406   MachineFunction &MF = *MBB.getParent();
407   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
408   int BOpc   = AFI->isThumbFunction() ? ARM::tB : ARM::B;
409   int BccOpc = AFI->isThumbFunction() ? ARM::tBcc : ARM::Bcc;
410
411   MachineBasicBlock::iterator I = MBB.end();
412   if (I == MBB.begin()) return 0;
413   --I;
414   if (I->getOpcode() != BOpc && I->getOpcode() != BccOpc)
415     return 0;
416   
417   // Remove the branch.
418   I->eraseFromParent();
419   
420   I = MBB.end();
421   
422   if (I == MBB.begin()) return 1;
423   --I;
424   if (I->getOpcode() != BccOpc)
425     return 1;
426   
427   // Remove the branch.
428   I->eraseFromParent();
429   return 2;
430 }
431
432 unsigned ARMInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
433                                 MachineBasicBlock *FBB,
434                                 const std::vector<MachineOperand> &Cond) const {
435   MachineFunction &MF = *MBB.getParent();
436   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
437   int BOpc   = AFI->isThumbFunction() ? ARM::tB : ARM::B;
438   int BccOpc = AFI->isThumbFunction() ? ARM::tBcc : ARM::Bcc;
439
440   // Shouldn't be a fall through.
441   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
442   assert((Cond.size() == 2 || Cond.size() == 0) &&
443          "ARM branch conditions have two components!");
444   
445   if (FBB == 0) {
446     if (Cond.empty()) // Unconditional branch?
447       BuildMI(&MBB, get(BOpc)).addMBB(TBB);
448     else
449       BuildMI(&MBB, get(BccOpc)).addMBB(TBB)
450         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
451     return 1;
452   }
453   
454   // Two-way conditional branch.
455   BuildMI(&MBB, get(BccOpc)).addMBB(TBB)
456     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
457   BuildMI(&MBB, get(BOpc)).addMBB(FBB);
458   return 2;
459 }
460
461 void ARMInstrInfo::copyRegToReg(MachineBasicBlock &MBB,
462                                    MachineBasicBlock::iterator I,
463                                    unsigned DestReg, unsigned SrcReg,
464                                    const TargetRegisterClass *DestRC,
465                                    const TargetRegisterClass *SrcRC) const {
466   if (DestRC != SrcRC) {
467     cerr << "Not yet supported!";
468     abort();
469   }
470
471   if (DestRC == ARM::GPRRegisterClass) {
472     MachineFunction &MF = *MBB.getParent();
473     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
474     if (AFI->isThumbFunction())
475       BuildMI(MBB, I, get(ARM::tMOVr), DestReg).addReg(SrcReg);
476     else
477       AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, get(ARM::MOVr), DestReg)
478                                   .addReg(SrcReg)));
479   } else if (DestRC == ARM::SPRRegisterClass)
480     AddDefaultPred(BuildMI(MBB, I, get(ARM::FCPYS), DestReg)
481                    .addReg(SrcReg));
482   else if (DestRC == ARM::DPRRegisterClass)
483     AddDefaultPred(BuildMI(MBB, I, get(ARM::FCPYD), DestReg)
484                    .addReg(SrcReg));
485   else
486     abort();
487 }
488
489 static const MachineInstrBuilder &ARMInstrAddOperand(MachineInstrBuilder &MIB,
490                                                      MachineOperand &MO) {
491   if (MO.isRegister())
492     MIB = MIB.addReg(MO.getReg(), MO.isDef(), MO.isImplicit());
493   else if (MO.isImmediate())
494     MIB = MIB.addImm(MO.getImm());
495   else if (MO.isFrameIndex())
496     MIB = MIB.addFrameIndex(MO.getIndex());
497   else
498     assert(0 && "Unknown operand for ARMInstrAddOperand!");
499
500   return MIB;
501 }
502
503 void ARMInstrInfo::
504 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
505                     unsigned SrcReg, bool isKill, int FI,
506                     const TargetRegisterClass *RC) const {
507   if (RC == ARM::GPRRegisterClass) {
508     MachineFunction &MF = *MBB.getParent();
509     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
510     if (AFI->isThumbFunction())
511       BuildMI(MBB, I, get(ARM::tSpill)).addReg(SrcReg, false, false, isKill)
512         .addFrameIndex(FI).addImm(0);
513     else
514       AddDefaultPred(BuildMI(MBB, I, get(ARM::STR))
515                      .addReg(SrcReg, false, false, isKill)
516                      .addFrameIndex(FI).addReg(0).addImm(0));
517   } else if (RC == ARM::DPRRegisterClass) {
518     AddDefaultPred(BuildMI(MBB, I, get(ARM::FSTD))
519                    .addReg(SrcReg, false, false, isKill)
520                    .addFrameIndex(FI).addImm(0));
521   } else {
522     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
523     AddDefaultPred(BuildMI(MBB, I, get(ARM::FSTS))
524                    .addReg(SrcReg, false, false, isKill)
525                    .addFrameIndex(FI).addImm(0));
526   }
527 }
528
529 void ARMInstrInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
530                                      bool isKill,
531                                      SmallVectorImpl<MachineOperand> &Addr,
532                                      const TargetRegisterClass *RC,
533                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
534   unsigned Opc = 0;
535   if (RC == ARM::GPRRegisterClass) {
536     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
537     if (AFI->isThumbFunction()) {
538       Opc = Addr[0].isFrameIndex() ? ARM::tSpill : ARM::tSTR;
539       MachineInstrBuilder MIB = 
540         BuildMI(get(Opc)).addReg(SrcReg, false, false, isKill);
541       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
542         MIB = ARMInstrAddOperand(MIB, Addr[i]);
543       NewMIs.push_back(MIB);
544       return;
545     }
546     Opc = ARM::STR;
547   } else if (RC == ARM::DPRRegisterClass) {
548     Opc = ARM::FSTD;
549   } else {
550     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
551     Opc = ARM::FSTS;
552   }
553
554   MachineInstrBuilder MIB = 
555     BuildMI(get(Opc)).addReg(SrcReg, false, false, isKill);
556   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
557     MIB = ARMInstrAddOperand(MIB, Addr[i]);
558   AddDefaultPred(MIB);
559   NewMIs.push_back(MIB);
560   return;
561 }
562
563 void ARMInstrInfo::
564 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
565                      unsigned DestReg, int FI,
566                      const TargetRegisterClass *RC) const {
567   if (RC == ARM::GPRRegisterClass) {
568     MachineFunction &MF = *MBB.getParent();
569     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
570     if (AFI->isThumbFunction())
571       BuildMI(MBB, I, get(ARM::tRestore), DestReg)
572         .addFrameIndex(FI).addImm(0);
573     else
574       AddDefaultPred(BuildMI(MBB, I, get(ARM::LDR), DestReg)
575                      .addFrameIndex(FI).addReg(0).addImm(0));
576   } else if (RC == ARM::DPRRegisterClass) {
577     AddDefaultPred(BuildMI(MBB, I, get(ARM::FLDD), DestReg)
578                    .addFrameIndex(FI).addImm(0));
579   } else {
580     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
581     AddDefaultPred(BuildMI(MBB, I, get(ARM::FLDS), DestReg)
582                    .addFrameIndex(FI).addImm(0));
583   }
584 }
585
586 void ARMInstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
587                                       SmallVectorImpl<MachineOperand> &Addr,
588                                       const TargetRegisterClass *RC,
589                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
590   unsigned Opc = 0;
591   if (RC == ARM::GPRRegisterClass) {
592     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
593     if (AFI->isThumbFunction()) {
594       Opc = Addr[0].isFrameIndex() ? ARM::tRestore : ARM::tLDR;
595       MachineInstrBuilder MIB = BuildMI(get(Opc), DestReg);
596       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
597         MIB = ARMInstrAddOperand(MIB, Addr[i]);
598       NewMIs.push_back(MIB);
599       return;
600     }
601     Opc = ARM::LDR;
602   } else if (RC == ARM::DPRRegisterClass) {
603     Opc = ARM::FLDD;
604   } else {
605     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
606     Opc = ARM::FLDS;
607   }
608
609   MachineInstrBuilder MIB =  BuildMI(get(Opc), DestReg);
610   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
611     MIB = ARMInstrAddOperand(MIB, Addr[i]);
612   AddDefaultPred(MIB);
613   NewMIs.push_back(MIB);
614   return;
615 }
616
617 bool ARMInstrInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
618                                                 MachineBasicBlock::iterator MI,
619                                 const std::vector<CalleeSavedInfo> &CSI) const {
620   MachineFunction &MF = *MBB.getParent();
621   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
622   if (!AFI->isThumbFunction() || CSI.empty())
623     return false;
624
625   MachineInstrBuilder MIB = BuildMI(MBB, MI, get(ARM::tPUSH));
626   for (unsigned i = CSI.size(); i != 0; --i) {
627     unsigned Reg = CSI[i-1].getReg();
628     // Add the callee-saved register as live-in. It's killed at the spill.
629     MBB.addLiveIn(Reg);
630     MIB.addReg(Reg, false/*isDef*/,false/*isImp*/,true/*isKill*/);
631   }
632   return true;
633 }
634
635 bool ARMInstrInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
636                                                  MachineBasicBlock::iterator MI,
637                                 const std::vector<CalleeSavedInfo> &CSI) const {
638   MachineFunction &MF = *MBB.getParent();
639   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
640   if (!AFI->isThumbFunction() || CSI.empty())
641     return false;
642
643   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
644   MachineInstr *PopMI = new MachineInstr(get(ARM::tPOP));
645   MBB.insert(MI, PopMI);
646   for (unsigned i = CSI.size(); i != 0; --i) {
647     unsigned Reg = CSI[i-1].getReg();
648     if (Reg == ARM::LR) {
649       // Special epilogue for vararg functions. See emitEpilogue
650       if (isVarArg)
651         continue;
652       Reg = ARM::PC;
653       PopMI->setDesc(get(ARM::tPOP_RET));
654       MBB.erase(MI);
655     }
656     PopMI->addOperand(MachineOperand::CreateReg(Reg, true));
657   }
658   return true;
659 }
660
661 MachineInstr *ARMInstrInfo::foldMemoryOperand(MachineFunction &MF,
662                                               MachineInstr *MI,
663                                               SmallVectorImpl<unsigned> &Ops,
664                                               int FI) const {
665   if (Ops.size() != 1) return NULL;
666
667   unsigned OpNum = Ops[0];
668   unsigned Opc = MI->getOpcode();
669   MachineInstr *NewMI = NULL;
670   switch (Opc) {
671   default: break;
672   case ARM::MOVr: {
673     if (MI->getOperand(4).getReg() == ARM::CPSR)
674       // If it is updating CPSR, then it cannot be foled.
675       break;
676     unsigned Pred = MI->getOperand(2).getImm();
677     unsigned PredReg = MI->getOperand(3).getReg();
678     if (OpNum == 0) { // move -> store
679       unsigned SrcReg = MI->getOperand(1).getReg();
680       bool isKill = MI->getOperand(1).isKill();
681       NewMI = BuildMI(get(ARM::STR)).addReg(SrcReg, false, false, isKill)
682         .addFrameIndex(FI).addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
683     } else {          // move -> load
684       unsigned DstReg = MI->getOperand(0).getReg();
685       bool isDead = MI->getOperand(0).isDead();
686       NewMI = BuildMI(get(ARM::LDR)).addReg(DstReg, true, false, false, isDead)
687         .addFrameIndex(FI).addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
688     }
689     break;
690   }
691   case ARM::tMOVr: {
692     if (OpNum == 0) { // move -> store
693       unsigned SrcReg = MI->getOperand(1).getReg();
694       bool isKill = MI->getOperand(1).isKill();
695       if (RI.isPhysicalRegister(SrcReg) && !RI.isLowRegister(SrcReg))
696         // tSpill cannot take a high register operand.
697         break;
698       NewMI = BuildMI(get(ARM::tSpill)).addReg(SrcReg, false, false, isKill)
699         .addFrameIndex(FI).addImm(0);
700     } else {          // move -> load
701       unsigned DstReg = MI->getOperand(0).getReg();
702       if (RI.isPhysicalRegister(DstReg) && !RI.isLowRegister(DstReg))
703         // tRestore cannot target a high register operand.
704         break;
705       bool isDead = MI->getOperand(0).isDead();
706       NewMI = BuildMI(get(ARM::tRestore))
707         .addReg(DstReg, true, false, false, isDead)
708         .addFrameIndex(FI).addImm(0);
709     }
710     break;
711   }
712   case ARM::FCPYS: {
713     unsigned Pred = MI->getOperand(2).getImm();
714     unsigned PredReg = MI->getOperand(3).getReg();
715     if (OpNum == 0) { // move -> store
716       unsigned SrcReg = MI->getOperand(1).getReg();
717       NewMI = BuildMI(get(ARM::FSTS)).addReg(SrcReg).addFrameIndex(FI)
718         .addImm(0).addImm(Pred).addReg(PredReg);
719     } else {          // move -> load
720       unsigned DstReg = MI->getOperand(0).getReg();
721       NewMI = BuildMI(get(ARM::FLDS), DstReg).addFrameIndex(FI)
722         .addImm(0).addImm(Pred).addReg(PredReg);
723     }
724     break;
725   }
726   case ARM::FCPYD: {
727     unsigned Pred = MI->getOperand(2).getImm();
728     unsigned PredReg = MI->getOperand(3).getReg();
729     if (OpNum == 0) { // move -> store
730       unsigned SrcReg = MI->getOperand(1).getReg();
731       bool isKill = MI->getOperand(1).isKill();
732       NewMI = BuildMI(get(ARM::FSTD)).addReg(SrcReg, false, false, isKill)
733         .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
734     } else {          // move -> load
735       unsigned DstReg = MI->getOperand(0).getReg();
736       bool isDead = MI->getOperand(0).isDead();
737       NewMI = BuildMI(get(ARM::FLDD)).addReg(DstReg, true, false, false, isDead)
738         .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
739     }
740     break;
741   }
742   }
743
744   return NewMI;
745 }
746
747 bool ARMInstrInfo::canFoldMemoryOperand(MachineInstr *MI,
748                                         SmallVectorImpl<unsigned> &Ops) const {
749   if (Ops.size() != 1) return false;
750
751   unsigned OpNum = Ops[0];
752   unsigned Opc = MI->getOpcode();
753   switch (Opc) {
754   default: break;
755   case ARM::MOVr:
756     // If it is updating CPSR, then it cannot be foled.
757     return MI->getOperand(4).getReg() != ARM::CPSR;
758   case ARM::tMOVr: {
759     if (OpNum == 0) { // move -> store
760       unsigned SrcReg = MI->getOperand(1).getReg();
761       if (RI.isPhysicalRegister(SrcReg) && !RI.isLowRegister(SrcReg))
762         // tSpill cannot take a high register operand.
763         return false;
764     } else {          // move -> load
765       unsigned DstReg = MI->getOperand(0).getReg();
766       if (RI.isPhysicalRegister(DstReg) && !RI.isLowRegister(DstReg))
767         // tRestore cannot target a high register operand.
768         return false;
769     }
770     return true;
771   }
772   case ARM::FCPYS:
773   case ARM::FCPYD:
774     return true;
775   }
776
777   return false;
778 }
779
780 bool ARMInstrInfo::BlockHasNoFallThrough(MachineBasicBlock &MBB) const {
781   if (MBB.empty()) return false;
782   
783   switch (MBB.back().getOpcode()) {
784   case ARM::BX_RET:   // Return.
785   case ARM::LDM_RET:
786   case ARM::tBX_RET:
787   case ARM::tBX_RET_vararg:
788   case ARM::tPOP_RET:
789   case ARM::B:
790   case ARM::tB:       // Uncond branch.
791   case ARM::tBR_JTr:
792   case ARM::BR_JTr:   // Jumptable branch.
793   case ARM::BR_JTm:   // Jumptable branch through mem.
794   case ARM::BR_JTadd: // Jumptable branch add to pc.
795     return true;
796   default: return false;
797   }
798 }
799
800 bool ARMInstrInfo::
801 ReverseBranchCondition(std::vector<MachineOperand> &Cond) const {
802   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
803   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
804   return false;
805 }
806
807 bool ARMInstrInfo::isPredicated(const MachineInstr *MI) const {
808   int PIdx = MI->findFirstPredOperandIdx();
809   return PIdx != -1 && MI->getOperand(PIdx).getImm() != ARMCC::AL;
810 }
811
812 bool ARMInstrInfo::PredicateInstruction(MachineInstr *MI,
813                                 const std::vector<MachineOperand> &Pred) const {
814   unsigned Opc = MI->getOpcode();
815   if (Opc == ARM::B || Opc == ARM::tB) {
816     MI->setDesc(get(Opc == ARM::B ? ARM::Bcc : ARM::tBcc));
817     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
818     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
819     return true;
820   }
821
822   int PIdx = MI->findFirstPredOperandIdx();
823   if (PIdx != -1) {
824     MachineOperand &PMO = MI->getOperand(PIdx);
825     PMO.setImm(Pred[0].getImm());
826     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
827     return true;
828   }
829   return false;
830 }
831
832 bool
833 ARMInstrInfo::SubsumesPredicate(const std::vector<MachineOperand> &Pred1,
834                                 const std::vector<MachineOperand> &Pred2) const{
835   if (Pred1.size() > 2 || Pred2.size() > 2)
836     return false;
837
838   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
839   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
840   if (CC1 == CC2)
841     return true;
842
843   switch (CC1) {
844   default:
845     return false;
846   case ARMCC::AL:
847     return true;
848   case ARMCC::HS:
849     return CC2 == ARMCC::HI;
850   case ARMCC::LS:
851     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
852   case ARMCC::GE:
853     return CC2 == ARMCC::GT;
854   case ARMCC::LE:
855     return CC2 == ARMCC::LT;
856   }
857 }
858
859 bool ARMInstrInfo::DefinesPredicate(MachineInstr *MI,
860                                     std::vector<MachineOperand> &Pred) const {
861   const TargetInstrDesc &TID = MI->getDesc();
862   if (!TID.getImplicitDefs() && !TID.hasOptionalDef())
863     return false;
864
865   bool Found = false;
866   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
867     const MachineOperand &MO = MI->getOperand(i);
868     if (MO.isRegister() && MO.getReg() == ARM::CPSR) {
869       Pred.push_back(MO);
870       Found = true;
871     }
872   }
873
874   return Found;
875 }
876
877
878 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
879 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
880                                 unsigned JTI) DISABLE_INLINE;
881 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
882                                 unsigned JTI) {
883   return JT[JTI].MBBs.size();
884 }
885
886 /// GetInstSize - Return the size of the specified MachineInstr.
887 ///
888 unsigned ARMInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
889   const MachineBasicBlock &MBB = *MI->getParent();
890   const MachineFunction *MF = MBB.getParent();
891   const TargetAsmInfo *TAI = MF->getTarget().getTargetAsmInfo();
892
893   // Basic size info comes from the TSFlags field.
894   const TargetInstrDesc &TID = MI->getDesc();
895   unsigned TSFlags = TID.TSFlags;
896   
897   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
898   default:
899     // If this machine instr is an inline asm, measure it.
900     if (MI->getOpcode() == ARM::INLINEASM)
901       return TAI->getInlineAsmLength(MI->getOperand(0).getSymbolName());
902     if (MI->isLabel())
903       return 0;
904     if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
905       return 0;
906     assert(0 && "Unknown or unset size field for instr!");
907     break;
908   case ARMII::Size8Bytes: return 8;          // Arm instruction x 2.
909   case ARMII::Size4Bytes: return 4;          // Arm instruction.
910   case ARMII::Size2Bytes: return 2;          // Thumb instruction.
911   case ARMII::SizeSpecial: {
912     switch (MI->getOpcode()) {
913     case ARM::CONSTPOOL_ENTRY:
914       // If this machine instr is a constant pool entry, its size is recorded as
915       // operand #2.
916       return MI->getOperand(2).getImm();
917     case ARM::BR_JTr:
918     case ARM::BR_JTm:
919     case ARM::BR_JTadd:
920     case ARM::tBR_JTr: {
921       // These are jumptable branches, i.e. a branch followed by an inlined
922       // jumptable. The size is 4 + 4 * number of entries.
923       unsigned NumOps = TID.getNumOperands();
924       MachineOperand JTOP =
925         MI->getOperand(NumOps - (TID.isPredicable() ? 3 : 2));
926       unsigned JTI = JTOP.getIndex();
927       MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
928       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
929       assert(JTI < JT.size());
930       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
931       // 4 aligned. The assembler / linker may add 2 byte padding just before
932       // the JT entries.  The size does not include this padding; the
933       // constant islands pass does separate bookkeeping for it.
934       // FIXME: If we know the size of the function is less than (1 << 16) *2
935       // bytes, we can use 16-bit entries instead. Then there won't be an
936       // alignment issue.
937       return getNumJTEntries(JT, JTI) * 4 + 
938              (MI->getOpcode()==ARM::tBR_JTr ? 2 : 4);
939     }
940     default:
941       // Otherwise, pseudo-instruction sizes are zero.
942       return 0;
943     }
944   }
945   }
946   return 0; // Not reached
947 }