Revert r145971: "Use conservative size estimate for tBR_JTr."
[oota-llvm.git] / lib / Target / ARM / ARMBaseInstrInfo.cpp
1 //===- ARMBaseInstrInfo.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 Base ARM implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMBaseInstrInfo.h"
15 #include "ARM.h"
16 #include "ARMConstantPoolValue.h"
17 #include "ARMHazardRecognizer.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMRegisterInfo.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGNodes.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/Support/BranchProbability.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/ADT/STLExtras.h"
38
39 #define GET_INSTRINFO_CTOR
40 #include "ARMGenInstrInfo.inc"
41
42 using namespace llvm;
43
44 static cl::opt<bool>
45 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
46                cl::desc("Enable ARM 2-addr to 3-addr conv"));
47
48 static cl::opt<bool>
49 WidenVMOVS("widen-vmovs", cl::Hidden, cl::init(true),
50            cl::desc("Widen ARM vmovs to vmovd when possible"));
51
52 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
53 struct ARM_MLxEntry {
54   unsigned MLxOpc;     // MLA / MLS opcode
55   unsigned MulOpc;     // Expanded multiplication opcode
56   unsigned AddSubOpc;  // Expanded add / sub opcode
57   bool NegAcc;         // True if the acc is negated before the add / sub.
58   bool HasLane;        // True if instruction has an extra "lane" operand.
59 };
60
61 static const ARM_MLxEntry ARM_MLxTable[] = {
62   // MLxOpc,          MulOpc,           AddSubOpc,       NegAcc, HasLane
63   // fp scalar ops
64   { ARM::VMLAS,       ARM::VMULS,       ARM::VADDS,      false,  false },
65   { ARM::VMLSS,       ARM::VMULS,       ARM::VSUBS,      false,  false },
66   { ARM::VMLAD,       ARM::VMULD,       ARM::VADDD,      false,  false },
67   { ARM::VMLSD,       ARM::VMULD,       ARM::VSUBD,      false,  false },
68   { ARM::VNMLAS,      ARM::VNMULS,      ARM::VSUBS,      true,   false },
69   { ARM::VNMLSS,      ARM::VMULS,       ARM::VSUBS,      true,   false },
70   { ARM::VNMLAD,      ARM::VNMULD,      ARM::VSUBD,      true,   false },
71   { ARM::VNMLSD,      ARM::VMULD,       ARM::VSUBD,      true,   false },
72
73   // fp SIMD ops
74   { ARM::VMLAfd,      ARM::VMULfd,      ARM::VADDfd,     false,  false },
75   { ARM::VMLSfd,      ARM::VMULfd,      ARM::VSUBfd,     false,  false },
76   { ARM::VMLAfq,      ARM::VMULfq,      ARM::VADDfq,     false,  false },
77   { ARM::VMLSfq,      ARM::VMULfq,      ARM::VSUBfq,     false,  false },
78   { ARM::VMLAslfd,    ARM::VMULslfd,    ARM::VADDfd,     false,  true  },
79   { ARM::VMLSslfd,    ARM::VMULslfd,    ARM::VSUBfd,     false,  true  },
80   { ARM::VMLAslfq,    ARM::VMULslfq,    ARM::VADDfq,     false,  true  },
81   { ARM::VMLSslfq,    ARM::VMULslfq,    ARM::VSUBfq,     false,  true  },
82 };
83
84 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
85   : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
86     Subtarget(STI) {
87   for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
88     if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
89       assert(false && "Duplicated entries?");
90     MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
91     MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
92   }
93 }
94
95 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
96 // currently defaults to no prepass hazard recognizer.
97 ScheduleHazardRecognizer *ARMBaseInstrInfo::
98 CreateTargetHazardRecognizer(const TargetMachine *TM,
99                              const ScheduleDAG *DAG) const {
100   if (usePreRAHazardRecognizer()) {
101     const InstrItineraryData *II = TM->getInstrItineraryData();
102     return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
103   }
104   return TargetInstrInfoImpl::CreateTargetHazardRecognizer(TM, DAG);
105 }
106
107 ScheduleHazardRecognizer *ARMBaseInstrInfo::
108 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
109                                    const ScheduleDAG *DAG) const {
110   if (Subtarget.isThumb2() || Subtarget.hasVFP2())
111     return (ScheduleHazardRecognizer *)
112       new ARMHazardRecognizer(II, *this, getRegisterInfo(), Subtarget, DAG);
113   return TargetInstrInfoImpl::CreateTargetPostRAHazardRecognizer(II, DAG);
114 }
115
116 MachineInstr *
117 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
118                                         MachineBasicBlock::iterator &MBBI,
119                                         LiveVariables *LV) const {
120   // FIXME: Thumb2 support.
121
122   if (!EnableARM3Addr)
123     return NULL;
124
125   MachineInstr *MI = MBBI;
126   MachineFunction &MF = *MI->getParent()->getParent();
127   uint64_t TSFlags = MI->getDesc().TSFlags;
128   bool isPre = false;
129   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
130   default: return NULL;
131   case ARMII::IndexModePre:
132     isPre = true;
133     break;
134   case ARMII::IndexModePost:
135     break;
136   }
137
138   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
139   // operation.
140   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
141   if (MemOpc == 0)
142     return NULL;
143
144   MachineInstr *UpdateMI = NULL;
145   MachineInstr *MemMI = NULL;
146   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
147   const MCInstrDesc &MCID = MI->getDesc();
148   unsigned NumOps = MCID.getNumOperands();
149   bool isLoad = !MCID.mayStore();
150   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
151   const MachineOperand &Base = MI->getOperand(2);
152   const MachineOperand &Offset = MI->getOperand(NumOps-3);
153   unsigned WBReg = WB.getReg();
154   unsigned BaseReg = Base.getReg();
155   unsigned OffReg = Offset.getReg();
156   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
157   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
158   switch (AddrMode) {
159   default:
160     assert(false && "Unknown indexed op!");
161     return NULL;
162   case ARMII::AddrMode2: {
163     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
164     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
165     if (OffReg == 0) {
166       if (ARM_AM::getSOImmVal(Amt) == -1)
167         // Can't encode it in a so_imm operand. This transformation will
168         // add more than 1 instruction. Abandon!
169         return NULL;
170       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
171                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
172         .addReg(BaseReg).addImm(Amt)
173         .addImm(Pred).addReg(0).addReg(0);
174     } else if (Amt != 0) {
175       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
176       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
177       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
178                          get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
179         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
180         .addImm(Pred).addReg(0).addReg(0);
181     } else
182       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
183                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
184         .addReg(BaseReg).addReg(OffReg)
185         .addImm(Pred).addReg(0).addReg(0);
186     break;
187   }
188   case ARMII::AddrMode3 : {
189     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
190     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
191     if (OffReg == 0)
192       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
193       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
194                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
195         .addReg(BaseReg).addImm(Amt)
196         .addImm(Pred).addReg(0).addReg(0);
197     else
198       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
199                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
200         .addReg(BaseReg).addReg(OffReg)
201         .addImm(Pred).addReg(0).addReg(0);
202     break;
203   }
204   }
205
206   std::vector<MachineInstr*> NewMIs;
207   if (isPre) {
208     if (isLoad)
209       MemMI = BuildMI(MF, MI->getDebugLoc(),
210                       get(MemOpc), MI->getOperand(0).getReg())
211         .addReg(WBReg).addImm(0).addImm(Pred);
212     else
213       MemMI = BuildMI(MF, MI->getDebugLoc(),
214                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
215         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
216     NewMIs.push_back(MemMI);
217     NewMIs.push_back(UpdateMI);
218   } else {
219     if (isLoad)
220       MemMI = BuildMI(MF, MI->getDebugLoc(),
221                       get(MemOpc), MI->getOperand(0).getReg())
222         .addReg(BaseReg).addImm(0).addImm(Pred);
223     else
224       MemMI = BuildMI(MF, MI->getDebugLoc(),
225                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
226         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
227     if (WB.isDead())
228       UpdateMI->getOperand(0).setIsDead();
229     NewMIs.push_back(UpdateMI);
230     NewMIs.push_back(MemMI);
231   }
232
233   // Transfer LiveVariables states, kill / dead info.
234   if (LV) {
235     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
236       MachineOperand &MO = MI->getOperand(i);
237       if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
238         unsigned Reg = MO.getReg();
239
240         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
241         if (MO.isDef()) {
242           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
243           if (MO.isDead())
244             LV->addVirtualRegisterDead(Reg, NewMI);
245         }
246         if (MO.isUse() && MO.isKill()) {
247           for (unsigned j = 0; j < 2; ++j) {
248             // Look at the two new MI's in reverse order.
249             MachineInstr *NewMI = NewMIs[j];
250             if (!NewMI->readsRegister(Reg))
251               continue;
252             LV->addVirtualRegisterKilled(Reg, NewMI);
253             if (VI.removeKill(MI))
254               VI.Kills.push_back(NewMI);
255             break;
256           }
257         }
258       }
259     }
260   }
261
262   MFI->insert(MBBI, NewMIs[1]);
263   MFI->insert(MBBI, NewMIs[0]);
264   return NewMIs[0];
265 }
266
267 // Branch analysis.
268 bool
269 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
270                                 MachineBasicBlock *&FBB,
271                                 SmallVectorImpl<MachineOperand> &Cond,
272                                 bool AllowModify) const {
273   // If the block has no terminators, it just falls into the block after it.
274   MachineBasicBlock::iterator I = MBB.end();
275   if (I == MBB.begin())
276     return false;
277   --I;
278   while (I->isDebugValue()) {
279     if (I == MBB.begin())
280       return false;
281     --I;
282   }
283   if (!isUnpredicatedTerminator(I))
284     return false;
285
286   // Get the last instruction in the block.
287   MachineInstr *LastInst = I;
288
289   // If there is only one terminator instruction, process it.
290   unsigned LastOpc = LastInst->getOpcode();
291   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
292     if (isUncondBranchOpcode(LastOpc)) {
293       TBB = LastInst->getOperand(0).getMBB();
294       return false;
295     }
296     if (isCondBranchOpcode(LastOpc)) {
297       // Block ends with fall-through condbranch.
298       TBB = LastInst->getOperand(0).getMBB();
299       Cond.push_back(LastInst->getOperand(1));
300       Cond.push_back(LastInst->getOperand(2));
301       return false;
302     }
303     return true;  // Can't handle indirect branch.
304   }
305
306   // Get the instruction before it if it is a terminator.
307   MachineInstr *SecondLastInst = I;
308   unsigned SecondLastOpc = SecondLastInst->getOpcode();
309
310   // If AllowModify is true and the block ends with two or more unconditional
311   // branches, delete all but the first unconditional branch.
312   if (AllowModify && isUncondBranchOpcode(LastOpc)) {
313     while (isUncondBranchOpcode(SecondLastOpc)) {
314       LastInst->eraseFromParent();
315       LastInst = SecondLastInst;
316       LastOpc = LastInst->getOpcode();
317       if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
318         // Return now the only terminator is an unconditional branch.
319         TBB = LastInst->getOperand(0).getMBB();
320         return false;
321       } else {
322         SecondLastInst = I;
323         SecondLastOpc = SecondLastInst->getOpcode();
324       }
325     }
326   }
327
328   // If there are three terminators, we don't know what sort of block this is.
329   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
330     return true;
331
332   // If the block ends with a B and a Bcc, handle it.
333   if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
334     TBB =  SecondLastInst->getOperand(0).getMBB();
335     Cond.push_back(SecondLastInst->getOperand(1));
336     Cond.push_back(SecondLastInst->getOperand(2));
337     FBB = LastInst->getOperand(0).getMBB();
338     return false;
339   }
340
341   // If the block ends with two unconditional branches, handle it.  The second
342   // one is not executed, so remove it.
343   if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
344     TBB = SecondLastInst->getOperand(0).getMBB();
345     I = LastInst;
346     if (AllowModify)
347       I->eraseFromParent();
348     return false;
349   }
350
351   // ...likewise if it ends with a branch table followed by an unconditional
352   // branch. The branch folder can create these, and we must get rid of them for
353   // correctness of Thumb constant islands.
354   if ((isJumpTableBranchOpcode(SecondLastOpc) ||
355        isIndirectBranchOpcode(SecondLastOpc)) &&
356       isUncondBranchOpcode(LastOpc)) {
357     I = LastInst;
358     if (AllowModify)
359       I->eraseFromParent();
360     return true;
361   }
362
363   // Otherwise, can't handle this.
364   return true;
365 }
366
367
368 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
369   MachineBasicBlock::iterator I = MBB.end();
370   if (I == MBB.begin()) return 0;
371   --I;
372   while (I->isDebugValue()) {
373     if (I == MBB.begin())
374       return 0;
375     --I;
376   }
377   if (!isUncondBranchOpcode(I->getOpcode()) &&
378       !isCondBranchOpcode(I->getOpcode()))
379     return 0;
380
381   // Remove the branch.
382   I->eraseFromParent();
383
384   I = MBB.end();
385
386   if (I == MBB.begin()) return 1;
387   --I;
388   if (!isCondBranchOpcode(I->getOpcode()))
389     return 1;
390
391   // Remove the branch.
392   I->eraseFromParent();
393   return 2;
394 }
395
396 unsigned
397 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
398                                MachineBasicBlock *FBB,
399                                const SmallVectorImpl<MachineOperand> &Cond,
400                                DebugLoc DL) const {
401   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
402   int BOpc   = !AFI->isThumbFunction()
403     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
404   int BccOpc = !AFI->isThumbFunction()
405     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
406   bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
407
408   // Shouldn't be a fall through.
409   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
410   assert((Cond.size() == 2 || Cond.size() == 0) &&
411          "ARM branch conditions have two components!");
412
413   if (FBB == 0) {
414     if (Cond.empty()) { // Unconditional branch?
415       if (isThumb)
416         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).addImm(ARMCC::AL).addReg(0);
417       else
418         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
419     } else
420       BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
421         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
422     return 1;
423   }
424
425   // Two-way conditional branch.
426   BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
427     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
428   if (isThumb)
429     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).addImm(ARMCC::AL).addReg(0);
430   else
431     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
432   return 2;
433 }
434
435 bool ARMBaseInstrInfo::
436 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
437   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
438   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
439   return false;
440 }
441
442 bool ARMBaseInstrInfo::
443 PredicateInstruction(MachineInstr *MI,
444                      const SmallVectorImpl<MachineOperand> &Pred) const {
445   unsigned Opc = MI->getOpcode();
446   if (isUncondBranchOpcode(Opc)) {
447     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
448     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
449     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
450     return true;
451   }
452
453   int PIdx = MI->findFirstPredOperandIdx();
454   if (PIdx != -1) {
455     MachineOperand &PMO = MI->getOperand(PIdx);
456     PMO.setImm(Pred[0].getImm());
457     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
458     return true;
459   }
460   return false;
461 }
462
463 bool ARMBaseInstrInfo::
464 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
465                   const SmallVectorImpl<MachineOperand> &Pred2) const {
466   if (Pred1.size() > 2 || Pred2.size() > 2)
467     return false;
468
469   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
470   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
471   if (CC1 == CC2)
472     return true;
473
474   switch (CC1) {
475   default:
476     return false;
477   case ARMCC::AL:
478     return true;
479   case ARMCC::HS:
480     return CC2 == ARMCC::HI;
481   case ARMCC::LS:
482     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
483   case ARMCC::GE:
484     return CC2 == ARMCC::GT;
485   case ARMCC::LE:
486     return CC2 == ARMCC::LT;
487   }
488 }
489
490 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
491                                     std::vector<MachineOperand> &Pred) const {
492   // FIXME: This confuses implicit_def with optional CPSR def.
493   const MCInstrDesc &MCID = MI->getDesc();
494   if (!MCID.getImplicitDefs() && !MCID.hasOptionalDef())
495     return false;
496
497   bool Found = false;
498   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
499     const MachineOperand &MO = MI->getOperand(i);
500     if (MO.isReg() && MO.getReg() == ARM::CPSR) {
501       Pred.push_back(MO);
502       Found = true;
503     }
504   }
505
506   return Found;
507 }
508
509 /// isPredicable - Return true if the specified instruction can be predicated.
510 /// By default, this returns true for every instruction with a
511 /// PredicateOperand.
512 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
513   const MCInstrDesc &MCID = MI->getDesc();
514   if (!MCID.isPredicable())
515     return false;
516
517   if ((MCID.TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) {
518     ARMFunctionInfo *AFI =
519       MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
520     return AFI->isThumb2Function();
521   }
522   return true;
523 }
524
525 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
526 LLVM_ATTRIBUTE_NOINLINE
527 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
528                                 unsigned JTI);
529 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
530                                 unsigned JTI) {
531   assert(JTI < JT.size());
532   return JT[JTI].MBBs.size();
533 }
534
535 /// GetInstSize - Return the size of the specified MachineInstr.
536 ///
537 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
538   const MachineBasicBlock &MBB = *MI->getParent();
539   const MachineFunction *MF = MBB.getParent();
540   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
541
542   const MCInstrDesc &MCID = MI->getDesc();
543   if (MCID.getSize())
544     return MCID.getSize();
545
546     // If this machine instr is an inline asm, measure it.
547     if (MI->getOpcode() == ARM::INLINEASM)
548       return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
549     if (MI->isLabel())
550       return 0;
551   unsigned Opc = MI->getOpcode();
552     switch (Opc) {
553     case TargetOpcode::IMPLICIT_DEF:
554     case TargetOpcode::KILL:
555     case TargetOpcode::PROLOG_LABEL:
556     case TargetOpcode::EH_LABEL:
557     case TargetOpcode::DBG_VALUE:
558       return 0;
559     case ARM::MOVi16_ga_pcrel:
560     case ARM::MOVTi16_ga_pcrel:
561     case ARM::t2MOVi16_ga_pcrel:
562     case ARM::t2MOVTi16_ga_pcrel:
563       return 4;
564     case ARM::MOVi32imm:
565     case ARM::t2MOVi32imm:
566       return 8;
567     case ARM::CONSTPOOL_ENTRY:
568       // If this machine instr is a constant pool entry, its size is recorded as
569       // operand #2.
570       return MI->getOperand(2).getImm();
571     case ARM::Int_eh_sjlj_longjmp:
572       return 16;
573     case ARM::tInt_eh_sjlj_longjmp:
574       return 10;
575     case ARM::Int_eh_sjlj_setjmp:
576     case ARM::Int_eh_sjlj_setjmp_nofp:
577       return 20;
578     case ARM::tInt_eh_sjlj_setjmp:
579     case ARM::t2Int_eh_sjlj_setjmp:
580     case ARM::t2Int_eh_sjlj_setjmp_nofp:
581       return 12;
582     case ARM::BR_JTr:
583     case ARM::BR_JTm:
584     case ARM::BR_JTadd:
585     case ARM::tBR_JTr:
586     case ARM::t2BR_JT:
587     case ARM::t2TBB_JT:
588     case ARM::t2TBH_JT: {
589       // These are jumptable branches, i.e. a branch followed by an inlined
590       // jumptable. The size is 4 + 4 * number of entries. For TBB, each
591       // entry is one byte; TBH two byte each.
592       unsigned EntrySize = (Opc == ARM::t2TBB_JT)
593         ? 1 : ((Opc == ARM::t2TBH_JT) ? 2 : 4);
594       unsigned NumOps = MCID.getNumOperands();
595       MachineOperand JTOP =
596         MI->getOperand(NumOps - (MCID.isPredicable() ? 3 : 2));
597       unsigned JTI = JTOP.getIndex();
598       const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
599       assert(MJTI != 0);
600       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
601       assert(JTI < JT.size());
602       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
603       // 4 aligned. The assembler / linker may add 2 byte padding just before
604       // the JT entries.  The size does not include this padding; the
605       // constant islands pass does separate bookkeeping for it.
606       // FIXME: If we know the size of the function is less than (1 << 16) *2
607       // bytes, we can use 16-bit entries instead. Then there won't be an
608       // alignment issue.
609       unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
610       unsigned NumEntries = getNumJTEntries(JT, JTI);
611       if (Opc == ARM::t2TBB_JT && (NumEntries & 1))
612         // Make sure the instruction that follows TBB is 2-byte aligned.
613         // FIXME: Constant island pass should insert an "ALIGN" instruction
614         // instead.
615         ++NumEntries;
616       return NumEntries * EntrySize + InstSize;
617     }
618     default:
619       // Otherwise, pseudo-instruction sizes are zero.
620       return 0;
621     }
622   return 0; // Not reached
623 }
624
625 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
626                                    MachineBasicBlock::iterator I, DebugLoc DL,
627                                    unsigned DestReg, unsigned SrcReg,
628                                    bool KillSrc) const {
629   bool GPRDest = ARM::GPRRegClass.contains(DestReg);
630   bool GPRSrc  = ARM::GPRRegClass.contains(SrcReg);
631
632   if (GPRDest && GPRSrc) {
633     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
634                                   .addReg(SrcReg, getKillRegState(KillSrc))));
635     return;
636   }
637
638   bool SPRDest = ARM::SPRRegClass.contains(DestReg);
639   bool SPRSrc  = ARM::SPRRegClass.contains(SrcReg);
640
641   unsigned Opc = 0;
642   if (SPRDest && SPRSrc)
643     Opc = ARM::VMOVS;
644   else if (GPRDest && SPRSrc)
645     Opc = ARM::VMOVRS;
646   else if (SPRDest && GPRSrc)
647     Opc = ARM::VMOVSR;
648   else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
649     Opc = ARM::VMOVD;
650   else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
651     Opc = ARM::VORRq;
652
653   if (Opc) {
654     MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
655     MIB.addReg(SrcReg, getKillRegState(KillSrc));
656     if (Opc == ARM::VORRq)
657       MIB.addReg(SrcReg, getKillRegState(KillSrc));
658     AddDefaultPred(MIB);
659     return;
660   }
661
662   // Generate instructions for VMOVQQ and VMOVQQQQ pseudos in place.
663   if (ARM::QQPRRegClass.contains(DestReg, SrcReg) ||
664       ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
665     const TargetRegisterInfo *TRI = &getRegisterInfo();
666     assert(ARM::qsub_0 + 3 == ARM::qsub_3 && "Expected contiguous enum.");
667     unsigned EndSubReg = ARM::QQPRRegClass.contains(DestReg, SrcReg) ?
668       ARM::qsub_1 : ARM::qsub_3;
669     for (unsigned i = ARM::qsub_0, e = EndSubReg + 1; i != e; ++i) {
670       unsigned Dst = TRI->getSubReg(DestReg, i);
671       unsigned Src = TRI->getSubReg(SrcReg, i);
672       MachineInstrBuilder Mov =
673         AddDefaultPred(BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VORRq))
674                        .addReg(Dst, RegState::Define)
675                        .addReg(Src, getKillRegState(KillSrc))
676                        .addReg(Src, getKillRegState(KillSrc)));
677       if (i == EndSubReg) {
678         Mov->addRegisterDefined(DestReg, TRI);
679         if (KillSrc)
680           Mov->addRegisterKilled(SrcReg, TRI);
681       }
682     }
683     return;
684   }
685   llvm_unreachable("Impossible reg-to-reg copy");
686 }
687
688 static const
689 MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB,
690                              unsigned Reg, unsigned SubIdx, unsigned State,
691                              const TargetRegisterInfo *TRI) {
692   if (!SubIdx)
693     return MIB.addReg(Reg, State);
694
695   if (TargetRegisterInfo::isPhysicalRegister(Reg))
696     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
697   return MIB.addReg(Reg, State, SubIdx);
698 }
699
700 void ARMBaseInstrInfo::
701 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
702                     unsigned SrcReg, bool isKill, int FI,
703                     const TargetRegisterClass *RC,
704                     const TargetRegisterInfo *TRI) const {
705   DebugLoc DL;
706   if (I != MBB.end()) DL = I->getDebugLoc();
707   MachineFunction &MF = *MBB.getParent();
708   MachineFrameInfo &MFI = *MF.getFrameInfo();
709   unsigned Align = MFI.getObjectAlignment(FI);
710
711   MachineMemOperand *MMO =
712     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
713                             MachineMemOperand::MOStore,
714                             MFI.getObjectSize(FI),
715                             Align);
716
717   switch (RC->getSize()) {
718     case 4:
719       if (ARM::GPRRegClass.hasSubClassEq(RC)) {
720         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
721                    .addReg(SrcReg, getKillRegState(isKill))
722                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
723       } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
724         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
725                    .addReg(SrcReg, getKillRegState(isKill))
726                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
727       } else
728         llvm_unreachable("Unknown reg class!");
729       break;
730     case 8:
731       if (ARM::DPRRegClass.hasSubClassEq(RC)) {
732         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
733                    .addReg(SrcReg, getKillRegState(isKill))
734                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
735       } else
736         llvm_unreachable("Unknown reg class!");
737       break;
738     case 16:
739       if (ARM::QPRRegClass.hasSubClassEq(RC)) {
740         if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
741           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64Pseudo))
742                      .addFrameIndex(FI).addImm(16)
743                      .addReg(SrcReg, getKillRegState(isKill))
744                      .addMemOperand(MMO));
745         } else {
746           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
747                      .addReg(SrcReg, getKillRegState(isKill))
748                      .addFrameIndex(FI)
749                      .addMemOperand(MMO));
750         }
751       } else
752         llvm_unreachable("Unknown reg class!");
753       break;
754     case 32:
755       if (ARM::QQPRRegClass.hasSubClassEq(RC)) {
756         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
757           // FIXME: It's possible to only store part of the QQ register if the
758           // spilled def has a sub-register index.
759           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
760                      .addFrameIndex(FI).addImm(16)
761                      .addReg(SrcReg, getKillRegState(isKill))
762                      .addMemOperand(MMO));
763         } else {
764           MachineInstrBuilder MIB =
765           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
766                        .addFrameIndex(FI))
767                        .addMemOperand(MMO);
768           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
769           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
770           MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
771                 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
772         }
773       } else
774         llvm_unreachable("Unknown reg class!");
775       break;
776     case 64:
777       if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
778         MachineInstrBuilder MIB =
779           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
780                          .addFrameIndex(FI))
781                          .addMemOperand(MMO);
782         MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
783         MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
784         MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
785         MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
786         MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
787         MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
788         MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
789               AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
790       } else
791         llvm_unreachable("Unknown reg class!");
792       break;
793     default:
794       llvm_unreachable("Unknown reg class!");
795   }
796 }
797
798 unsigned
799 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
800                                      int &FrameIndex) const {
801   switch (MI->getOpcode()) {
802   default: break;
803   case ARM::STRrs:
804   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
805     if (MI->getOperand(1).isFI() &&
806         MI->getOperand(2).isReg() &&
807         MI->getOperand(3).isImm() &&
808         MI->getOperand(2).getReg() == 0 &&
809         MI->getOperand(3).getImm() == 0) {
810       FrameIndex = MI->getOperand(1).getIndex();
811       return MI->getOperand(0).getReg();
812     }
813     break;
814   case ARM::STRi12:
815   case ARM::t2STRi12:
816   case ARM::tSTRspi:
817   case ARM::VSTRD:
818   case ARM::VSTRS:
819     if (MI->getOperand(1).isFI() &&
820         MI->getOperand(2).isImm() &&
821         MI->getOperand(2).getImm() == 0) {
822       FrameIndex = MI->getOperand(1).getIndex();
823       return MI->getOperand(0).getReg();
824     }
825     break;
826   case ARM::VST1q64Pseudo:
827     if (MI->getOperand(0).isFI() &&
828         MI->getOperand(2).getSubReg() == 0) {
829       FrameIndex = MI->getOperand(0).getIndex();
830       return MI->getOperand(2).getReg();
831     }
832     break;
833   case ARM::VSTMQIA:
834     if (MI->getOperand(1).isFI() &&
835         MI->getOperand(0).getSubReg() == 0) {
836       FrameIndex = MI->getOperand(1).getIndex();
837       return MI->getOperand(0).getReg();
838     }
839     break;
840   }
841
842   return 0;
843 }
844
845 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
846                                                     int &FrameIndex) const {
847   const MachineMemOperand *Dummy;
848   return MI->getDesc().mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex);
849 }
850
851 void ARMBaseInstrInfo::
852 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
853                      unsigned DestReg, int FI,
854                      const TargetRegisterClass *RC,
855                      const TargetRegisterInfo *TRI) const {
856   DebugLoc DL;
857   if (I != MBB.end()) DL = I->getDebugLoc();
858   MachineFunction &MF = *MBB.getParent();
859   MachineFrameInfo &MFI = *MF.getFrameInfo();
860   unsigned Align = MFI.getObjectAlignment(FI);
861   MachineMemOperand *MMO =
862     MF.getMachineMemOperand(
863                     MachinePointerInfo::getFixedStack(FI),
864                             MachineMemOperand::MOLoad,
865                             MFI.getObjectSize(FI),
866                             Align);
867
868   switch (RC->getSize()) {
869   case 4:
870     if (ARM::GPRRegClass.hasSubClassEq(RC)) {
871       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
872                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
873
874     } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
875       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
876                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
877     } else
878       llvm_unreachable("Unknown reg class!");
879     break;
880   case 8:
881     if (ARM::DPRRegClass.hasSubClassEq(RC)) {
882       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
883                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
884     } else
885       llvm_unreachable("Unknown reg class!");
886     break;
887   case 16:
888     if (ARM::QPRRegClass.hasSubClassEq(RC)) {
889       if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
890         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64Pseudo), DestReg)
891                      .addFrameIndex(FI).addImm(16)
892                      .addMemOperand(MMO));
893       } else {
894         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
895                        .addFrameIndex(FI)
896                        .addMemOperand(MMO));
897       }
898     } else
899       llvm_unreachable("Unknown reg class!");
900     break;
901   case 32:
902     if (ARM::QQPRRegClass.hasSubClassEq(RC)) {
903       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
904         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
905                      .addFrameIndex(FI).addImm(16)
906                      .addMemOperand(MMO));
907       } else {
908         MachineInstrBuilder MIB =
909         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
910                        .addFrameIndex(FI))
911                        .addMemOperand(MMO);
912         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
913         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
914         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
915         MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
916         MIB.addReg(DestReg, RegState::Define | RegState::Implicit);
917       }
918     } else
919       llvm_unreachable("Unknown reg class!");
920     break;
921   case 64:
922     if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
923       MachineInstrBuilder MIB =
924       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
925                      .addFrameIndex(FI))
926                      .addMemOperand(MMO);
927       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
928       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
929       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
930       MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
931       MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::Define, TRI);
932       MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::Define, TRI);
933       MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::Define, TRI);
934       MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::Define, TRI);
935       MIB.addReg(DestReg, RegState::Define | RegState::Implicit);
936     } else
937       llvm_unreachable("Unknown reg class!");
938     break;
939   default:
940     llvm_unreachable("Unknown regclass!");
941   }
942 }
943
944 unsigned
945 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
946                                       int &FrameIndex) const {
947   switch (MI->getOpcode()) {
948   default: break;
949   case ARM::LDRrs:
950   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
951     if (MI->getOperand(1).isFI() &&
952         MI->getOperand(2).isReg() &&
953         MI->getOperand(3).isImm() &&
954         MI->getOperand(2).getReg() == 0 &&
955         MI->getOperand(3).getImm() == 0) {
956       FrameIndex = MI->getOperand(1).getIndex();
957       return MI->getOperand(0).getReg();
958     }
959     break;
960   case ARM::LDRi12:
961   case ARM::t2LDRi12:
962   case ARM::tLDRspi:
963   case ARM::VLDRD:
964   case ARM::VLDRS:
965     if (MI->getOperand(1).isFI() &&
966         MI->getOperand(2).isImm() &&
967         MI->getOperand(2).getImm() == 0) {
968       FrameIndex = MI->getOperand(1).getIndex();
969       return MI->getOperand(0).getReg();
970     }
971     break;
972   case ARM::VLD1q64Pseudo:
973     if (MI->getOperand(1).isFI() &&
974         MI->getOperand(0).getSubReg() == 0) {
975       FrameIndex = MI->getOperand(1).getIndex();
976       return MI->getOperand(0).getReg();
977     }
978     break;
979   case ARM::VLDMQIA:
980     if (MI->getOperand(1).isFI() &&
981         MI->getOperand(0).getSubReg() == 0) {
982       FrameIndex = MI->getOperand(1).getIndex();
983       return MI->getOperand(0).getReg();
984     }
985     break;
986   }
987
988   return 0;
989 }
990
991 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI,
992                                              int &FrameIndex) const {
993   const MachineMemOperand *Dummy;
994   return MI->getDesc().mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex);
995 }
996
997 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const{
998   // This hook gets to expand COPY instructions before they become
999   // copyPhysReg() calls.  Look for VMOVS instructions that can legally be
1000   // widened to VMOVD.  We prefer the VMOVD when possible because it may be
1001   // changed into a VORR that can go down the NEON pipeline.
1002   if (!WidenVMOVS || !MI->isCopy())
1003     return false;
1004
1005   // Look for a copy between even S-registers.  That is where we keep floats
1006   // when using NEON v2f32 instructions for f32 arithmetic.
1007   unsigned DstRegS = MI->getOperand(0).getReg();
1008   unsigned SrcRegS = MI->getOperand(1).getReg();
1009   if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1010     return false;
1011
1012   const TargetRegisterInfo *TRI = &getRegisterInfo();
1013   unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1014                                               &ARM::DPRRegClass);
1015   unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1016                                               &ARM::DPRRegClass);
1017   if (!DstRegD || !SrcRegD)
1018     return false;
1019
1020   // We want to widen this into a DstRegD = VMOVD SrcRegD copy.  This is only
1021   // legal if the COPY already defines the full DstRegD, and it isn't a
1022   // sub-register insertion.
1023   if (!MI->definesRegister(DstRegD, TRI) || MI->readsRegister(DstRegD, TRI))
1024     return false;
1025
1026   // A dead copy shouldn't show up here, but reject it just in case.
1027   if (MI->getOperand(0).isDead())
1028     return false;
1029
1030   // All clear, widen the COPY.
1031   DEBUG(dbgs() << "widening:    " << *MI);
1032
1033   // Get rid of the old <imp-def> of DstRegD.  Leave it if it defines a Q-reg
1034   // or some other super-register.
1035   int ImpDefIdx = MI->findRegisterDefOperandIdx(DstRegD);
1036   if (ImpDefIdx != -1)
1037     MI->RemoveOperand(ImpDefIdx);
1038
1039   // Change the opcode and operands.
1040   MI->setDesc(get(ARM::VMOVD));
1041   MI->getOperand(0).setReg(DstRegD);
1042   MI->getOperand(1).setReg(SrcRegD);
1043   AddDefaultPred(MachineInstrBuilder(MI));
1044
1045   // We are now reading SrcRegD instead of SrcRegS.  This may upset the
1046   // register scavenger and machine verifier, so we need to indicate that we
1047   // are reading an undefined value from SrcRegD, but a proper value from
1048   // SrcRegS.
1049   MI->getOperand(1).setIsUndef();
1050   MachineInstrBuilder(MI).addReg(SrcRegS, RegState::Implicit);
1051
1052   // SrcRegD may actually contain an unrelated value in the ssub_1
1053   // sub-register.  Don't kill it.  Only kill the ssub_0 sub-register.
1054   if (MI->getOperand(1).isKill()) {
1055     MI->getOperand(1).setIsKill(false);
1056     MI->addRegisterKilled(SrcRegS, TRI, true);
1057   }
1058
1059   DEBUG(dbgs() << "replaced by: " << *MI);
1060   return true;
1061 }
1062
1063 MachineInstr*
1064 ARMBaseInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
1065                                            int FrameIx, uint64_t Offset,
1066                                            const MDNode *MDPtr,
1067                                            DebugLoc DL) const {
1068   MachineInstrBuilder MIB = BuildMI(MF, DL, get(ARM::DBG_VALUE))
1069     .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
1070   return &*MIB;
1071 }
1072
1073 /// Create a copy of a const pool value. Update CPI to the new index and return
1074 /// the label UID.
1075 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1076   MachineConstantPool *MCP = MF.getConstantPool();
1077   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1078
1079   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1080   assert(MCPE.isMachineConstantPoolEntry() &&
1081          "Expecting a machine constantpool entry!");
1082   ARMConstantPoolValue *ACPV =
1083     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1084
1085   unsigned PCLabelId = AFI->createPICLabelUId();
1086   ARMConstantPoolValue *NewCPV = 0;
1087   // FIXME: The below assumes PIC relocation model and that the function
1088   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1089   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1090   // instructions, so that's probably OK, but is PIC always correct when
1091   // we get here?
1092   if (ACPV->isGlobalValue())
1093     NewCPV = ARMConstantPoolConstant::
1094       Create(cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId,
1095              ARMCP::CPValue, 4);
1096   else if (ACPV->isExtSymbol())
1097     NewCPV = ARMConstantPoolSymbol::
1098       Create(MF.getFunction()->getContext(),
1099              cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1100   else if (ACPV->isBlockAddress())
1101     NewCPV = ARMConstantPoolConstant::
1102       Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1103              ARMCP::CPBlockAddress, 4);
1104   else if (ACPV->isLSDA())
1105     NewCPV = ARMConstantPoolConstant::Create(MF.getFunction(), PCLabelId,
1106                                              ARMCP::CPLSDA, 4);
1107   else if (ACPV->isMachineBasicBlock())
1108     NewCPV = ARMConstantPoolMBB::
1109       Create(MF.getFunction()->getContext(),
1110              cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1111   else
1112     llvm_unreachable("Unexpected ARM constantpool value type!!");
1113   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1114   return PCLabelId;
1115 }
1116
1117 void ARMBaseInstrInfo::
1118 reMaterialize(MachineBasicBlock &MBB,
1119               MachineBasicBlock::iterator I,
1120               unsigned DestReg, unsigned SubIdx,
1121               const MachineInstr *Orig,
1122               const TargetRegisterInfo &TRI) const {
1123   unsigned Opcode = Orig->getOpcode();
1124   switch (Opcode) {
1125   default: {
1126     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1127     MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1128     MBB.insert(I, MI);
1129     break;
1130   }
1131   case ARM::tLDRpci_pic:
1132   case ARM::t2LDRpci_pic: {
1133     MachineFunction &MF = *MBB.getParent();
1134     unsigned CPI = Orig->getOperand(1).getIndex();
1135     unsigned PCLabelId = duplicateCPV(MF, CPI);
1136     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1137                                       DestReg)
1138       .addConstantPoolIndex(CPI).addImm(PCLabelId);
1139     MIB->setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1140     break;
1141   }
1142   }
1143 }
1144
1145 MachineInstr *
1146 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1147   MachineInstr *MI = TargetInstrInfoImpl::duplicate(Orig, MF);
1148   switch(Orig->getOpcode()) {
1149   case ARM::tLDRpci_pic:
1150   case ARM::t2LDRpci_pic: {
1151     unsigned CPI = Orig->getOperand(1).getIndex();
1152     unsigned PCLabelId = duplicateCPV(MF, CPI);
1153     Orig->getOperand(1).setIndex(CPI);
1154     Orig->getOperand(2).setImm(PCLabelId);
1155     break;
1156   }
1157   }
1158   return MI;
1159 }
1160
1161 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1162                                         const MachineInstr *MI1,
1163                                         const MachineRegisterInfo *MRI) const {
1164   int Opcode = MI0->getOpcode();
1165   if (Opcode == ARM::t2LDRpci ||
1166       Opcode == ARM::t2LDRpci_pic ||
1167       Opcode == ARM::tLDRpci ||
1168       Opcode == ARM::tLDRpci_pic ||
1169       Opcode == ARM::MOV_ga_dyn ||
1170       Opcode == ARM::MOV_ga_pcrel ||
1171       Opcode == ARM::MOV_ga_pcrel_ldr ||
1172       Opcode == ARM::t2MOV_ga_dyn ||
1173       Opcode == ARM::t2MOV_ga_pcrel) {
1174     if (MI1->getOpcode() != Opcode)
1175       return false;
1176     if (MI0->getNumOperands() != MI1->getNumOperands())
1177       return false;
1178
1179     const MachineOperand &MO0 = MI0->getOperand(1);
1180     const MachineOperand &MO1 = MI1->getOperand(1);
1181     if (MO0.getOffset() != MO1.getOffset())
1182       return false;
1183
1184     if (Opcode == ARM::MOV_ga_dyn ||
1185         Opcode == ARM::MOV_ga_pcrel ||
1186         Opcode == ARM::MOV_ga_pcrel_ldr ||
1187         Opcode == ARM::t2MOV_ga_dyn ||
1188         Opcode == ARM::t2MOV_ga_pcrel)
1189       // Ignore the PC labels.
1190       return MO0.getGlobal() == MO1.getGlobal();
1191
1192     const MachineFunction *MF = MI0->getParent()->getParent();
1193     const MachineConstantPool *MCP = MF->getConstantPool();
1194     int CPI0 = MO0.getIndex();
1195     int CPI1 = MO1.getIndex();
1196     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1197     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1198     bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1199     bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1200     if (isARMCP0 && isARMCP1) {
1201       ARMConstantPoolValue *ACPV0 =
1202         static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1203       ARMConstantPoolValue *ACPV1 =
1204         static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1205       return ACPV0->hasSameValue(ACPV1);
1206     } else if (!isARMCP0 && !isARMCP1) {
1207       return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1208     }
1209     return false;
1210   } else if (Opcode == ARM::PICLDR) {
1211     if (MI1->getOpcode() != Opcode)
1212       return false;
1213     if (MI0->getNumOperands() != MI1->getNumOperands())
1214       return false;
1215
1216     unsigned Addr0 = MI0->getOperand(1).getReg();
1217     unsigned Addr1 = MI1->getOperand(1).getReg();
1218     if (Addr0 != Addr1) {
1219       if (!MRI ||
1220           !TargetRegisterInfo::isVirtualRegister(Addr0) ||
1221           !TargetRegisterInfo::isVirtualRegister(Addr1))
1222         return false;
1223
1224       // This assumes SSA form.
1225       MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1226       MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1227       // Check if the loaded value, e.g. a constantpool of a global address, are
1228       // the same.
1229       if (!produceSameValue(Def0, Def1, MRI))
1230         return false;
1231     }
1232
1233     for (unsigned i = 3, e = MI0->getNumOperands(); i != e; ++i) {
1234       // %vreg12<def> = PICLDR %vreg11, 0, pred:14, pred:%noreg
1235       const MachineOperand &MO0 = MI0->getOperand(i);
1236       const MachineOperand &MO1 = MI1->getOperand(i);
1237       if (!MO0.isIdenticalTo(MO1))
1238         return false;
1239     }
1240     return true;
1241   }
1242
1243   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1244 }
1245
1246 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1247 /// determine if two loads are loading from the same base address. It should
1248 /// only return true if the base pointers are the same and the only differences
1249 /// between the two addresses is the offset. It also returns the offsets by
1250 /// reference.
1251 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1252                                                int64_t &Offset1,
1253                                                int64_t &Offset2) const {
1254   // Don't worry about Thumb: just ARM and Thumb2.
1255   if (Subtarget.isThumb1Only()) return false;
1256
1257   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1258     return false;
1259
1260   switch (Load1->getMachineOpcode()) {
1261   default:
1262     return false;
1263   case ARM::LDRi12:
1264   case ARM::LDRBi12:
1265   case ARM::LDRD:
1266   case ARM::LDRH:
1267   case ARM::LDRSB:
1268   case ARM::LDRSH:
1269   case ARM::VLDRD:
1270   case ARM::VLDRS:
1271   case ARM::t2LDRi8:
1272   case ARM::t2LDRDi8:
1273   case ARM::t2LDRSHi8:
1274   case ARM::t2LDRi12:
1275   case ARM::t2LDRSHi12:
1276     break;
1277   }
1278
1279   switch (Load2->getMachineOpcode()) {
1280   default:
1281     return false;
1282   case ARM::LDRi12:
1283   case ARM::LDRBi12:
1284   case ARM::LDRD:
1285   case ARM::LDRH:
1286   case ARM::LDRSB:
1287   case ARM::LDRSH:
1288   case ARM::VLDRD:
1289   case ARM::VLDRS:
1290   case ARM::t2LDRi8:
1291   case ARM::t2LDRDi8:
1292   case ARM::t2LDRSHi8:
1293   case ARM::t2LDRi12:
1294   case ARM::t2LDRSHi12:
1295     break;
1296   }
1297
1298   // Check if base addresses and chain operands match.
1299   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1300       Load1->getOperand(4) != Load2->getOperand(4))
1301     return false;
1302
1303   // Index should be Reg0.
1304   if (Load1->getOperand(3) != Load2->getOperand(3))
1305     return false;
1306
1307   // Determine the offsets.
1308   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1309       isa<ConstantSDNode>(Load2->getOperand(1))) {
1310     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1311     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1312     return true;
1313   }
1314
1315   return false;
1316 }
1317
1318 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1319 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1320 /// be scheduled togther. On some targets if two loads are loading from
1321 /// addresses in the same cache line, it's better if they are scheduled
1322 /// together. This function takes two integers that represent the load offsets
1323 /// from the common base address. It returns true if it decides it's desirable
1324 /// to schedule the two loads together. "NumLoads" is the number of loads that
1325 /// have already been scheduled after Load1.
1326 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1327                                                int64_t Offset1, int64_t Offset2,
1328                                                unsigned NumLoads) const {
1329   // Don't worry about Thumb: just ARM and Thumb2.
1330   if (Subtarget.isThumb1Only()) return false;
1331
1332   assert(Offset2 > Offset1);
1333
1334   if ((Offset2 - Offset1) / 8 > 64)
1335     return false;
1336
1337   if (Load1->getMachineOpcode() != Load2->getMachineOpcode())
1338     return false;  // FIXME: overly conservative?
1339
1340   // Four loads in a row should be sufficient.
1341   if (NumLoads >= 3)
1342     return false;
1343
1344   return true;
1345 }
1346
1347 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1348                                             const MachineBasicBlock *MBB,
1349                                             const MachineFunction &MF) const {
1350   // Debug info is never a scheduling boundary. It's necessary to be explicit
1351   // due to the special treatment of IT instructions below, otherwise a
1352   // dbg_value followed by an IT will result in the IT instruction being
1353   // considered a scheduling hazard, which is wrong. It should be the actual
1354   // instruction preceding the dbg_value instruction(s), just like it is
1355   // when debug info is not present.
1356   if (MI->isDebugValue())
1357     return false;
1358
1359   // Terminators and labels can't be scheduled around.
1360   if (MI->getDesc().isTerminator() || MI->isLabel())
1361     return true;
1362
1363   // Treat the start of the IT block as a scheduling boundary, but schedule
1364   // t2IT along with all instructions following it.
1365   // FIXME: This is a big hammer. But the alternative is to add all potential
1366   // true and anti dependencies to IT block instructions as implicit operands
1367   // to the t2IT instruction. The added compile time and complexity does not
1368   // seem worth it.
1369   MachineBasicBlock::const_iterator I = MI;
1370   // Make sure to skip any dbg_value instructions
1371   while (++I != MBB->end() && I->isDebugValue())
1372     ;
1373   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1374     return true;
1375
1376   // Don't attempt to schedule around any instruction that defines
1377   // a stack-oriented pointer, as it's unlikely to be profitable. This
1378   // saves compile time, because it doesn't require every single
1379   // stack slot reference to depend on the instruction that does the
1380   // modification.
1381   if (MI->definesRegister(ARM::SP))
1382     return true;
1383
1384   return false;
1385 }
1386
1387 bool ARMBaseInstrInfo::
1388 isProfitableToIfCvt(MachineBasicBlock &MBB,
1389                     unsigned NumCycles, unsigned ExtraPredCycles,
1390                     const BranchProbability &Probability) const {
1391   if (!NumCycles)
1392     return false;
1393
1394   // Attempt to estimate the relative costs of predication versus branching.
1395   unsigned UnpredCost = Probability.getNumerator() * NumCycles;
1396   UnpredCost /= Probability.getDenominator();
1397   UnpredCost += 1; // The branch itself
1398   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1399
1400   return (NumCycles + ExtraPredCycles) <= UnpredCost;
1401 }
1402
1403 bool ARMBaseInstrInfo::
1404 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1405                     unsigned TCycles, unsigned TExtra,
1406                     MachineBasicBlock &FMBB,
1407                     unsigned FCycles, unsigned FExtra,
1408                     const BranchProbability &Probability) const {
1409   if (!TCycles || !FCycles)
1410     return false;
1411
1412   // Attempt to estimate the relative costs of predication versus branching.
1413   unsigned TUnpredCost = Probability.getNumerator() * TCycles;
1414   TUnpredCost /= Probability.getDenominator();
1415
1416   uint32_t Comp = Probability.getDenominator() - Probability.getNumerator();
1417   unsigned FUnpredCost = Comp * FCycles;
1418   FUnpredCost /= Probability.getDenominator();
1419
1420   unsigned UnpredCost = TUnpredCost + FUnpredCost;
1421   UnpredCost += 1; // The branch itself
1422   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1423
1424   return (TCycles + FCycles + TExtra + FExtra) <= UnpredCost;
1425 }
1426
1427 /// getInstrPredicate - If instruction is predicated, returns its predicate
1428 /// condition, otherwise returns AL. It also returns the condition code
1429 /// register by reference.
1430 ARMCC::CondCodes
1431 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1432   int PIdx = MI->findFirstPredOperandIdx();
1433   if (PIdx == -1) {
1434     PredReg = 0;
1435     return ARMCC::AL;
1436   }
1437
1438   PredReg = MI->getOperand(PIdx+1).getReg();
1439   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1440 }
1441
1442
1443 int llvm::getMatchingCondBranchOpcode(int Opc) {
1444   if (Opc == ARM::B)
1445     return ARM::Bcc;
1446   else if (Opc == ARM::tB)
1447     return ARM::tBcc;
1448   else if (Opc == ARM::t2B)
1449       return ARM::t2Bcc;
1450
1451   llvm_unreachable("Unknown unconditional branch opcode!");
1452   return 0;
1453 }
1454
1455
1456 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
1457 /// instruction is encoded with an 'S' bit is determined by the optional CPSR
1458 /// def operand.
1459 ///
1460 /// This will go away once we can teach tblgen how to set the optional CPSR def
1461 /// operand itself.
1462 struct AddSubFlagsOpcodePair {
1463   unsigned PseudoOpc;
1464   unsigned MachineOpc;
1465 };
1466
1467 static AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
1468   {ARM::ADDSri, ARM::ADDri},
1469   {ARM::ADDSrr, ARM::ADDrr},
1470   {ARM::ADDSrsi, ARM::ADDrsi},
1471   {ARM::ADDSrsr, ARM::ADDrsr},
1472
1473   {ARM::SUBSri, ARM::SUBri},
1474   {ARM::SUBSrr, ARM::SUBrr},
1475   {ARM::SUBSrsi, ARM::SUBrsi},
1476   {ARM::SUBSrsr, ARM::SUBrsr},
1477
1478   {ARM::RSBSri, ARM::RSBri},
1479   {ARM::RSBSrsi, ARM::RSBrsi},
1480   {ARM::RSBSrsr, ARM::RSBrsr},
1481
1482   {ARM::t2ADDSri, ARM::t2ADDri},
1483   {ARM::t2ADDSrr, ARM::t2ADDrr},
1484   {ARM::t2ADDSrs, ARM::t2ADDrs},
1485
1486   {ARM::t2SUBSri, ARM::t2SUBri},
1487   {ARM::t2SUBSrr, ARM::t2SUBrr},
1488   {ARM::t2SUBSrs, ARM::t2SUBrs},
1489
1490   {ARM::t2RSBSri, ARM::t2RSBri},
1491   {ARM::t2RSBSrs, ARM::t2RSBrs},
1492 };
1493
1494 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
1495   static const int NPairs =
1496     sizeof(AddSubFlagsOpcodeMap) / sizeof(AddSubFlagsOpcodePair);
1497   for (AddSubFlagsOpcodePair *OpcPair = &AddSubFlagsOpcodeMap[0],
1498          *End = &AddSubFlagsOpcodeMap[NPairs]; OpcPair != End; ++OpcPair) {
1499     if (OldOpc == OpcPair->PseudoOpc) {
1500       return OpcPair->MachineOpc;
1501     }
1502   }
1503   return 0;
1504 }
1505
1506 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1507                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1508                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1509                                ARMCC::CondCodes Pred, unsigned PredReg,
1510                                const ARMBaseInstrInfo &TII, unsigned MIFlags) {
1511   bool isSub = NumBytes < 0;
1512   if (isSub) NumBytes = -NumBytes;
1513
1514   while (NumBytes) {
1515     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1516     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1517     assert(ThisVal && "Didn't extract field correctly");
1518
1519     // We will handle these bits from offset, clear them.
1520     NumBytes &= ~ThisVal;
1521
1522     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1523
1524     // Build the new ADD / SUB.
1525     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1526     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1527       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1528       .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1529       .setMIFlags(MIFlags);
1530     BaseReg = DestReg;
1531   }
1532 }
1533
1534 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1535                                 unsigned FrameReg, int &Offset,
1536                                 const ARMBaseInstrInfo &TII) {
1537   unsigned Opcode = MI.getOpcode();
1538   const MCInstrDesc &Desc = MI.getDesc();
1539   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1540   bool isSub = false;
1541
1542   // Memory operands in inline assembly always use AddrMode2.
1543   if (Opcode == ARM::INLINEASM)
1544     AddrMode = ARMII::AddrMode2;
1545
1546   if (Opcode == ARM::ADDri) {
1547     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1548     if (Offset == 0) {
1549       // Turn it into a move.
1550       MI.setDesc(TII.get(ARM::MOVr));
1551       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1552       MI.RemoveOperand(FrameRegIdx+1);
1553       Offset = 0;
1554       return true;
1555     } else if (Offset < 0) {
1556       Offset = -Offset;
1557       isSub = true;
1558       MI.setDesc(TII.get(ARM::SUBri));
1559     }
1560
1561     // Common case: small offset, fits into instruction.
1562     if (ARM_AM::getSOImmVal(Offset) != -1) {
1563       // Replace the FrameIndex with sp / fp
1564       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1565       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1566       Offset = 0;
1567       return true;
1568     }
1569
1570     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1571     // as possible.
1572     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1573     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1574
1575     // We will handle these bits from offset, clear them.
1576     Offset &= ~ThisImmVal;
1577
1578     // Get the properly encoded SOImmVal field.
1579     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1580            "Bit extraction didn't work?");
1581     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1582  } else {
1583     unsigned ImmIdx = 0;
1584     int InstrOffs = 0;
1585     unsigned NumBits = 0;
1586     unsigned Scale = 1;
1587     switch (AddrMode) {
1588     case ARMII::AddrMode_i12: {
1589       ImmIdx = FrameRegIdx + 1;
1590       InstrOffs = MI.getOperand(ImmIdx).getImm();
1591       NumBits = 12;
1592       break;
1593     }
1594     case ARMII::AddrMode2: {
1595       ImmIdx = FrameRegIdx+2;
1596       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1597       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1598         InstrOffs *= -1;
1599       NumBits = 12;
1600       break;
1601     }
1602     case ARMII::AddrMode3: {
1603       ImmIdx = FrameRegIdx+2;
1604       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1605       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1606         InstrOffs *= -1;
1607       NumBits = 8;
1608       break;
1609     }
1610     case ARMII::AddrMode4:
1611     case ARMII::AddrMode6:
1612       // Can't fold any offset even if it's zero.
1613       return false;
1614     case ARMII::AddrMode5: {
1615       ImmIdx = FrameRegIdx+1;
1616       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1617       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1618         InstrOffs *= -1;
1619       NumBits = 8;
1620       Scale = 4;
1621       break;
1622     }
1623     default:
1624       llvm_unreachable("Unsupported addressing mode!");
1625       break;
1626     }
1627
1628     Offset += InstrOffs * Scale;
1629     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1630     if (Offset < 0) {
1631       Offset = -Offset;
1632       isSub = true;
1633     }
1634
1635     // Attempt to fold address comp. if opcode has offset bits
1636     if (NumBits > 0) {
1637       // Common case: small offset, fits into instruction.
1638       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1639       int ImmedOffset = Offset / Scale;
1640       unsigned Mask = (1 << NumBits) - 1;
1641       if ((unsigned)Offset <= Mask * Scale) {
1642         // Replace the FrameIndex with sp
1643         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1644         // FIXME: When addrmode2 goes away, this will simplify (like the
1645         // T2 version), as the LDR.i12 versions don't need the encoding
1646         // tricks for the offset value.
1647         if (isSub) {
1648           if (AddrMode == ARMII::AddrMode_i12)
1649             ImmedOffset = -ImmedOffset;
1650           else
1651             ImmedOffset |= 1 << NumBits;
1652         }
1653         ImmOp.ChangeToImmediate(ImmedOffset);
1654         Offset = 0;
1655         return true;
1656       }
1657
1658       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1659       ImmedOffset = ImmedOffset & Mask;
1660       if (isSub) {
1661         if (AddrMode == ARMII::AddrMode_i12)
1662           ImmedOffset = -ImmedOffset;
1663         else
1664           ImmedOffset |= 1 << NumBits;
1665       }
1666       ImmOp.ChangeToImmediate(ImmedOffset);
1667       Offset &= ~(Mask*Scale);
1668     }
1669   }
1670
1671   Offset = (isSub) ? -Offset : Offset;
1672   return Offset == 0;
1673 }
1674
1675 bool ARMBaseInstrInfo::
1676 AnalyzeCompare(const MachineInstr *MI, unsigned &SrcReg, int &CmpMask,
1677                int &CmpValue) const {
1678   switch (MI->getOpcode()) {
1679   default: break;
1680   case ARM::CMPri:
1681   case ARM::t2CMPri:
1682     SrcReg = MI->getOperand(0).getReg();
1683     CmpMask = ~0;
1684     CmpValue = MI->getOperand(1).getImm();
1685     return true;
1686   case ARM::TSTri:
1687   case ARM::t2TSTri:
1688     SrcReg = MI->getOperand(0).getReg();
1689     CmpMask = MI->getOperand(1).getImm();
1690     CmpValue = 0;
1691     return true;
1692   }
1693
1694   return false;
1695 }
1696
1697 /// isSuitableForMask - Identify a suitable 'and' instruction that
1698 /// operates on the given source register and applies the same mask
1699 /// as a 'tst' instruction. Provide a limited look-through for copies.
1700 /// When successful, MI will hold the found instruction.
1701 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
1702                               int CmpMask, bool CommonUse) {
1703   switch (MI->getOpcode()) {
1704     case ARM::ANDri:
1705     case ARM::t2ANDri:
1706       if (CmpMask != MI->getOperand(2).getImm())
1707         return false;
1708       if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
1709         return true;
1710       break;
1711     case ARM::COPY: {
1712       // Walk down one instruction which is potentially an 'and'.
1713       const MachineInstr &Copy = *MI;
1714       MachineBasicBlock::iterator AND(
1715         llvm::next(MachineBasicBlock::iterator(MI)));
1716       if (AND == MI->getParent()->end()) return false;
1717       MI = AND;
1718       return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
1719                                CmpMask, true);
1720     }
1721   }
1722
1723   return false;
1724 }
1725
1726 /// OptimizeCompareInstr - Convert the instruction supplying the argument to the
1727 /// comparison into one that sets the zero bit in the flags register.
1728 bool ARMBaseInstrInfo::
1729 OptimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, int CmpMask,
1730                      int CmpValue, const MachineRegisterInfo *MRI) const {
1731   if (CmpValue != 0)
1732     return false;
1733
1734   MachineRegisterInfo::def_iterator DI = MRI->def_begin(SrcReg);
1735   if (llvm::next(DI) != MRI->def_end())
1736     // Only support one definition.
1737     return false;
1738
1739   MachineInstr *MI = &*DI;
1740
1741   // Masked compares sometimes use the same register as the corresponding 'and'.
1742   if (CmpMask != ~0) {
1743     if (!isSuitableForMask(MI, SrcReg, CmpMask, false)) {
1744       MI = 0;
1745       for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
1746            UE = MRI->use_end(); UI != UE; ++UI) {
1747         if (UI->getParent() != CmpInstr->getParent()) continue;
1748         MachineInstr *PotentialAND = &*UI;
1749         if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true))
1750           continue;
1751         MI = PotentialAND;
1752         break;
1753       }
1754       if (!MI) return false;
1755     }
1756   }
1757
1758   // Conservatively refuse to convert an instruction which isn't in the same BB
1759   // as the comparison.
1760   if (MI->getParent() != CmpInstr->getParent())
1761     return false;
1762
1763   // Check that CPSR isn't set between the comparison instruction and the one we
1764   // want to change.
1765   MachineBasicBlock::iterator I = CmpInstr,E = MI, B = MI->getParent()->begin();
1766
1767   // Early exit if CmpInstr is at the beginning of the BB.
1768   if (I == B) return false;
1769
1770   --I;
1771   for (; I != E; --I) {
1772     const MachineInstr &Instr = *I;
1773
1774     for (unsigned IO = 0, EO = Instr.getNumOperands(); IO != EO; ++IO) {
1775       const MachineOperand &MO = Instr.getOperand(IO);
1776       if (!MO.isReg()) continue;
1777
1778       // This instruction modifies or uses CPSR after the one we want to
1779       // change. We can't do this transformation.
1780       if (MO.getReg() == ARM::CPSR)
1781         return false;
1782     }
1783
1784     if (I == B)
1785       // The 'and' is below the comparison instruction.
1786       return false;
1787   }
1788
1789   // Set the "zero" bit in CPSR.
1790   switch (MI->getOpcode()) {
1791   default: break;
1792   case ARM::RSBrr:
1793   case ARM::RSBri:
1794   case ARM::RSCrr:
1795   case ARM::RSCri:
1796   case ARM::ADDrr:
1797   case ARM::ADDri:
1798   case ARM::ADCrr:
1799   case ARM::ADCri:
1800   case ARM::SUBrr:
1801   case ARM::SUBri:
1802   case ARM::SBCrr:
1803   case ARM::SBCri:
1804   case ARM::t2RSBri:
1805   case ARM::t2ADDrr:
1806   case ARM::t2ADDri:
1807   case ARM::t2ADCrr:
1808   case ARM::t2ADCri:
1809   case ARM::t2SUBrr:
1810   case ARM::t2SUBri:
1811   case ARM::t2SBCrr:
1812   case ARM::t2SBCri:
1813   case ARM::ANDrr:
1814   case ARM::ANDri:
1815   case ARM::t2ANDrr:
1816   case ARM::t2ANDri:
1817   case ARM::ORRrr:
1818   case ARM::ORRri:
1819   case ARM::t2ORRrr:
1820   case ARM::t2ORRri:
1821   case ARM::EORrr:
1822   case ARM::EORri:
1823   case ARM::t2EORrr:
1824   case ARM::t2EORri: {
1825     // Scan forward for the use of CPSR, if it's a conditional code requires
1826     // checking of V bit, then this is not safe to do. If we can't find the
1827     // CPSR use (i.e. used in another block), then it's not safe to perform
1828     // the optimization.
1829     bool isSafe = false;
1830     I = CmpInstr;
1831     E = MI->getParent()->end();
1832     while (!isSafe && ++I != E) {
1833       const MachineInstr &Instr = *I;
1834       for (unsigned IO = 0, EO = Instr.getNumOperands();
1835            !isSafe && IO != EO; ++IO) {
1836         const MachineOperand &MO = Instr.getOperand(IO);
1837         if (!MO.isReg() || MO.getReg() != ARM::CPSR)
1838           continue;
1839         if (MO.isDef()) {
1840           isSafe = true;
1841           break;
1842         }
1843         // Condition code is after the operand before CPSR.
1844         ARMCC::CondCodes CC = (ARMCC::CondCodes)Instr.getOperand(IO-1).getImm();
1845         switch (CC) {
1846         default:
1847           isSafe = true;
1848           break;
1849         case ARMCC::VS:
1850         case ARMCC::VC:
1851         case ARMCC::GE:
1852         case ARMCC::LT:
1853         case ARMCC::GT:
1854         case ARMCC::LE:
1855           return false;
1856         }
1857       }
1858     }
1859
1860     if (!isSafe)
1861       return false;
1862
1863     // Toggle the optional operand to CPSR.
1864     MI->getOperand(5).setReg(ARM::CPSR);
1865     MI->getOperand(5).setIsDef(true);
1866     CmpInstr->eraseFromParent();
1867     return true;
1868   }
1869   }
1870
1871   return false;
1872 }
1873
1874 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
1875                                      MachineInstr *DefMI, unsigned Reg,
1876                                      MachineRegisterInfo *MRI) const {
1877   // Fold large immediates into add, sub, or, xor.
1878   unsigned DefOpc = DefMI->getOpcode();
1879   if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
1880     return false;
1881   if (!DefMI->getOperand(1).isImm())
1882     // Could be t2MOVi32imm <ga:xx>
1883     return false;
1884
1885   if (!MRI->hasOneNonDBGUse(Reg))
1886     return false;
1887
1888   unsigned UseOpc = UseMI->getOpcode();
1889   unsigned NewUseOpc = 0;
1890   uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
1891   uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
1892   bool Commute = false;
1893   switch (UseOpc) {
1894   default: return false;
1895   case ARM::SUBrr:
1896   case ARM::ADDrr:
1897   case ARM::ORRrr:
1898   case ARM::EORrr:
1899   case ARM::t2SUBrr:
1900   case ARM::t2ADDrr:
1901   case ARM::t2ORRrr:
1902   case ARM::t2EORrr: {
1903     Commute = UseMI->getOperand(2).getReg() != Reg;
1904     switch (UseOpc) {
1905     default: break;
1906     case ARM::SUBrr: {
1907       if (Commute)
1908         return false;
1909       ImmVal = -ImmVal;
1910       NewUseOpc = ARM::SUBri;
1911       // Fallthrough
1912     }
1913     case ARM::ADDrr:
1914     case ARM::ORRrr:
1915     case ARM::EORrr: {
1916       if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
1917         return false;
1918       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
1919       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
1920       switch (UseOpc) {
1921       default: break;
1922       case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
1923       case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
1924       case ARM::EORrr: NewUseOpc = ARM::EORri; break;
1925       }
1926       break;
1927     }
1928     case ARM::t2SUBrr: {
1929       if (Commute)
1930         return false;
1931       ImmVal = -ImmVal;
1932       NewUseOpc = ARM::t2SUBri;
1933       // Fallthrough
1934     }
1935     case ARM::t2ADDrr:
1936     case ARM::t2ORRrr:
1937     case ARM::t2EORrr: {
1938       if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
1939         return false;
1940       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
1941       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
1942       switch (UseOpc) {
1943       default: break;
1944       case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
1945       case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
1946       case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
1947       }
1948       break;
1949     }
1950     }
1951   }
1952   }
1953
1954   unsigned OpIdx = Commute ? 2 : 1;
1955   unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
1956   bool isKill = UseMI->getOperand(OpIdx).isKill();
1957   unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
1958   AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
1959                                       *UseMI, UseMI->getDebugLoc(),
1960                                       get(NewUseOpc), NewReg)
1961                               .addReg(Reg1, getKillRegState(isKill))
1962                               .addImm(SOImmValV1)));
1963   UseMI->setDesc(get(NewUseOpc));
1964   UseMI->getOperand(1).setReg(NewReg);
1965   UseMI->getOperand(1).setIsKill();
1966   UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
1967   DefMI->eraseFromParent();
1968   return true;
1969 }
1970
1971 unsigned
1972 ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1973                                  const MachineInstr *MI) const {
1974   if (!ItinData || ItinData->isEmpty())
1975     return 1;
1976
1977   const MCInstrDesc &Desc = MI->getDesc();
1978   unsigned Class = Desc.getSchedClass();
1979   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
1980   if (UOps)
1981     return UOps;
1982
1983   unsigned Opc = MI->getOpcode();
1984   switch (Opc) {
1985   default:
1986     llvm_unreachable("Unexpected multi-uops instruction!");
1987     break;
1988   case ARM::VLDMQIA:
1989   case ARM::VSTMQIA:
1990     return 2;
1991
1992   // The number of uOps for load / store multiple are determined by the number
1993   // registers.
1994   //
1995   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
1996   // same cycle. The scheduling for the first load / store must be done
1997   // separately by assuming the the address is not 64-bit aligned.
1998   //
1999   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
2000   // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
2001   // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
2002   case ARM::VLDMDIA:
2003   case ARM::VLDMDIA_UPD:
2004   case ARM::VLDMDDB_UPD:
2005   case ARM::VLDMSIA:
2006   case ARM::VLDMSIA_UPD:
2007   case ARM::VLDMSDB_UPD:
2008   case ARM::VSTMDIA:
2009   case ARM::VSTMDIA_UPD:
2010   case ARM::VSTMDDB_UPD:
2011   case ARM::VSTMSIA:
2012   case ARM::VSTMSIA_UPD:
2013   case ARM::VSTMSDB_UPD: {
2014     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
2015     return (NumRegs / 2) + (NumRegs % 2) + 1;
2016   }
2017
2018   case ARM::LDMIA_RET:
2019   case ARM::LDMIA:
2020   case ARM::LDMDA:
2021   case ARM::LDMDB:
2022   case ARM::LDMIB:
2023   case ARM::LDMIA_UPD:
2024   case ARM::LDMDA_UPD:
2025   case ARM::LDMDB_UPD:
2026   case ARM::LDMIB_UPD:
2027   case ARM::STMIA:
2028   case ARM::STMDA:
2029   case ARM::STMDB:
2030   case ARM::STMIB:
2031   case ARM::STMIA_UPD:
2032   case ARM::STMDA_UPD:
2033   case ARM::STMDB_UPD:
2034   case ARM::STMIB_UPD:
2035   case ARM::tLDMIA:
2036   case ARM::tLDMIA_UPD:
2037   case ARM::tSTMIA_UPD:
2038   case ARM::tPOP_RET:
2039   case ARM::tPOP:
2040   case ARM::tPUSH:
2041   case ARM::t2LDMIA_RET:
2042   case ARM::t2LDMIA:
2043   case ARM::t2LDMDB:
2044   case ARM::t2LDMIA_UPD:
2045   case ARM::t2LDMDB_UPD:
2046   case ARM::t2STMIA:
2047   case ARM::t2STMDB:
2048   case ARM::t2STMIA_UPD:
2049   case ARM::t2STMDB_UPD: {
2050     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
2051     if (Subtarget.isCortexA8()) {
2052       if (NumRegs < 4)
2053         return 2;
2054       // 4 registers would be issued: 2, 2.
2055       // 5 registers would be issued: 2, 2, 1.
2056       UOps = (NumRegs / 2);
2057       if (NumRegs % 2)
2058         ++UOps;
2059       return UOps;
2060     } else if (Subtarget.isCortexA9()) {
2061       UOps = (NumRegs / 2);
2062       // If there are odd number of registers or if it's not 64-bit aligned,
2063       // then it takes an extra AGU (Address Generation Unit) cycle.
2064       if ((NumRegs % 2) ||
2065           !MI->hasOneMemOperand() ||
2066           (*MI->memoperands_begin())->getAlignment() < 8)
2067         ++UOps;
2068       return UOps;
2069     } else {
2070       // Assume the worst.
2071       return NumRegs;
2072     }
2073   }
2074   }
2075 }
2076
2077 int
2078 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
2079                                   const MCInstrDesc &DefMCID,
2080                                   unsigned DefClass,
2081                                   unsigned DefIdx, unsigned DefAlign) const {
2082   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2083   if (RegNo <= 0)
2084     // Def is the address writeback.
2085     return ItinData->getOperandCycle(DefClass, DefIdx);
2086
2087   int DefCycle;
2088   if (Subtarget.isCortexA8()) {
2089     // (regno / 2) + (regno % 2) + 1
2090     DefCycle = RegNo / 2 + 1;
2091     if (RegNo % 2)
2092       ++DefCycle;
2093   } else if (Subtarget.isCortexA9()) {
2094     DefCycle = RegNo;
2095     bool isSLoad = false;
2096
2097     switch (DefMCID.getOpcode()) {
2098     default: break;
2099     case ARM::VLDMSIA:
2100     case ARM::VLDMSIA_UPD:
2101     case ARM::VLDMSDB_UPD:
2102       isSLoad = true;
2103       break;
2104     }
2105
2106     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2107     // then it takes an extra cycle.
2108     if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
2109       ++DefCycle;
2110   } else {
2111     // Assume the worst.
2112     DefCycle = RegNo + 2;
2113   }
2114
2115   return DefCycle;
2116 }
2117
2118 int
2119 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
2120                                  const MCInstrDesc &DefMCID,
2121                                  unsigned DefClass,
2122                                  unsigned DefIdx, unsigned DefAlign) const {
2123   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2124   if (RegNo <= 0)
2125     // Def is the address writeback.
2126     return ItinData->getOperandCycle(DefClass, DefIdx);
2127
2128   int DefCycle;
2129   if (Subtarget.isCortexA8()) {
2130     // 4 registers would be issued: 1, 2, 1.
2131     // 5 registers would be issued: 1, 2, 2.
2132     DefCycle = RegNo / 2;
2133     if (DefCycle < 1)
2134       DefCycle = 1;
2135     // Result latency is issue cycle + 2: E2.
2136     DefCycle += 2;
2137   } else if (Subtarget.isCortexA9()) {
2138     DefCycle = (RegNo / 2);
2139     // If there are odd number of registers or if it's not 64-bit aligned,
2140     // then it takes an extra AGU (Address Generation Unit) cycle.
2141     if ((RegNo % 2) || DefAlign < 8)
2142       ++DefCycle;
2143     // Result latency is AGU cycles + 2.
2144     DefCycle += 2;
2145   } else {
2146     // Assume the worst.
2147     DefCycle = RegNo + 2;
2148   }
2149
2150   return DefCycle;
2151 }
2152
2153 int
2154 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
2155                                   const MCInstrDesc &UseMCID,
2156                                   unsigned UseClass,
2157                                   unsigned UseIdx, unsigned UseAlign) const {
2158   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2159   if (RegNo <= 0)
2160     return ItinData->getOperandCycle(UseClass, UseIdx);
2161
2162   int UseCycle;
2163   if (Subtarget.isCortexA8()) {
2164     // (regno / 2) + (regno % 2) + 1
2165     UseCycle = RegNo / 2 + 1;
2166     if (RegNo % 2)
2167       ++UseCycle;
2168   } else if (Subtarget.isCortexA9()) {
2169     UseCycle = RegNo;
2170     bool isSStore = false;
2171
2172     switch (UseMCID.getOpcode()) {
2173     default: break;
2174     case ARM::VSTMSIA:
2175     case ARM::VSTMSIA_UPD:
2176     case ARM::VSTMSDB_UPD:
2177       isSStore = true;
2178       break;
2179     }
2180
2181     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2182     // then it takes an extra cycle.
2183     if ((isSStore && (RegNo % 2)) || UseAlign < 8)
2184       ++UseCycle;
2185   } else {
2186     // Assume the worst.
2187     UseCycle = RegNo + 2;
2188   }
2189
2190   return UseCycle;
2191 }
2192
2193 int
2194 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
2195                                  const MCInstrDesc &UseMCID,
2196                                  unsigned UseClass,
2197                                  unsigned UseIdx, unsigned UseAlign) const {
2198   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2199   if (RegNo <= 0)
2200     return ItinData->getOperandCycle(UseClass, UseIdx);
2201
2202   int UseCycle;
2203   if (Subtarget.isCortexA8()) {
2204     UseCycle = RegNo / 2;
2205     if (UseCycle < 2)
2206       UseCycle = 2;
2207     // Read in E3.
2208     UseCycle += 2;
2209   } else if (Subtarget.isCortexA9()) {
2210     UseCycle = (RegNo / 2);
2211     // If there are odd number of registers or if it's not 64-bit aligned,
2212     // then it takes an extra AGU (Address Generation Unit) cycle.
2213     if ((RegNo % 2) || UseAlign < 8)
2214       ++UseCycle;
2215   } else {
2216     // Assume the worst.
2217     UseCycle = 1;
2218   }
2219   return UseCycle;
2220 }
2221
2222 int
2223 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2224                                     const MCInstrDesc &DefMCID,
2225                                     unsigned DefIdx, unsigned DefAlign,
2226                                     const MCInstrDesc &UseMCID,
2227                                     unsigned UseIdx, unsigned UseAlign) const {
2228   unsigned DefClass = DefMCID.getSchedClass();
2229   unsigned UseClass = UseMCID.getSchedClass();
2230
2231   if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
2232     return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
2233
2234   // This may be a def / use of a variable_ops instruction, the operand
2235   // latency might be determinable dynamically. Let the target try to
2236   // figure it out.
2237   int DefCycle = -1;
2238   bool LdmBypass = false;
2239   switch (DefMCID.getOpcode()) {
2240   default:
2241     DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2242     break;
2243
2244   case ARM::VLDMDIA:
2245   case ARM::VLDMDIA_UPD:
2246   case ARM::VLDMDDB_UPD:
2247   case ARM::VLDMSIA:
2248   case ARM::VLDMSIA_UPD:
2249   case ARM::VLDMSDB_UPD:
2250     DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
2251     break;
2252
2253   case ARM::LDMIA_RET:
2254   case ARM::LDMIA:
2255   case ARM::LDMDA:
2256   case ARM::LDMDB:
2257   case ARM::LDMIB:
2258   case ARM::LDMIA_UPD:
2259   case ARM::LDMDA_UPD:
2260   case ARM::LDMDB_UPD:
2261   case ARM::LDMIB_UPD:
2262   case ARM::tLDMIA:
2263   case ARM::tLDMIA_UPD:
2264   case ARM::tPUSH:
2265   case ARM::t2LDMIA_RET:
2266   case ARM::t2LDMIA:
2267   case ARM::t2LDMDB:
2268   case ARM::t2LDMIA_UPD:
2269   case ARM::t2LDMDB_UPD:
2270     LdmBypass = 1;
2271     DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
2272     break;
2273   }
2274
2275   if (DefCycle == -1)
2276     // We can't seem to determine the result latency of the def, assume it's 2.
2277     DefCycle = 2;
2278
2279   int UseCycle = -1;
2280   switch (UseMCID.getOpcode()) {
2281   default:
2282     UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
2283     break;
2284
2285   case ARM::VSTMDIA:
2286   case ARM::VSTMDIA_UPD:
2287   case ARM::VSTMDDB_UPD:
2288   case ARM::VSTMSIA:
2289   case ARM::VSTMSIA_UPD:
2290   case ARM::VSTMSDB_UPD:
2291     UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
2292     break;
2293
2294   case ARM::STMIA:
2295   case ARM::STMDA:
2296   case ARM::STMDB:
2297   case ARM::STMIB:
2298   case ARM::STMIA_UPD:
2299   case ARM::STMDA_UPD:
2300   case ARM::STMDB_UPD:
2301   case ARM::STMIB_UPD:
2302   case ARM::tSTMIA_UPD:
2303   case ARM::tPOP_RET:
2304   case ARM::tPOP:
2305   case ARM::t2STMIA:
2306   case ARM::t2STMDB:
2307   case ARM::t2STMIA_UPD:
2308   case ARM::t2STMDB_UPD:
2309     UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
2310     break;
2311   }
2312
2313   if (UseCycle == -1)
2314     // Assume it's read in the first stage.
2315     UseCycle = 1;
2316
2317   UseCycle = DefCycle - UseCycle + 1;
2318   if (UseCycle > 0) {
2319     if (LdmBypass) {
2320       // It's a variable_ops instruction so we can't use DefIdx here. Just use
2321       // first def operand.
2322       if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
2323                                           UseClass, UseIdx))
2324         --UseCycle;
2325     } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
2326                                                UseClass, UseIdx)) {
2327       --UseCycle;
2328     }
2329   }
2330
2331   return UseCycle;
2332 }
2333
2334 int
2335 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2336                              const MachineInstr *DefMI, unsigned DefIdx,
2337                              const MachineInstr *UseMI, unsigned UseIdx) const {
2338   if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
2339       DefMI->isRegSequence() || DefMI->isImplicitDef())
2340     return 1;
2341
2342   const MCInstrDesc &DefMCID = DefMI->getDesc();
2343   if (!ItinData || ItinData->isEmpty())
2344     return DefMCID.mayLoad() ? 3 : 1;
2345
2346   const MCInstrDesc &UseMCID = UseMI->getDesc();
2347   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
2348   if (DefMO.getReg() == ARM::CPSR) {
2349     if (DefMI->getOpcode() == ARM::FMSTAT) {
2350       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
2351       return Subtarget.isCortexA9() ? 1 : 20;
2352     }
2353
2354     // CPSR set and branch can be paired in the same cycle.
2355     if (UseMCID.isBranch())
2356       return 0;
2357   }
2358
2359   unsigned DefAlign = DefMI->hasOneMemOperand()
2360     ? (*DefMI->memoperands_begin())->getAlignment() : 0;
2361   unsigned UseAlign = UseMI->hasOneMemOperand()
2362     ? (*UseMI->memoperands_begin())->getAlignment() : 0;
2363   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
2364                                   UseMCID, UseIdx, UseAlign);
2365
2366   if (Latency > 1 &&
2367       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2368     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2369     // variants are one cycle cheaper.
2370     switch (DefMCID.getOpcode()) {
2371     default: break;
2372     case ARM::LDRrs:
2373     case ARM::LDRBrs: {
2374       unsigned ShOpVal = DefMI->getOperand(3).getImm();
2375       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2376       if (ShImm == 0 ||
2377           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2378         --Latency;
2379       break;
2380     }
2381     case ARM::t2LDRs:
2382     case ARM::t2LDRBs:
2383     case ARM::t2LDRHs:
2384     case ARM::t2LDRSHs: {
2385       // Thumb2 mode: lsl only.
2386       unsigned ShAmt = DefMI->getOperand(3).getImm();
2387       if (ShAmt == 0 || ShAmt == 2)
2388         --Latency;
2389       break;
2390     }
2391     }
2392   }
2393
2394   if (DefAlign < 8 && Subtarget.isCortexA9())
2395     switch (DefMCID.getOpcode()) {
2396     default: break;
2397     case ARM::VLD1q8:
2398     case ARM::VLD1q16:
2399     case ARM::VLD1q32:
2400     case ARM::VLD1q64:
2401     case ARM::VLD1q8wb_fixed:
2402     case ARM::VLD1q16wb_fixed:
2403     case ARM::VLD1q32wb_fixed:
2404     case ARM::VLD1q64wb_fixed:
2405     case ARM::VLD1q8wb_register:
2406     case ARM::VLD1q16wb_register:
2407     case ARM::VLD1q32wb_register:
2408     case ARM::VLD1q64wb_register:
2409     case ARM::VLD2d8:
2410     case ARM::VLD2d16:
2411     case ARM::VLD2d32:
2412     case ARM::VLD2q8:
2413     case ARM::VLD2q16:
2414     case ARM::VLD2q32:
2415     case ARM::VLD2d8_UPD:
2416     case ARM::VLD2d16_UPD:
2417     case ARM::VLD2d32_UPD:
2418     case ARM::VLD2q8_UPD:
2419     case ARM::VLD2q16_UPD:
2420     case ARM::VLD2q32_UPD:
2421     case ARM::VLD3d8:
2422     case ARM::VLD3d16:
2423     case ARM::VLD3d32:
2424     case ARM::VLD1d64T:
2425     case ARM::VLD3d8_UPD:
2426     case ARM::VLD3d16_UPD:
2427     case ARM::VLD3d32_UPD:
2428     case ARM::VLD1d64Twb_fixed:
2429     case ARM::VLD1d64Twb_register:
2430     case ARM::VLD3q8_UPD:
2431     case ARM::VLD3q16_UPD:
2432     case ARM::VLD3q32_UPD:
2433     case ARM::VLD4d8:
2434     case ARM::VLD4d16:
2435     case ARM::VLD4d32:
2436     case ARM::VLD1d64Q:
2437     case ARM::VLD4d8_UPD:
2438     case ARM::VLD4d16_UPD:
2439     case ARM::VLD4d32_UPD:
2440     case ARM::VLD1d64Qwb_fixed:
2441     case ARM::VLD1d64Qwb_register:
2442     case ARM::VLD4q8_UPD:
2443     case ARM::VLD4q16_UPD:
2444     case ARM::VLD4q32_UPD:
2445     case ARM::VLD1DUPq8:
2446     case ARM::VLD1DUPq16:
2447     case ARM::VLD1DUPq32:
2448     case ARM::VLD1DUPq8wb_fixed:
2449     case ARM::VLD1DUPq16wb_fixed:
2450     case ARM::VLD1DUPq32wb_fixed:
2451     case ARM::VLD1DUPq8wb_register:
2452     case ARM::VLD1DUPq16wb_register:
2453     case ARM::VLD1DUPq32wb_register:
2454     case ARM::VLD2DUPd8:
2455     case ARM::VLD2DUPd16:
2456     case ARM::VLD2DUPd32:
2457     case ARM::VLD2DUPd8_UPD:
2458     case ARM::VLD2DUPd16_UPD:
2459     case ARM::VLD2DUPd32_UPD:
2460     case ARM::VLD4DUPd8:
2461     case ARM::VLD4DUPd16:
2462     case ARM::VLD4DUPd32:
2463     case ARM::VLD4DUPd8_UPD:
2464     case ARM::VLD4DUPd16_UPD:
2465     case ARM::VLD4DUPd32_UPD:
2466     case ARM::VLD1LNd8:
2467     case ARM::VLD1LNd16:
2468     case ARM::VLD1LNd32:
2469     case ARM::VLD1LNd8_UPD:
2470     case ARM::VLD1LNd16_UPD:
2471     case ARM::VLD1LNd32_UPD:
2472     case ARM::VLD2LNd8:
2473     case ARM::VLD2LNd16:
2474     case ARM::VLD2LNd32:
2475     case ARM::VLD2LNq16:
2476     case ARM::VLD2LNq32:
2477     case ARM::VLD2LNd8_UPD:
2478     case ARM::VLD2LNd16_UPD:
2479     case ARM::VLD2LNd32_UPD:
2480     case ARM::VLD2LNq16_UPD:
2481     case ARM::VLD2LNq32_UPD:
2482     case ARM::VLD4LNd8:
2483     case ARM::VLD4LNd16:
2484     case ARM::VLD4LNd32:
2485     case ARM::VLD4LNq16:
2486     case ARM::VLD4LNq32:
2487     case ARM::VLD4LNd8_UPD:
2488     case ARM::VLD4LNd16_UPD:
2489     case ARM::VLD4LNd32_UPD:
2490     case ARM::VLD4LNq16_UPD:
2491     case ARM::VLD4LNq32_UPD:
2492       // If the address is not 64-bit aligned, the latencies of these
2493       // instructions increases by one.
2494       ++Latency;
2495       break;
2496     }
2497
2498   return Latency;
2499 }
2500
2501 int
2502 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2503                                     SDNode *DefNode, unsigned DefIdx,
2504                                     SDNode *UseNode, unsigned UseIdx) const {
2505   if (!DefNode->isMachineOpcode())
2506     return 1;
2507
2508   const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
2509
2510   if (isZeroCost(DefMCID.Opcode))
2511     return 0;
2512
2513   if (!ItinData || ItinData->isEmpty())
2514     return DefMCID.mayLoad() ? 3 : 1;
2515
2516   if (!UseNode->isMachineOpcode()) {
2517     int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
2518     if (Subtarget.isCortexA9())
2519       return Latency <= 2 ? 1 : Latency - 1;
2520     else
2521       return Latency <= 3 ? 1 : Latency - 2;
2522   }
2523
2524   const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
2525   const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
2526   unsigned DefAlign = !DefMN->memoperands_empty()
2527     ? (*DefMN->memoperands_begin())->getAlignment() : 0;
2528   const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
2529   unsigned UseAlign = !UseMN->memoperands_empty()
2530     ? (*UseMN->memoperands_begin())->getAlignment() : 0;
2531   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
2532                                   UseMCID, UseIdx, UseAlign);
2533
2534   if (Latency > 1 &&
2535       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2536     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2537     // variants are one cycle cheaper.
2538     switch (DefMCID.getOpcode()) {
2539     default: break;
2540     case ARM::LDRrs:
2541     case ARM::LDRBrs: {
2542       unsigned ShOpVal =
2543         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2544       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2545       if (ShImm == 0 ||
2546           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2547         --Latency;
2548       break;
2549     }
2550     case ARM::t2LDRs:
2551     case ARM::t2LDRBs:
2552     case ARM::t2LDRHs:
2553     case ARM::t2LDRSHs: {
2554       // Thumb2 mode: lsl only.
2555       unsigned ShAmt =
2556         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2557       if (ShAmt == 0 || ShAmt == 2)
2558         --Latency;
2559       break;
2560     }
2561     }
2562   }
2563
2564   if (DefAlign < 8 && Subtarget.isCortexA9())
2565     switch (DefMCID.getOpcode()) {
2566     default: break;
2567     case ARM::VLD1q8Pseudo:
2568     case ARM::VLD1q16Pseudo:
2569     case ARM::VLD1q32Pseudo:
2570     case ARM::VLD1q64Pseudo:
2571     case ARM::VLD1q8PseudoWB_register:
2572     case ARM::VLD1q16PseudoWB_register:
2573     case ARM::VLD1q32PseudoWB_register:
2574     case ARM::VLD1q64PseudoWB_register:
2575     case ARM::VLD1q8PseudoWB_fixed:
2576     case ARM::VLD1q16PseudoWB_fixed:
2577     case ARM::VLD1q32PseudoWB_fixed:
2578     case ARM::VLD1q64PseudoWB_fixed:
2579     case ARM::VLD2d8Pseudo:
2580     case ARM::VLD2d16Pseudo:
2581     case ARM::VLD2d32Pseudo:
2582     case ARM::VLD2q8Pseudo:
2583     case ARM::VLD2q16Pseudo:
2584     case ARM::VLD2q32Pseudo:
2585     case ARM::VLD2d8Pseudo_UPD:
2586     case ARM::VLD2d16Pseudo_UPD:
2587     case ARM::VLD2d32Pseudo_UPD:
2588     case ARM::VLD2q8Pseudo_UPD:
2589     case ARM::VLD2q16Pseudo_UPD:
2590     case ARM::VLD2q32Pseudo_UPD:
2591     case ARM::VLD3d8Pseudo:
2592     case ARM::VLD3d16Pseudo:
2593     case ARM::VLD3d32Pseudo:
2594     case ARM::VLD1d64TPseudo:
2595     case ARM::VLD3d8Pseudo_UPD:
2596     case ARM::VLD3d16Pseudo_UPD:
2597     case ARM::VLD3d32Pseudo_UPD:
2598     case ARM::VLD3q8Pseudo_UPD:
2599     case ARM::VLD3q16Pseudo_UPD:
2600     case ARM::VLD3q32Pseudo_UPD:
2601     case ARM::VLD3q8oddPseudo:
2602     case ARM::VLD3q16oddPseudo:
2603     case ARM::VLD3q32oddPseudo:
2604     case ARM::VLD3q8oddPseudo_UPD:
2605     case ARM::VLD3q16oddPseudo_UPD:
2606     case ARM::VLD3q32oddPseudo_UPD:
2607     case ARM::VLD4d8Pseudo:
2608     case ARM::VLD4d16Pseudo:
2609     case ARM::VLD4d32Pseudo:
2610     case ARM::VLD1d64QPseudo:
2611     case ARM::VLD4d8Pseudo_UPD:
2612     case ARM::VLD4d16Pseudo_UPD:
2613     case ARM::VLD4d32Pseudo_UPD:
2614     case ARM::VLD4q8Pseudo_UPD:
2615     case ARM::VLD4q16Pseudo_UPD:
2616     case ARM::VLD4q32Pseudo_UPD:
2617     case ARM::VLD4q8oddPseudo:
2618     case ARM::VLD4q16oddPseudo:
2619     case ARM::VLD4q32oddPseudo:
2620     case ARM::VLD4q8oddPseudo_UPD:
2621     case ARM::VLD4q16oddPseudo_UPD:
2622     case ARM::VLD4q32oddPseudo_UPD:
2623     case ARM::VLD1DUPq8Pseudo:
2624     case ARM::VLD1DUPq16Pseudo:
2625     case ARM::VLD1DUPq32Pseudo:
2626     case ARM::VLD1DUPq8PseudoWB_fixed:
2627     case ARM::VLD1DUPq16PseudoWB_fixed:
2628     case ARM::VLD1DUPq32PseudoWB_fixed:
2629     case ARM::VLD1DUPq8PseudoWB_register:
2630     case ARM::VLD1DUPq16PseudoWB_register:
2631     case ARM::VLD1DUPq32PseudoWB_register:
2632     case ARM::VLD2DUPd8Pseudo:
2633     case ARM::VLD2DUPd16Pseudo:
2634     case ARM::VLD2DUPd32Pseudo:
2635     case ARM::VLD2DUPd8Pseudo_UPD:
2636     case ARM::VLD2DUPd16Pseudo_UPD:
2637     case ARM::VLD2DUPd32Pseudo_UPD:
2638     case ARM::VLD4DUPd8Pseudo:
2639     case ARM::VLD4DUPd16Pseudo:
2640     case ARM::VLD4DUPd32Pseudo:
2641     case ARM::VLD4DUPd8Pseudo_UPD:
2642     case ARM::VLD4DUPd16Pseudo_UPD:
2643     case ARM::VLD4DUPd32Pseudo_UPD:
2644     case ARM::VLD1LNq8Pseudo:
2645     case ARM::VLD1LNq16Pseudo:
2646     case ARM::VLD1LNq32Pseudo:
2647     case ARM::VLD1LNq8Pseudo_UPD:
2648     case ARM::VLD1LNq16Pseudo_UPD:
2649     case ARM::VLD1LNq32Pseudo_UPD:
2650     case ARM::VLD2LNd8Pseudo:
2651     case ARM::VLD2LNd16Pseudo:
2652     case ARM::VLD2LNd32Pseudo:
2653     case ARM::VLD2LNq16Pseudo:
2654     case ARM::VLD2LNq32Pseudo:
2655     case ARM::VLD2LNd8Pseudo_UPD:
2656     case ARM::VLD2LNd16Pseudo_UPD:
2657     case ARM::VLD2LNd32Pseudo_UPD:
2658     case ARM::VLD2LNq16Pseudo_UPD:
2659     case ARM::VLD2LNq32Pseudo_UPD:
2660     case ARM::VLD4LNd8Pseudo:
2661     case ARM::VLD4LNd16Pseudo:
2662     case ARM::VLD4LNd32Pseudo:
2663     case ARM::VLD4LNq16Pseudo:
2664     case ARM::VLD4LNq32Pseudo:
2665     case ARM::VLD4LNd8Pseudo_UPD:
2666     case ARM::VLD4LNd16Pseudo_UPD:
2667     case ARM::VLD4LNd32Pseudo_UPD:
2668     case ARM::VLD4LNq16Pseudo_UPD:
2669     case ARM::VLD4LNq32Pseudo_UPD:
2670       // If the address is not 64-bit aligned, the latencies of these
2671       // instructions increases by one.
2672       ++Latency;
2673       break;
2674     }
2675
2676   return Latency;
2677 }
2678
2679 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2680                                       const MachineInstr *MI,
2681                                       unsigned *PredCost) const {
2682   if (MI->isCopyLike() || MI->isInsertSubreg() ||
2683       MI->isRegSequence() || MI->isImplicitDef())
2684     return 1;
2685
2686   if (!ItinData || ItinData->isEmpty())
2687     return 1;
2688
2689   const MCInstrDesc &MCID = MI->getDesc();
2690   unsigned Class = MCID.getSchedClass();
2691   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
2692   if (PredCost && MCID.hasImplicitDefOfPhysReg(ARM::CPSR))
2693     // When predicated, CPSR is an additional source operand for CPSR updating
2694     // instructions, this apparently increases their latencies.
2695     *PredCost = 1;
2696   if (UOps)
2697     return ItinData->getStageLatency(Class);
2698   return getNumMicroOps(ItinData, MI);
2699 }
2700
2701 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2702                                       SDNode *Node) const {
2703   if (!Node->isMachineOpcode())
2704     return 1;
2705
2706   if (!ItinData || ItinData->isEmpty())
2707     return 1;
2708
2709   unsigned Opcode = Node->getMachineOpcode();
2710   switch (Opcode) {
2711   default:
2712     return ItinData->getStageLatency(get(Opcode).getSchedClass());
2713   case ARM::VLDMQIA:
2714   case ARM::VSTMQIA:
2715     return 2;
2716   }
2717 }
2718
2719 bool ARMBaseInstrInfo::
2720 hasHighOperandLatency(const InstrItineraryData *ItinData,
2721                       const MachineRegisterInfo *MRI,
2722                       const MachineInstr *DefMI, unsigned DefIdx,
2723                       const MachineInstr *UseMI, unsigned UseIdx) const {
2724   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2725   unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
2726   if (Subtarget.isCortexA8() &&
2727       (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
2728     // CortexA8 VFP instructions are not pipelined.
2729     return true;
2730
2731   // Hoist VFP / NEON instructions with 4 or higher latency.
2732   int Latency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
2733   if (Latency <= 3)
2734     return false;
2735   return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
2736          UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
2737 }
2738
2739 bool ARMBaseInstrInfo::
2740 hasLowDefLatency(const InstrItineraryData *ItinData,
2741                  const MachineInstr *DefMI, unsigned DefIdx) const {
2742   if (!ItinData || ItinData->isEmpty())
2743     return false;
2744
2745   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2746   if (DDomain == ARMII::DomainGeneral) {
2747     unsigned DefClass = DefMI->getDesc().getSchedClass();
2748     int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2749     return (DefCycle != -1 && DefCycle <= 2);
2750   }
2751   return false;
2752 }
2753
2754 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr *MI,
2755                                          StringRef &ErrInfo) const {
2756   if (convertAddSubFlagsOpcode(MI->getOpcode())) {
2757     ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
2758     return false;
2759   }
2760   return true;
2761 }
2762
2763 bool
2764 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
2765                                      unsigned &AddSubOpc,
2766                                      bool &NegAcc, bool &HasLane) const {
2767   DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
2768   if (I == MLxEntryMap.end())
2769     return false;
2770
2771   const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
2772   MulOpc = Entry.MulOpc;
2773   AddSubOpc = Entry.AddSubOpc;
2774   NegAcc = Entry.NegAcc;
2775   HasLane = Entry.HasLane;
2776   return true;
2777 }
2778
2779 //===----------------------------------------------------------------------===//
2780 // Execution domains.
2781 //===----------------------------------------------------------------------===//
2782 //
2783 // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
2784 // and some can go down both.  The vmov instructions go down the VFP pipeline,
2785 // but they can be changed to vorr equivalents that are executed by the NEON
2786 // pipeline.
2787 //
2788 // We use the following execution domain numbering:
2789 //
2790 enum ARMExeDomain {
2791   ExeGeneric = 0,
2792   ExeVFP = 1,
2793   ExeNEON = 2
2794 };
2795 //
2796 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
2797 //
2798 std::pair<uint16_t, uint16_t>
2799 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr *MI) const {
2800   // VMOVD is a VFP instruction, but can be changed to NEON if it isn't
2801   // predicated.
2802   if (MI->getOpcode() == ARM::VMOVD && !isPredicated(MI))
2803     return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
2804
2805   // No other instructions can be swizzled, so just determine their domain.
2806   unsigned Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
2807
2808   if (Domain & ARMII::DomainNEON)
2809     return std::make_pair(ExeNEON, 0);
2810
2811   // Certain instructions can go either way on Cortex-A8.
2812   // Treat them as NEON instructions.
2813   if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
2814     return std::make_pair(ExeNEON, 0);
2815
2816   if (Domain & ARMII::DomainVFP)
2817     return std::make_pair(ExeVFP, 0);
2818
2819   return std::make_pair(ExeGeneric, 0);
2820 }
2821
2822 void
2823 ARMBaseInstrInfo::setExecutionDomain(MachineInstr *MI, unsigned Domain) const {
2824   // We only know how to change VMOVD into VORR.
2825   assert(MI->getOpcode() == ARM::VMOVD && "Can only swizzle VMOVD");
2826   if (Domain != ExeNEON)
2827     return;
2828
2829   // Zap the predicate operands.
2830   assert(!isPredicated(MI) && "Cannot predicate a VORRd");
2831   MI->RemoveOperand(3);
2832   MI->RemoveOperand(2);
2833
2834   // Change to a VORRd which requires two identical use operands.
2835   MI->setDesc(get(ARM::VORRd));
2836
2837   // Add the extra source operand and new predicates.
2838   // This will go before any implicit ops.
2839   AddDefaultPred(MachineInstrBuilder(MI).addOperand(MI->getOperand(1)));
2840 }