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