8edc0e7f12154dbf5024a1e27ae5cebec2321ba1
[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 "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMHazardRecognizer.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMRegisterInfo.h"
21 #include "ARMGenInstrInfo.inc"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalValue.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/PseudoSourceValue.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/ADT/STLExtras.h"
38 using namespace llvm;
39
40 static cl::opt<bool>
41 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
42                cl::desc("Enable ARM 2-addr to 3-addr conv"));
43
44
45 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
46 struct ARM_MLxEntry {
47   unsigned MLxOpc;     // MLA / MLS opcode
48   unsigned MulOpc;     // Expanded multiplication opcode
49   unsigned AddSubOpc;  // Expanded add / sub opcode
50   bool NegAcc;         // True if the acc is negated before the add / sub.
51   bool HasLane;        // True if instruction has an extra "lane" operand.
52 };
53
54 static const ARM_MLxEntry ARM_MLxTable[] = {
55   // MLxOpc,          MulOpc,           AddSubOpc,       NegAcc, HasLane
56   // fp scalar ops
57   { ARM::VMLAS,       ARM::VMULS,       ARM::VADDS,      false,  false },
58   { ARM::VMLSS,       ARM::VMULS,       ARM::VSUBS,      false,  false },
59   { ARM::VMLAD,       ARM::VMULD,       ARM::VADDD,      false,  false },
60   { ARM::VMLSD,       ARM::VMULD,       ARM::VSUBD,      false,  false },
61   { ARM::VNMLAS,      ARM::VNMULS,      ARM::VSUBS,      true,   false },
62   { ARM::VNMLSS,      ARM::VMULS,       ARM::VSUBS,      true,   false },
63   { ARM::VNMLAD,      ARM::VNMULD,      ARM::VSUBD,      true,   false },
64   { ARM::VNMLSD,      ARM::VMULD,       ARM::VSUBD,      true,   false },
65
66   // fp SIMD ops
67   { ARM::VMLAfd,      ARM::VMULfd,      ARM::VADDfd,     false,  false },
68   { ARM::VMLSfd,      ARM::VMULfd,      ARM::VSUBfd,     false,  false },
69   { ARM::VMLAfq,      ARM::VMULfq,      ARM::VADDfq,     false,  false },
70   { ARM::VMLSfq,      ARM::VMULfq,      ARM::VSUBfq,     false,  false },
71   { ARM::VMLAslfd,    ARM::VMULslfd,    ARM::VADDfd,     false,  true  },
72   { ARM::VMLSslfd,    ARM::VMULslfd,    ARM::VSUBfd,     false,  true  },
73   { ARM::VMLAslfq,    ARM::VMULslfq,    ARM::VADDfq,     false,  true  },
74   { ARM::VMLSslfq,    ARM::VMULslfq,    ARM::VSUBfq,     false,  true  },
75 };
76
77 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
78   : TargetInstrInfoImpl(ARMInsts, array_lengthof(ARMInsts)),
79     Subtarget(STI) {
80   for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
81     if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
82       assert(false && "Duplicated entries?");
83     MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
84     MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
85   }
86 }
87
88 ScheduleHazardRecognizer *ARMBaseInstrInfo::
89 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II) const {
90   if (Subtarget.isThumb2() || Subtarget.hasVFP2())
91     return (ScheduleHazardRecognizer *)
92       new ARMHazardRecognizer(II, *this, getRegisterInfo(), Subtarget);
93   return TargetInstrInfoImpl::CreateTargetPostRAHazardRecognizer(II);
94 }
95
96 MachineInstr *
97 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
98                                         MachineBasicBlock::iterator &MBBI,
99                                         LiveVariables *LV) const {
100   // FIXME: Thumb2 support.
101
102   if (!EnableARM3Addr)
103     return NULL;
104
105   MachineInstr *MI = MBBI;
106   MachineFunction &MF = *MI->getParent()->getParent();
107   uint64_t TSFlags = MI->getDesc().TSFlags;
108   bool isPre = false;
109   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
110   default: return NULL;
111   case ARMII::IndexModePre:
112     isPre = true;
113     break;
114   case ARMII::IndexModePost:
115     break;
116   }
117
118   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
119   // operation.
120   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
121   if (MemOpc == 0)
122     return NULL;
123
124   MachineInstr *UpdateMI = NULL;
125   MachineInstr *MemMI = NULL;
126   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
127   const TargetInstrDesc &TID = MI->getDesc();
128   unsigned NumOps = TID.getNumOperands();
129   bool isLoad = !TID.mayStore();
130   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
131   const MachineOperand &Base = MI->getOperand(2);
132   const MachineOperand &Offset = MI->getOperand(NumOps-3);
133   unsigned WBReg = WB.getReg();
134   unsigned BaseReg = Base.getReg();
135   unsigned OffReg = Offset.getReg();
136   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
137   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
138   switch (AddrMode) {
139   default:
140     assert(false && "Unknown indexed op!");
141     return NULL;
142   case ARMII::AddrMode2: {
143     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
144     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
145     if (OffReg == 0) {
146       if (ARM_AM::getSOImmVal(Amt) == -1)
147         // Can't encode it in a so_imm operand. This transformation will
148         // add more than 1 instruction. Abandon!
149         return NULL;
150       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
151                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
152         .addReg(BaseReg).addImm(Amt)
153         .addImm(Pred).addReg(0).addReg(0);
154     } else if (Amt != 0) {
155       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
156       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
157       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
158                          get(isSub ? ARM::SUBrs : ARM::ADDrs), WBReg)
159         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
160         .addImm(Pred).addReg(0).addReg(0);
161     } else
162       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
163                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
164         .addReg(BaseReg).addReg(OffReg)
165         .addImm(Pred).addReg(0).addReg(0);
166     break;
167   }
168   case ARMII::AddrMode3 : {
169     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
170     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
171     if (OffReg == 0)
172       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
173       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
174                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
175         .addReg(BaseReg).addImm(Amt)
176         .addImm(Pred).addReg(0).addReg(0);
177     else
178       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
179                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
180         .addReg(BaseReg).addReg(OffReg)
181         .addImm(Pred).addReg(0).addReg(0);
182     break;
183   }
184   }
185
186   std::vector<MachineInstr*> NewMIs;
187   if (isPre) {
188     if (isLoad)
189       MemMI = BuildMI(MF, MI->getDebugLoc(),
190                       get(MemOpc), MI->getOperand(0).getReg())
191         .addReg(WBReg).addImm(0).addImm(Pred);
192     else
193       MemMI = BuildMI(MF, MI->getDebugLoc(),
194                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
195         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
196     NewMIs.push_back(MemMI);
197     NewMIs.push_back(UpdateMI);
198   } else {
199     if (isLoad)
200       MemMI = BuildMI(MF, MI->getDebugLoc(),
201                       get(MemOpc), MI->getOperand(0).getReg())
202         .addReg(BaseReg).addImm(0).addImm(Pred);
203     else
204       MemMI = BuildMI(MF, MI->getDebugLoc(),
205                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
206         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
207     if (WB.isDead())
208       UpdateMI->getOperand(0).setIsDead();
209     NewMIs.push_back(UpdateMI);
210     NewMIs.push_back(MemMI);
211   }
212
213   // Transfer LiveVariables states, kill / dead info.
214   if (LV) {
215     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
216       MachineOperand &MO = MI->getOperand(i);
217       if (MO.isReg() && MO.getReg() &&
218           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
219         unsigned Reg = MO.getReg();
220
221         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
222         if (MO.isDef()) {
223           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
224           if (MO.isDead())
225             LV->addVirtualRegisterDead(Reg, NewMI);
226         }
227         if (MO.isUse() && MO.isKill()) {
228           for (unsigned j = 0; j < 2; ++j) {
229             // Look at the two new MI's in reverse order.
230             MachineInstr *NewMI = NewMIs[j];
231             if (!NewMI->readsRegister(Reg))
232               continue;
233             LV->addVirtualRegisterKilled(Reg, NewMI);
234             if (VI.removeKill(MI))
235               VI.Kills.push_back(NewMI);
236             break;
237           }
238         }
239       }
240     }
241   }
242
243   MFI->insert(MBBI, NewMIs[1]);
244   MFI->insert(MBBI, NewMIs[0]);
245   return NewMIs[0];
246 }
247
248 // Branch analysis.
249 bool
250 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
251                                 MachineBasicBlock *&FBB,
252                                 SmallVectorImpl<MachineOperand> &Cond,
253                                 bool AllowModify) const {
254   // If the block has no terminators, it just falls into the block after it.
255   MachineBasicBlock::iterator I = MBB.end();
256   if (I == MBB.begin())
257     return false;
258   --I;
259   while (I->isDebugValue()) {
260     if (I == MBB.begin())
261       return false;
262     --I;
263   }
264   if (!isUnpredicatedTerminator(I))
265     return false;
266
267   // Get the last instruction in the block.
268   MachineInstr *LastInst = I;
269
270   // If there is only one terminator instruction, process it.
271   unsigned LastOpc = LastInst->getOpcode();
272   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
273     if (isUncondBranchOpcode(LastOpc)) {
274       TBB = LastInst->getOperand(0).getMBB();
275       return false;
276     }
277     if (isCondBranchOpcode(LastOpc)) {
278       // Block ends with fall-through condbranch.
279       TBB = LastInst->getOperand(0).getMBB();
280       Cond.push_back(LastInst->getOperand(1));
281       Cond.push_back(LastInst->getOperand(2));
282       return false;
283     }
284     return true;  // Can't handle indirect branch.
285   }
286
287   // Get the instruction before it if it is a terminator.
288   MachineInstr *SecondLastInst = I;
289   unsigned SecondLastOpc = SecondLastInst->getOpcode();
290
291   // If AllowModify is true and the block ends with two or more unconditional
292   // branches, delete all but the first unconditional branch.
293   if (AllowModify && isUncondBranchOpcode(LastOpc)) {
294     while (isUncondBranchOpcode(SecondLastOpc)) {
295       LastInst->eraseFromParent();
296       LastInst = SecondLastInst;
297       LastOpc = LastInst->getOpcode();
298       if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
299         // Return now the only terminator is an unconditional branch.
300         TBB = LastInst->getOperand(0).getMBB();
301         return false;
302       } else {
303         SecondLastInst = I;
304         SecondLastOpc = SecondLastInst->getOpcode();
305       }
306     }
307   }
308
309   // If there are three terminators, we don't know what sort of block this is.
310   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
311     return true;
312
313   // If the block ends with a B and a Bcc, handle it.
314   if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
315     TBB =  SecondLastInst->getOperand(0).getMBB();
316     Cond.push_back(SecondLastInst->getOperand(1));
317     Cond.push_back(SecondLastInst->getOperand(2));
318     FBB = LastInst->getOperand(0).getMBB();
319     return false;
320   }
321
322   // If the block ends with two unconditional branches, handle it.  The second
323   // one is not executed, so remove it.
324   if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
325     TBB = SecondLastInst->getOperand(0).getMBB();
326     I = LastInst;
327     if (AllowModify)
328       I->eraseFromParent();
329     return false;
330   }
331
332   // ...likewise if it ends with a branch table followed by an unconditional
333   // branch. The branch folder can create these, and we must get rid of them for
334   // correctness of Thumb constant islands.
335   if ((isJumpTableBranchOpcode(SecondLastOpc) ||
336        isIndirectBranchOpcode(SecondLastOpc)) &&
337       isUncondBranchOpcode(LastOpc)) {
338     I = LastInst;
339     if (AllowModify)
340       I->eraseFromParent();
341     return true;
342   }
343
344   // Otherwise, can't handle this.
345   return true;
346 }
347
348
349 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
350   MachineBasicBlock::iterator I = MBB.end();
351   if (I == MBB.begin()) return 0;
352   --I;
353   while (I->isDebugValue()) {
354     if (I == MBB.begin())
355       return 0;
356     --I;
357   }
358   if (!isUncondBranchOpcode(I->getOpcode()) &&
359       !isCondBranchOpcode(I->getOpcode()))
360     return 0;
361
362   // Remove the branch.
363   I->eraseFromParent();
364
365   I = MBB.end();
366
367   if (I == MBB.begin()) return 1;
368   --I;
369   if (!isCondBranchOpcode(I->getOpcode()))
370     return 1;
371
372   // Remove the branch.
373   I->eraseFromParent();
374   return 2;
375 }
376
377 unsigned
378 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
379                                MachineBasicBlock *FBB,
380                                const SmallVectorImpl<MachineOperand> &Cond,
381                                DebugLoc DL) const {
382   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
383   int BOpc   = !AFI->isThumbFunction()
384     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
385   int BccOpc = !AFI->isThumbFunction()
386     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
387
388   // Shouldn't be a fall through.
389   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
390   assert((Cond.size() == 2 || Cond.size() == 0) &&
391          "ARM branch conditions have two components!");
392
393   if (FBB == 0) {
394     if (Cond.empty()) // Unconditional branch?
395       BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
396     else
397       BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
398         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
399     return 1;
400   }
401
402   // Two-way conditional branch.
403   BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
404     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
405   BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
406   return 2;
407 }
408
409 bool ARMBaseInstrInfo::
410 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
411   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
412   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
413   return false;
414 }
415
416 bool ARMBaseInstrInfo::
417 PredicateInstruction(MachineInstr *MI,
418                      const SmallVectorImpl<MachineOperand> &Pred) const {
419   unsigned Opc = MI->getOpcode();
420   if (isUncondBranchOpcode(Opc)) {
421     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
422     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
423     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
424     return true;
425   }
426
427   int PIdx = MI->findFirstPredOperandIdx();
428   if (PIdx != -1) {
429     MachineOperand &PMO = MI->getOperand(PIdx);
430     PMO.setImm(Pred[0].getImm());
431     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
432     return true;
433   }
434   return false;
435 }
436
437 bool ARMBaseInstrInfo::
438 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
439                   const SmallVectorImpl<MachineOperand> &Pred2) const {
440   if (Pred1.size() > 2 || Pred2.size() > 2)
441     return false;
442
443   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
444   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
445   if (CC1 == CC2)
446     return true;
447
448   switch (CC1) {
449   default:
450     return false;
451   case ARMCC::AL:
452     return true;
453   case ARMCC::HS:
454     return CC2 == ARMCC::HI;
455   case ARMCC::LS:
456     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
457   case ARMCC::GE:
458     return CC2 == ARMCC::GT;
459   case ARMCC::LE:
460     return CC2 == ARMCC::LT;
461   }
462 }
463
464 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
465                                     std::vector<MachineOperand> &Pred) const {
466   // FIXME: This confuses implicit_def with optional CPSR def.
467   const TargetInstrDesc &TID = MI->getDesc();
468   if (!TID.getImplicitDefs() && !TID.hasOptionalDef())
469     return false;
470
471   bool Found = false;
472   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
473     const MachineOperand &MO = MI->getOperand(i);
474     if (MO.isReg() && MO.getReg() == ARM::CPSR) {
475       Pred.push_back(MO);
476       Found = true;
477     }
478   }
479
480   return Found;
481 }
482
483 /// isPredicable - Return true if the specified instruction can be predicated.
484 /// By default, this returns true for every instruction with a
485 /// PredicateOperand.
486 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
487   const TargetInstrDesc &TID = MI->getDesc();
488   if (!TID.isPredicable())
489     return false;
490
491   if ((TID.TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) {
492     ARMFunctionInfo *AFI =
493       MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
494     return AFI->isThumb2Function();
495   }
496   return true;
497 }
498
499 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
500 LLVM_ATTRIBUTE_NOINLINE
501 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
502                                 unsigned JTI);
503 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
504                                 unsigned JTI) {
505   assert(JTI < JT.size());
506   return JT[JTI].MBBs.size();
507 }
508
509 /// GetInstSize - Return the size of the specified MachineInstr.
510 ///
511 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
512   const MachineBasicBlock &MBB = *MI->getParent();
513   const MachineFunction *MF = MBB.getParent();
514   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
515
516   // Basic size info comes from the TSFlags field.
517   const TargetInstrDesc &TID = MI->getDesc();
518   uint64_t TSFlags = TID.TSFlags;
519
520   unsigned Opc = MI->getOpcode();
521   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
522   default: {
523     // If this machine instr is an inline asm, measure it.
524     if (MI->getOpcode() == ARM::INLINEASM)
525       return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
526     if (MI->isLabel())
527       return 0;
528     switch (Opc) {
529     default:
530       llvm_unreachable("Unknown or unset size field for instr!");
531     case TargetOpcode::IMPLICIT_DEF:
532     case TargetOpcode::KILL:
533     case TargetOpcode::PROLOG_LABEL:
534     case TargetOpcode::EH_LABEL:
535     case TargetOpcode::DBG_VALUE:
536       return 0;
537     }
538     break;
539   }
540   case ARMII::Size8Bytes: return 8;          // ARM instruction x 2.
541   case ARMII::Size4Bytes: return 4;          // ARM / Thumb2 instruction.
542   case ARMII::Size2Bytes: return 2;          // Thumb1 instruction.
543   case ARMII::SizeSpecial: {
544     switch (Opc) {
545     case ARM::MOVi32imm:
546     case ARM::t2MOVi32imm:
547       return 8;
548     case ARM::CONSTPOOL_ENTRY:
549       // If this machine instr is a constant pool entry, its size is recorded as
550       // operand #2.
551       return MI->getOperand(2).getImm();
552     case ARM::Int_eh_sjlj_longjmp:
553       return 16;
554     case ARM::tInt_eh_sjlj_longjmp:
555       return 10;
556     case ARM::Int_eh_sjlj_setjmp:
557     case ARM::Int_eh_sjlj_setjmp_nofp:
558       return 20;
559     case ARM::tInt_eh_sjlj_setjmp:
560     case ARM::t2Int_eh_sjlj_setjmp:
561     case ARM::t2Int_eh_sjlj_setjmp_nofp:
562       return 12;
563     case ARM::BR_JTr:
564     case ARM::BR_JTm:
565     case ARM::BR_JTadd:
566     case ARM::tBR_JTr:
567     case ARM::t2BR_JT:
568     case ARM::t2TBB_JT:
569     case ARM::t2TBH_JT: {
570       // These are jumptable branches, i.e. a branch followed by an inlined
571       // jumptable. The size is 4 + 4 * number of entries. For TBB, each
572       // entry is one byte; TBH two byte each.
573       unsigned EntrySize = (Opc == ARM::t2TBB_JT)
574         ? 1 : ((Opc == ARM::t2TBH_JT) ? 2 : 4);
575       unsigned NumOps = TID.getNumOperands();
576       MachineOperand JTOP =
577         MI->getOperand(NumOps - (TID.isPredicable() ? 3 : 2));
578       unsigned JTI = JTOP.getIndex();
579       const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
580       assert(MJTI != 0);
581       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
582       assert(JTI < JT.size());
583       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
584       // 4 aligned. The assembler / linker may add 2 byte padding just before
585       // the JT entries.  The size does not include this padding; the
586       // constant islands pass does separate bookkeeping for it.
587       // FIXME: If we know the size of the function is less than (1 << 16) *2
588       // bytes, we can use 16-bit entries instead. Then there won't be an
589       // alignment issue.
590       unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
591       unsigned NumEntries = getNumJTEntries(JT, JTI);
592       if (Opc == ARM::t2TBB_JT && (NumEntries & 1))
593         // Make sure the instruction that follows TBB is 2-byte aligned.
594         // FIXME: Constant island pass should insert an "ALIGN" instruction
595         // instead.
596         ++NumEntries;
597       return NumEntries * EntrySize + InstSize;
598     }
599     default:
600       // Otherwise, pseudo-instruction sizes are zero.
601       return 0;
602     }
603   }
604   }
605   return 0; // Not reached
606 }
607
608 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
609                                    MachineBasicBlock::iterator I, DebugLoc DL,
610                                    unsigned DestReg, unsigned SrcReg,
611                                    bool KillSrc) const {
612   bool GPRDest = ARM::GPRRegClass.contains(DestReg);
613   bool GPRSrc  = ARM::GPRRegClass.contains(SrcReg);
614
615   if (GPRDest && GPRSrc) {
616     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
617                                   .addReg(SrcReg, getKillRegState(KillSrc))));
618     return;
619   }
620
621   bool SPRDest = ARM::SPRRegClass.contains(DestReg);
622   bool SPRSrc  = ARM::SPRRegClass.contains(SrcReg);
623
624   unsigned Opc;
625   if (SPRDest && SPRSrc)
626     Opc = ARM::VMOVS;
627   else if (GPRDest && SPRSrc)
628     Opc = ARM::VMOVRS;
629   else if (SPRDest && GPRSrc)
630     Opc = ARM::VMOVSR;
631   else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
632     Opc = ARM::VMOVD;
633   else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
634     Opc = ARM::VMOVQ;
635   else if (ARM::QQPRRegClass.contains(DestReg, SrcReg))
636     Opc = ARM::VMOVQQ;
637   else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg))
638     Opc = ARM::VMOVQQQQ;
639   else
640     llvm_unreachable("Impossible reg-to-reg copy");
641
642   MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
643   MIB.addReg(SrcReg, getKillRegState(KillSrc));
644   if (Opc != ARM::VMOVQQ && Opc != ARM::VMOVQQQQ)
645     AddDefaultPred(MIB);
646 }
647
648 static const
649 MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB,
650                              unsigned Reg, unsigned SubIdx, unsigned State,
651                              const TargetRegisterInfo *TRI) {
652   if (!SubIdx)
653     return MIB.addReg(Reg, State);
654
655   if (TargetRegisterInfo::isPhysicalRegister(Reg))
656     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
657   return MIB.addReg(Reg, State, SubIdx);
658 }
659
660 void ARMBaseInstrInfo::
661 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
662                     unsigned SrcReg, bool isKill, int FI,
663                     const TargetRegisterClass *RC,
664                     const TargetRegisterInfo *TRI) const {
665   DebugLoc DL;
666   if (I != MBB.end()) DL = I->getDebugLoc();
667   MachineFunction &MF = *MBB.getParent();
668   MachineFrameInfo &MFI = *MF.getFrameInfo();
669   unsigned Align = MFI.getObjectAlignment(FI);
670
671   MachineMemOperand *MMO =
672     MF.getMachineMemOperand(MachinePointerInfo(
673                                          PseudoSourceValue::getFixedStack(FI)),
674                             MachineMemOperand::MOStore,
675                             MFI.getObjectSize(FI),
676                             Align);
677
678   // tGPR is used sometimes in ARM instructions that need to avoid using
679   // certain registers.  Just treat it as GPR here. Likewise, rGPR.
680   if (RC == ARM::tGPRRegisterClass || RC == ARM::tcGPRRegisterClass
681       || RC == ARM::rGPRRegisterClass)
682     RC = ARM::GPRRegisterClass;
683
684   switch (RC->getID()) {
685   case ARM::GPRRegClassID:
686     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
687                    .addReg(SrcReg, getKillRegState(isKill))
688                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
689     break;
690   case ARM::SPRRegClassID:
691     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
692                    .addReg(SrcReg, getKillRegState(isKill))
693                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
694     break;
695   case ARM::DPRRegClassID:
696   case ARM::DPR_VFP2RegClassID:
697   case ARM::DPR_8RegClassID:
698     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
699                    .addReg(SrcReg, getKillRegState(isKill))
700                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
701     break;
702   case ARM::QPRRegClassID:
703   case ARM::QPR_VFP2RegClassID:
704   case ARM::QPR_8RegClassID:
705     if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
706       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64Pseudo))
707                      .addFrameIndex(FI).addImm(16)
708                      .addReg(SrcReg, getKillRegState(isKill))
709                      .addMemOperand(MMO));
710     } else {
711       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
712                      .addReg(SrcReg, getKillRegState(isKill))
713                      .addFrameIndex(FI)
714                      .addMemOperand(MMO));
715     }
716     break;
717   case ARM::QQPRRegClassID:
718   case ARM::QQPR_VFP2RegClassID:
719     if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
720       // FIXME: It's possible to only store part of the QQ register if the
721       // spilled def has a sub-register index.
722       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
723                      .addFrameIndex(FI).addImm(16)
724                      .addReg(SrcReg, getKillRegState(isKill))
725                      .addMemOperand(MMO));
726     } else {
727       MachineInstrBuilder MIB =
728         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
729                        .addFrameIndex(FI))
730         .addMemOperand(MMO);
731       MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
732       MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
733       MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
734             AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
735     }
736     break;
737   case ARM::QQQQPRRegClassID: {
738     MachineInstrBuilder MIB =
739       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
740                      .addFrameIndex(FI))
741       .addMemOperand(MMO);
742     MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
743     MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
744     MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
745     MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
746     MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
747     MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
748     MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
749           AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
750     break;
751   }
752   default:
753     llvm_unreachable("Unknown regclass!");
754   }
755 }
756
757 unsigned
758 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
759                                      int &FrameIndex) const {
760   switch (MI->getOpcode()) {
761   default: break;
762   case ARM::STRrs:
763   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
764     if (MI->getOperand(1).isFI() &&
765         MI->getOperand(2).isReg() &&
766         MI->getOperand(3).isImm() &&
767         MI->getOperand(2).getReg() == 0 &&
768         MI->getOperand(3).getImm() == 0) {
769       FrameIndex = MI->getOperand(1).getIndex();
770       return MI->getOperand(0).getReg();
771     }
772     break;
773   case ARM::STRi12:
774   case ARM::t2STRi12:
775   case ARM::tSpill:
776   case ARM::VSTRD:
777   case ARM::VSTRS:
778     if (MI->getOperand(1).isFI() &&
779         MI->getOperand(2).isImm() &&
780         MI->getOperand(2).getImm() == 0) {
781       FrameIndex = MI->getOperand(1).getIndex();
782       return MI->getOperand(0).getReg();
783     }
784     break;
785   case ARM::VST1q64Pseudo:
786     if (MI->getOperand(0).isFI() &&
787         MI->getOperand(2).getSubReg() == 0) {
788       FrameIndex = MI->getOperand(0).getIndex();
789       return MI->getOperand(2).getReg();
790     }
791     break;
792   case ARM::VSTMQIA:
793     if (MI->getOperand(1).isFI() &&
794         MI->getOperand(0).getSubReg() == 0) {
795       FrameIndex = MI->getOperand(1).getIndex();
796       return MI->getOperand(0).getReg();
797     }
798     break;
799   }
800
801   return 0;
802 }
803
804 void ARMBaseInstrInfo::
805 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
806                      unsigned DestReg, int FI,
807                      const TargetRegisterClass *RC,
808                      const TargetRegisterInfo *TRI) const {
809   DebugLoc DL;
810   if (I != MBB.end()) DL = I->getDebugLoc();
811   MachineFunction &MF = *MBB.getParent();
812   MachineFrameInfo &MFI = *MF.getFrameInfo();
813   unsigned Align = MFI.getObjectAlignment(FI);
814   MachineMemOperand *MMO =
815     MF.getMachineMemOperand(
816                     MachinePointerInfo(PseudoSourceValue::getFixedStack(FI)),
817                             MachineMemOperand::MOLoad,
818                             MFI.getObjectSize(FI),
819                             Align);
820
821   // tGPR is used sometimes in ARM instructions that need to avoid using
822   // certain registers.  Just treat it as GPR here.
823   if (RC == ARM::tGPRRegisterClass || RC == ARM::tcGPRRegisterClass
824       || RC == ARM::rGPRRegisterClass)
825     RC = ARM::GPRRegisterClass;
826
827   switch (RC->getID()) {
828   case ARM::GPRRegClassID:
829     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
830                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
831     break;
832   case ARM::SPRRegClassID:
833     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
834                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
835     break;
836   case ARM::DPRRegClassID:
837   case ARM::DPR_VFP2RegClassID:
838   case ARM::DPR_8RegClassID:
839     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
840                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
841     break;
842   case ARM::QPRRegClassID:
843   case ARM::QPR_VFP2RegClassID:
844   case ARM::QPR_8RegClassID:
845     if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
846       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64Pseudo), DestReg)
847                      .addFrameIndex(FI).addImm(16)
848                      .addMemOperand(MMO));
849     } else {
850       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
851                      .addFrameIndex(FI)
852                      .addMemOperand(MMO));
853     }
854     break;
855   case ARM::QQPRRegClassID:
856   case ARM::QQPR_VFP2RegClassID:
857     if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
858       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
859                      .addFrameIndex(FI).addImm(16)
860                      .addMemOperand(MMO));
861     } else {
862       MachineInstrBuilder MIB =
863         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
864                        .addFrameIndex(FI))
865         .addMemOperand(MMO);
866       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
867       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
868       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
869             AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
870     }
871     break;
872   case ARM::QQQQPRRegClassID: {
873     MachineInstrBuilder MIB =
874       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
875                      .addFrameIndex(FI))
876       .addMemOperand(MMO);
877     MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
878     MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
879     MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
880     MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
881     MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::Define, TRI);
882     MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::Define, TRI);
883     MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::Define, TRI);
884     AddDReg(MIB, DestReg, ARM::dsub_7, RegState::Define, TRI);
885     break;
886   }
887   default:
888     llvm_unreachable("Unknown regclass!");
889   }
890 }
891
892 unsigned
893 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
894                                       int &FrameIndex) const {
895   switch (MI->getOpcode()) {
896   default: break;
897   case ARM::LDRrs:
898   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
899     if (MI->getOperand(1).isFI() &&
900         MI->getOperand(2).isReg() &&
901         MI->getOperand(3).isImm() &&
902         MI->getOperand(2).getReg() == 0 &&
903         MI->getOperand(3).getImm() == 0) {
904       FrameIndex = MI->getOperand(1).getIndex();
905       return MI->getOperand(0).getReg();
906     }
907     break;
908   case ARM::LDRi12:
909   case ARM::t2LDRi12:
910   case ARM::tRestore:
911   case ARM::VLDRD:
912   case ARM::VLDRS:
913     if (MI->getOperand(1).isFI() &&
914         MI->getOperand(2).isImm() &&
915         MI->getOperand(2).getImm() == 0) {
916       FrameIndex = MI->getOperand(1).getIndex();
917       return MI->getOperand(0).getReg();
918     }
919     break;
920   case ARM::VLD1q64Pseudo:
921     if (MI->getOperand(1).isFI() &&
922         MI->getOperand(0).getSubReg() == 0) {
923       FrameIndex = MI->getOperand(1).getIndex();
924       return MI->getOperand(0).getReg();
925     }
926     break;
927   case ARM::VLDMQIA:
928     if (MI->getOperand(1).isFI() &&
929         MI->getOperand(0).getSubReg() == 0) {
930       FrameIndex = MI->getOperand(1).getIndex();
931       return MI->getOperand(0).getReg();
932     }
933     break;
934   }
935
936   return 0;
937 }
938
939 MachineInstr*
940 ARMBaseInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
941                                            int FrameIx, uint64_t Offset,
942                                            const MDNode *MDPtr,
943                                            DebugLoc DL) const {
944   MachineInstrBuilder MIB = BuildMI(MF, DL, get(ARM::DBG_VALUE))
945     .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
946   return &*MIB;
947 }
948
949 /// Create a copy of a const pool value. Update CPI to the new index and return
950 /// the label UID.
951 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
952   MachineConstantPool *MCP = MF.getConstantPool();
953   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
954
955   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
956   assert(MCPE.isMachineConstantPoolEntry() &&
957          "Expecting a machine constantpool entry!");
958   ARMConstantPoolValue *ACPV =
959     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
960
961   unsigned PCLabelId = AFI->createConstPoolEntryUId();
962   ARMConstantPoolValue *NewCPV = 0;
963   // FIXME: The below assumes PIC relocation model and that the function
964   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
965   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
966   // instructions, so that's probably OK, but is PIC always correct when
967   // we get here?
968   if (ACPV->isGlobalValue())
969     NewCPV = new ARMConstantPoolValue(ACPV->getGV(), PCLabelId,
970                                       ARMCP::CPValue, 4);
971   else if (ACPV->isExtSymbol())
972     NewCPV = new ARMConstantPoolValue(MF.getFunction()->getContext(),
973                                       ACPV->getSymbol(), PCLabelId, 4);
974   else if (ACPV->isBlockAddress())
975     NewCPV = new ARMConstantPoolValue(ACPV->getBlockAddress(), PCLabelId,
976                                       ARMCP::CPBlockAddress, 4);
977   else if (ACPV->isLSDA())
978     NewCPV = new ARMConstantPoolValue(MF.getFunction(), PCLabelId,
979                                       ARMCP::CPLSDA, 4);
980   else
981     llvm_unreachable("Unexpected ARM constantpool value type!!");
982   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
983   return PCLabelId;
984 }
985
986 void ARMBaseInstrInfo::
987 reMaterialize(MachineBasicBlock &MBB,
988               MachineBasicBlock::iterator I,
989               unsigned DestReg, unsigned SubIdx,
990               const MachineInstr *Orig,
991               const TargetRegisterInfo &TRI) const {
992   unsigned Opcode = Orig->getOpcode();
993   switch (Opcode) {
994   default: {
995     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
996     MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
997     MBB.insert(I, MI);
998     break;
999   }
1000   case ARM::tLDRpci_pic:
1001   case ARM::t2LDRpci_pic: {
1002     MachineFunction &MF = *MBB.getParent();
1003     unsigned CPI = Orig->getOperand(1).getIndex();
1004     unsigned PCLabelId = duplicateCPV(MF, CPI);
1005     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1006                                       DestReg)
1007       .addConstantPoolIndex(CPI).addImm(PCLabelId);
1008     (*MIB).setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1009     break;
1010   }
1011   }
1012 }
1013
1014 MachineInstr *
1015 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1016   MachineInstr *MI = TargetInstrInfoImpl::duplicate(Orig, MF);
1017   switch(Orig->getOpcode()) {
1018   case ARM::tLDRpci_pic:
1019   case ARM::t2LDRpci_pic: {
1020     unsigned CPI = Orig->getOperand(1).getIndex();
1021     unsigned PCLabelId = duplicateCPV(MF, CPI);
1022     Orig->getOperand(1).setIndex(CPI);
1023     Orig->getOperand(2).setImm(PCLabelId);
1024     break;
1025   }
1026   }
1027   return MI;
1028 }
1029
1030 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1031                                         const MachineInstr *MI1) const {
1032   int Opcode = MI0->getOpcode();
1033   if (Opcode == ARM::t2LDRpci ||
1034       Opcode == ARM::t2LDRpci_pic ||
1035       Opcode == ARM::tLDRpci ||
1036       Opcode == ARM::tLDRpci_pic) {
1037     if (MI1->getOpcode() != Opcode)
1038       return false;
1039     if (MI0->getNumOperands() != MI1->getNumOperands())
1040       return false;
1041
1042     const MachineOperand &MO0 = MI0->getOperand(1);
1043     const MachineOperand &MO1 = MI1->getOperand(1);
1044     if (MO0.getOffset() != MO1.getOffset())
1045       return false;
1046
1047     const MachineFunction *MF = MI0->getParent()->getParent();
1048     const MachineConstantPool *MCP = MF->getConstantPool();
1049     int CPI0 = MO0.getIndex();
1050     int CPI1 = MO1.getIndex();
1051     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1052     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1053     ARMConstantPoolValue *ACPV0 =
1054       static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1055     ARMConstantPoolValue *ACPV1 =
1056       static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1057     return ACPV0->hasSameValue(ACPV1);
1058   }
1059
1060   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1061 }
1062
1063 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1064 /// determine if two loads are loading from the same base address. It should
1065 /// only return true if the base pointers are the same and the only differences
1066 /// between the two addresses is the offset. It also returns the offsets by
1067 /// reference.
1068 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1069                                                int64_t &Offset1,
1070                                                int64_t &Offset2) const {
1071   // Don't worry about Thumb: just ARM and Thumb2.
1072   if (Subtarget.isThumb1Only()) return false;
1073
1074   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1075     return false;
1076
1077   switch (Load1->getMachineOpcode()) {
1078   default:
1079     return false;
1080   case ARM::LDRi12:
1081   case ARM::LDRBi12:
1082   case ARM::LDRD:
1083   case ARM::LDRH:
1084   case ARM::LDRSB:
1085   case ARM::LDRSH:
1086   case ARM::VLDRD:
1087   case ARM::VLDRS:
1088   case ARM::t2LDRi8:
1089   case ARM::t2LDRDi8:
1090   case ARM::t2LDRSHi8:
1091   case ARM::t2LDRi12:
1092   case ARM::t2LDRSHi12:
1093     break;
1094   }
1095
1096   switch (Load2->getMachineOpcode()) {
1097   default:
1098     return false;
1099   case ARM::LDRi12:
1100   case ARM::LDRBi12:
1101   case ARM::LDRD:
1102   case ARM::LDRH:
1103   case ARM::LDRSB:
1104   case ARM::LDRSH:
1105   case ARM::VLDRD:
1106   case ARM::VLDRS:
1107   case ARM::t2LDRi8:
1108   case ARM::t2LDRDi8:
1109   case ARM::t2LDRSHi8:
1110   case ARM::t2LDRi12:
1111   case ARM::t2LDRSHi12:
1112     break;
1113   }
1114
1115   // Check if base addresses and chain operands match.
1116   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1117       Load1->getOperand(4) != Load2->getOperand(4))
1118     return false;
1119
1120   // Index should be Reg0.
1121   if (Load1->getOperand(3) != Load2->getOperand(3))
1122     return false;
1123
1124   // Determine the offsets.
1125   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1126       isa<ConstantSDNode>(Load2->getOperand(1))) {
1127     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1128     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1129     return true;
1130   }
1131
1132   return false;
1133 }
1134
1135 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1136 /// determine (in conjuction with areLoadsFromSameBasePtr) if two loads should
1137 /// be scheduled togther. On some targets if two loads are loading from
1138 /// addresses in the same cache line, it's better if they are scheduled
1139 /// together. This function takes two integers that represent the load offsets
1140 /// from the common base address. It returns true if it decides it's desirable
1141 /// to schedule the two loads together. "NumLoads" is the number of loads that
1142 /// have already been scheduled after Load1.
1143 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1144                                                int64_t Offset1, int64_t Offset2,
1145                                                unsigned NumLoads) const {
1146   // Don't worry about Thumb: just ARM and Thumb2.
1147   if (Subtarget.isThumb1Only()) return false;
1148
1149   assert(Offset2 > Offset1);
1150
1151   if ((Offset2 - Offset1) / 8 > 64)
1152     return false;
1153
1154   if (Load1->getMachineOpcode() != Load2->getMachineOpcode())
1155     return false;  // FIXME: overly conservative?
1156
1157   // Four loads in a row should be sufficient.
1158   if (NumLoads >= 3)
1159     return false;
1160
1161   return true;
1162 }
1163
1164 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1165                                             const MachineBasicBlock *MBB,
1166                                             const MachineFunction &MF) const {
1167   // Debug info is never a scheduling boundary. It's necessary to be explicit
1168   // due to the special treatment of IT instructions below, otherwise a
1169   // dbg_value followed by an IT will result in the IT instruction being
1170   // considered a scheduling hazard, which is wrong. It should be the actual
1171   // instruction preceding the dbg_value instruction(s), just like it is
1172   // when debug info is not present.
1173   if (MI->isDebugValue())
1174     return false;
1175
1176   // Terminators and labels can't be scheduled around.
1177   if (MI->getDesc().isTerminator() || MI->isLabel())
1178     return true;
1179
1180   // Treat the start of the IT block as a scheduling boundary, but schedule
1181   // t2IT along with all instructions following it.
1182   // FIXME: This is a big hammer. But the alternative is to add all potential
1183   // true and anti dependencies to IT block instructions as implicit operands
1184   // to the t2IT instruction. The added compile time and complexity does not
1185   // seem worth it.
1186   MachineBasicBlock::const_iterator I = MI;
1187   // Make sure to skip any dbg_value instructions
1188   while (++I != MBB->end() && I->isDebugValue())
1189     ;
1190   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1191     return true;
1192
1193   // Don't attempt to schedule around any instruction that defines
1194   // a stack-oriented pointer, as it's unlikely to be profitable. This
1195   // saves compile time, because it doesn't require every single
1196   // stack slot reference to depend on the instruction that does the
1197   // modification.
1198   if (MI->definesRegister(ARM::SP))
1199     return true;
1200
1201   return false;
1202 }
1203
1204 bool ARMBaseInstrInfo::isProfitableToIfCvt(MachineBasicBlock &MBB,
1205                                            unsigned NumCyles,
1206                                            unsigned ExtraPredCycles,
1207                                            float Probability,
1208                                            float Confidence) const {
1209   if (!NumCyles)
1210     return false;
1211
1212   // Attempt to estimate the relative costs of predication versus branching.
1213   float UnpredCost = Probability * NumCyles;
1214   UnpredCost += 1.0; // The branch itself
1215   UnpredCost += (1.0 - Confidence) * Subtarget.getMispredictionPenalty();
1216
1217   return (float)(NumCyles + ExtraPredCycles) < UnpredCost;
1218 }
1219
1220 bool ARMBaseInstrInfo::
1221 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1222                     unsigned TCycles, unsigned TExtra,
1223                     MachineBasicBlock &FMBB,
1224                     unsigned FCycles, unsigned FExtra,
1225                     float Probability, float Confidence) const {
1226   if (!TCycles || !FCycles)
1227     return false;
1228
1229   // Attempt to estimate the relative costs of predication versus branching.
1230   float UnpredCost = Probability * TCycles + (1.0 - Probability) * FCycles;
1231   UnpredCost += 1.0; // The branch itself
1232   UnpredCost += (1.0 - Confidence) * Subtarget.getMispredictionPenalty();
1233
1234   return (float)(TCycles + FCycles + TExtra + FExtra) < UnpredCost;
1235 }
1236
1237 /// getInstrPredicate - If instruction is predicated, returns its predicate
1238 /// condition, otherwise returns AL. It also returns the condition code
1239 /// register by reference.
1240 ARMCC::CondCodes
1241 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1242   int PIdx = MI->findFirstPredOperandIdx();
1243   if (PIdx == -1) {
1244     PredReg = 0;
1245     return ARMCC::AL;
1246   }
1247
1248   PredReg = MI->getOperand(PIdx+1).getReg();
1249   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1250 }
1251
1252
1253 int llvm::getMatchingCondBranchOpcode(int Opc) {
1254   if (Opc == ARM::B)
1255     return ARM::Bcc;
1256   else if (Opc == ARM::tB)
1257     return ARM::tBcc;
1258   else if (Opc == ARM::t2B)
1259       return ARM::t2Bcc;
1260
1261   llvm_unreachable("Unknown unconditional branch opcode!");
1262   return 0;
1263 }
1264
1265
1266 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1267                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1268                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1269                                ARMCC::CondCodes Pred, unsigned PredReg,
1270                                const ARMBaseInstrInfo &TII) {
1271   bool isSub = NumBytes < 0;
1272   if (isSub) NumBytes = -NumBytes;
1273
1274   while (NumBytes) {
1275     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1276     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1277     assert(ThisVal && "Didn't extract field correctly");
1278
1279     // We will handle these bits from offset, clear them.
1280     NumBytes &= ~ThisVal;
1281
1282     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1283
1284     // Build the new ADD / SUB.
1285     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1286     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1287       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1288       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
1289     BaseReg = DestReg;
1290   }
1291 }
1292
1293 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1294                                 unsigned FrameReg, int &Offset,
1295                                 const ARMBaseInstrInfo &TII) {
1296   unsigned Opcode = MI.getOpcode();
1297   const TargetInstrDesc &Desc = MI.getDesc();
1298   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1299   bool isSub = false;
1300
1301   // Memory operands in inline assembly always use AddrMode2.
1302   if (Opcode == ARM::INLINEASM)
1303     AddrMode = ARMII::AddrMode2;
1304
1305   if (Opcode == ARM::ADDri) {
1306     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1307     if (Offset == 0) {
1308       // Turn it into a move.
1309       MI.setDesc(TII.get(ARM::MOVr));
1310       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1311       MI.RemoveOperand(FrameRegIdx+1);
1312       Offset = 0;
1313       return true;
1314     } else if (Offset < 0) {
1315       Offset = -Offset;
1316       isSub = true;
1317       MI.setDesc(TII.get(ARM::SUBri));
1318     }
1319
1320     // Common case: small offset, fits into instruction.
1321     if (ARM_AM::getSOImmVal(Offset) != -1) {
1322       // Replace the FrameIndex with sp / fp
1323       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1324       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1325       Offset = 0;
1326       return true;
1327     }
1328
1329     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1330     // as possible.
1331     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1332     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1333
1334     // We will handle these bits from offset, clear them.
1335     Offset &= ~ThisImmVal;
1336
1337     // Get the properly encoded SOImmVal field.
1338     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1339            "Bit extraction didn't work?");
1340     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1341  } else {
1342     unsigned ImmIdx = 0;
1343     int InstrOffs = 0;
1344     unsigned NumBits = 0;
1345     unsigned Scale = 1;
1346     switch (AddrMode) {
1347     case ARMII::AddrMode_i12: {
1348       ImmIdx = FrameRegIdx + 1;
1349       InstrOffs = MI.getOperand(ImmIdx).getImm();
1350       NumBits = 12;
1351       break;
1352     }
1353     case ARMII::AddrMode2: {
1354       ImmIdx = FrameRegIdx+2;
1355       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1356       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1357         InstrOffs *= -1;
1358       NumBits = 12;
1359       break;
1360     }
1361     case ARMII::AddrMode3: {
1362       ImmIdx = FrameRegIdx+2;
1363       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1364       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1365         InstrOffs *= -1;
1366       NumBits = 8;
1367       break;
1368     }
1369     case ARMII::AddrMode4:
1370     case ARMII::AddrMode6:
1371       // Can't fold any offset even if it's zero.
1372       return false;
1373     case ARMII::AddrMode5: {
1374       ImmIdx = FrameRegIdx+1;
1375       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1376       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1377         InstrOffs *= -1;
1378       NumBits = 8;
1379       Scale = 4;
1380       break;
1381     }
1382     default:
1383       llvm_unreachable("Unsupported addressing mode!");
1384       break;
1385     }
1386
1387     Offset += InstrOffs * Scale;
1388     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1389     if (Offset < 0) {
1390       Offset = -Offset;
1391       isSub = true;
1392     }
1393
1394     // Attempt to fold address comp. if opcode has offset bits
1395     if (NumBits > 0) {
1396       // Common case: small offset, fits into instruction.
1397       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1398       int ImmedOffset = Offset / Scale;
1399       unsigned Mask = (1 << NumBits) - 1;
1400       if ((unsigned)Offset <= Mask * Scale) {
1401         // Replace the FrameIndex with sp
1402         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1403         // FIXME: When addrmode2 goes away, this will simplify (like the
1404         // T2 version), as the LDR.i12 versions don't need the encoding
1405         // tricks for the offset value.
1406         if (isSub) {
1407           if (AddrMode == ARMII::AddrMode_i12)
1408             ImmedOffset = -ImmedOffset;
1409           else
1410             ImmedOffset |= 1 << NumBits;
1411         }
1412         ImmOp.ChangeToImmediate(ImmedOffset);
1413         Offset = 0;
1414         return true;
1415       }
1416
1417       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1418       ImmedOffset = ImmedOffset & Mask;
1419       if (isSub) {
1420         if (AddrMode == ARMII::AddrMode_i12)
1421           ImmedOffset = -ImmedOffset;
1422         else
1423           ImmedOffset |= 1 << NumBits;
1424       }
1425       ImmOp.ChangeToImmediate(ImmedOffset);
1426       Offset &= ~(Mask*Scale);
1427     }
1428   }
1429
1430   Offset = (isSub) ? -Offset : Offset;
1431   return Offset == 0;
1432 }
1433
1434 bool ARMBaseInstrInfo::
1435 AnalyzeCompare(const MachineInstr *MI, unsigned &SrcReg, int &CmpMask,
1436                int &CmpValue) const {
1437   switch (MI->getOpcode()) {
1438   default: break;
1439   case ARM::CMPri:
1440   case ARM::t2CMPri:
1441     SrcReg = MI->getOperand(0).getReg();
1442     CmpMask = ~0;
1443     CmpValue = MI->getOperand(1).getImm();
1444     return true;
1445   case ARM::TSTri:
1446   case ARM::t2TSTri:
1447     SrcReg = MI->getOperand(0).getReg();
1448     CmpMask = MI->getOperand(1).getImm();
1449     CmpValue = 0;
1450     return true;
1451   }
1452
1453   return false;
1454 }
1455
1456 /// isSuitableForMask - Identify a suitable 'and' instruction that
1457 /// operates on the given source register and applies the same mask
1458 /// as a 'tst' instruction. Provide a limited look-through for copies.
1459 /// When successful, MI will hold the found instruction.
1460 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
1461                               int CmpMask, bool CommonUse) {
1462   switch (MI->getOpcode()) {
1463     case ARM::ANDri:
1464     case ARM::t2ANDri:
1465       if (CmpMask != MI->getOperand(2).getImm())
1466         return false;
1467       if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
1468         return true;
1469       break;
1470     case ARM::COPY: {
1471       // Walk down one instruction which is potentially an 'and'.
1472       const MachineInstr &Copy = *MI;
1473       MachineBasicBlock::iterator AND(
1474         llvm::next(MachineBasicBlock::iterator(MI)));
1475       if (AND == MI->getParent()->end()) return false;
1476       MI = AND;
1477       return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
1478                                CmpMask, true);
1479     }
1480   }
1481
1482   return false;
1483 }
1484
1485 /// OptimizeCompareInstr - Convert the instruction supplying the argument to the
1486 /// comparison into one that sets the zero bit in the flags register.
1487 bool ARMBaseInstrInfo::
1488 OptimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, int CmpMask,
1489                      int CmpValue, const MachineRegisterInfo *MRI) const {
1490   if (CmpValue != 0)
1491     return false;
1492
1493   MachineRegisterInfo::def_iterator DI = MRI->def_begin(SrcReg);
1494   if (llvm::next(DI) != MRI->def_end())
1495     // Only support one definition.
1496     return false;
1497
1498   MachineInstr *MI = &*DI;
1499
1500   // Masked compares sometimes use the same register as the corresponding 'and'.
1501   if (CmpMask != ~0) {
1502     if (!isSuitableForMask(MI, SrcReg, CmpMask, false)) {
1503       MI = 0;
1504       for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
1505            UE = MRI->use_end(); UI != UE; ++UI) {
1506         if (UI->getParent() != CmpInstr->getParent()) continue;
1507         MachineInstr *PotentialAND = &*UI;
1508         if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true))
1509           continue;
1510         MI = PotentialAND;
1511         break;
1512       }
1513       if (!MI) return false;
1514     }
1515   }
1516
1517   // Conservatively refuse to convert an instruction which isn't in the same BB
1518   // as the comparison.
1519   if (MI->getParent() != CmpInstr->getParent())
1520     return false;
1521
1522   // Check that CPSR isn't set between the comparison instruction and the one we
1523   // want to change.
1524   MachineBasicBlock::const_iterator I = CmpInstr, E = MI,
1525     B = MI->getParent()->begin();
1526
1527   // Early exit if CmpInstr is at the beginning of the BB.
1528   if (I == B) return false;
1529
1530   --I;
1531   for (; I != E; --I) {
1532     const MachineInstr &Instr = *I;
1533
1534     for (unsigned IO = 0, EO = Instr.getNumOperands(); IO != EO; ++IO) {
1535       const MachineOperand &MO = Instr.getOperand(IO);
1536       if (!MO.isReg()) continue;
1537
1538       // This instruction modifies or uses CPSR after the one we want to
1539       // change. We can't do this transformation.
1540       if (MO.getReg() == ARM::CPSR)
1541         return false;
1542     }
1543
1544     if (I == B)
1545       // The 'and' is below the comparison instruction.
1546       return false;
1547   }
1548
1549   // Set the "zero" bit in CPSR.
1550   switch (MI->getOpcode()) {
1551   default: break;
1552   case ARM::ADDri:
1553   case ARM::ANDri:
1554   case ARM::t2ANDri:
1555   case ARM::SUBri:
1556   case ARM::t2ADDri:
1557   case ARM::t2SUBri:
1558     // Toggle the optional operand to CPSR.
1559     MI->getOperand(5).setReg(ARM::CPSR);
1560     MI->getOperand(5).setIsDef(true);
1561     CmpInstr->eraseFromParent();
1562     return true;
1563   }
1564
1565   return false;
1566 }
1567
1568 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
1569                                      MachineInstr *DefMI, unsigned Reg,
1570                                      MachineRegisterInfo *MRI) const {
1571   // Fold large immediates into add, sub, or, xor.
1572   unsigned DefOpc = DefMI->getOpcode();
1573   if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
1574     return false;
1575   if (!DefMI->getOperand(1).isImm())
1576     // Could be t2MOVi32imm <ga:xx>
1577     return false;
1578
1579   if (!MRI->hasOneNonDBGUse(Reg))
1580     return false;
1581
1582   unsigned UseOpc = UseMI->getOpcode();
1583   unsigned NewUseOpc = 0;
1584   uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
1585   uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
1586   bool Commute = false;
1587   switch (UseOpc) {
1588   default: return false;
1589   case ARM::SUBrr:
1590   case ARM::ADDrr:
1591   case ARM::ORRrr:
1592   case ARM::EORrr:
1593   case ARM::t2SUBrr:
1594   case ARM::t2ADDrr:
1595   case ARM::t2ORRrr:
1596   case ARM::t2EORrr: {
1597     Commute = UseMI->getOperand(2).getReg() != Reg;
1598     switch (UseOpc) {
1599     default: break;
1600     case ARM::SUBrr: {
1601       if (Commute)
1602         return false;
1603       ImmVal = -ImmVal;
1604       NewUseOpc = ARM::SUBri;
1605       // Fallthrough
1606     }
1607     case ARM::ADDrr:
1608     case ARM::ORRrr:
1609     case ARM::EORrr: {
1610       if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
1611         return false;
1612       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
1613       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
1614       switch (UseOpc) {
1615       default: break;
1616       case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
1617       case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
1618       case ARM::EORrr: NewUseOpc = ARM::EORri; break;
1619       }
1620       break;
1621     }
1622     case ARM::t2SUBrr: {
1623       if (Commute)
1624         return false;
1625       ImmVal = -ImmVal;
1626       NewUseOpc = ARM::t2SUBri;
1627       // Fallthrough
1628     }
1629     case ARM::t2ADDrr:
1630     case ARM::t2ORRrr:
1631     case ARM::t2EORrr: {
1632       if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
1633         return false;
1634       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
1635       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
1636       switch (UseOpc) {
1637       default: break;
1638       case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
1639       case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
1640       case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
1641       }
1642       break;
1643     }
1644     }
1645   }
1646   }
1647
1648   unsigned OpIdx = Commute ? 2 : 1;
1649   unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
1650   bool isKill = UseMI->getOperand(OpIdx).isKill();
1651   unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
1652   AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
1653                                       *UseMI, UseMI->getDebugLoc(),
1654                                       get(NewUseOpc), NewReg)
1655                               .addReg(Reg1, getKillRegState(isKill))
1656                               .addImm(SOImmValV1)));
1657   UseMI->setDesc(get(NewUseOpc));
1658   UseMI->getOperand(1).setReg(NewReg);
1659   UseMI->getOperand(1).setIsKill();
1660   UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
1661   DefMI->eraseFromParent();
1662   return true;
1663 }
1664
1665 unsigned
1666 ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1667                                  const MachineInstr *MI) const {
1668   if (!ItinData || ItinData->isEmpty())
1669     return 1;
1670
1671   const TargetInstrDesc &Desc = MI->getDesc();
1672   unsigned Class = Desc.getSchedClass();
1673   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
1674   if (UOps)
1675     return UOps;
1676
1677   unsigned Opc = MI->getOpcode();
1678   switch (Opc) {
1679   default:
1680     llvm_unreachable("Unexpected multi-uops instruction!");
1681     break;
1682   case ARM::VLDMQIA:
1683   case ARM::VLDMQDB:
1684   case ARM::VSTMQIA:
1685   case ARM::VSTMQDB:
1686     return 2;
1687
1688   // The number of uOps for load / store multiple are determined by the number
1689   // registers.
1690   //
1691   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
1692   // same cycle. The scheduling for the first load / store must be done
1693   // separately by assuming the the address is not 64-bit aligned.
1694   //
1695   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
1696   // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
1697   // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
1698   case ARM::VLDMDIA:
1699   case ARM::VLDMDDB:
1700   case ARM::VLDMDIA_UPD:
1701   case ARM::VLDMDDB_UPD:
1702   case ARM::VLDMSIA:
1703   case ARM::VLDMSDB:
1704   case ARM::VLDMSIA_UPD:
1705   case ARM::VLDMSDB_UPD:
1706   case ARM::VSTMDIA:
1707   case ARM::VSTMDDB:
1708   case ARM::VSTMDIA_UPD:
1709   case ARM::VSTMDDB_UPD:
1710   case ARM::VSTMSIA:
1711   case ARM::VSTMSDB:
1712   case ARM::VSTMSIA_UPD:
1713   case ARM::VSTMSDB_UPD: {
1714     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
1715     return (NumRegs / 2) + (NumRegs % 2) + 1;
1716   }
1717
1718   case ARM::LDMIA_RET:
1719   case ARM::LDMIA:
1720   case ARM::LDMDA:
1721   case ARM::LDMDB:
1722   case ARM::LDMIB:
1723   case ARM::LDMIA_UPD:
1724   case ARM::LDMDA_UPD:
1725   case ARM::LDMDB_UPD:
1726   case ARM::LDMIB_UPD:
1727   case ARM::STMIA:
1728   case ARM::STMDA:
1729   case ARM::STMDB:
1730   case ARM::STMIB:
1731   case ARM::STMIA_UPD:
1732   case ARM::STMDA_UPD:
1733   case ARM::STMDB_UPD:
1734   case ARM::STMIB_UPD:
1735   case ARM::tLDMIA:
1736   case ARM::tLDMIA_UPD:
1737   case ARM::tSTMIA:
1738   case ARM::tSTMIA_UPD:
1739   case ARM::tPOP_RET:
1740   case ARM::tPOP:
1741   case ARM::tPUSH:
1742   case ARM::t2LDMIA_RET:
1743   case ARM::t2LDMIA:
1744   case ARM::t2LDMDB:
1745   case ARM::t2LDMIA_UPD:
1746   case ARM::t2LDMDB_UPD:
1747   case ARM::t2STMIA:
1748   case ARM::t2STMDB:
1749   case ARM::t2STMIA_UPD:
1750   case ARM::t2STMDB_UPD: {
1751     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
1752     if (Subtarget.isCortexA8()) {
1753       if (NumRegs < 4)
1754         return 2;
1755       // 4 registers would be issued: 2, 2.
1756       // 5 registers would be issued: 2, 2, 1.
1757       UOps = (NumRegs / 2);
1758       if (NumRegs % 2)
1759         ++UOps;
1760       return UOps;
1761     } else if (Subtarget.isCortexA9()) {
1762       UOps = (NumRegs / 2);
1763       // If there are odd number of registers or if it's not 64-bit aligned,
1764       // then it takes an extra AGU (Address Generation Unit) cycle.
1765       if ((NumRegs % 2) ||
1766           !MI->hasOneMemOperand() ||
1767           (*MI->memoperands_begin())->getAlignment() < 8)
1768         ++UOps;
1769       return UOps;
1770     } else {
1771       // Assume the worst.
1772       return NumRegs;
1773     }
1774   }
1775   }
1776 }
1777
1778 int
1779 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
1780                                   const TargetInstrDesc &DefTID,
1781                                   unsigned DefClass,
1782                                   unsigned DefIdx, unsigned DefAlign) const {
1783   int RegNo = (int)(DefIdx+1) - DefTID.getNumOperands() + 1;
1784   if (RegNo <= 0)
1785     // Def is the address writeback.
1786     return ItinData->getOperandCycle(DefClass, DefIdx);
1787
1788   int DefCycle;
1789   if (Subtarget.isCortexA8()) {
1790     // (regno / 2) + (regno % 2) + 1
1791     DefCycle = RegNo / 2 + 1;
1792     if (RegNo % 2)
1793       ++DefCycle;
1794   } else if (Subtarget.isCortexA9()) {
1795     DefCycle = RegNo;
1796     bool isSLoad = false;
1797
1798     switch (DefTID.getOpcode()) {
1799     default: break;
1800     case ARM::VLDMSIA:
1801     case ARM::VLDMSDB:
1802     case ARM::VLDMSIA_UPD:
1803     case ARM::VLDMSDB_UPD:
1804       isSLoad = true;
1805       break;
1806     }
1807
1808     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
1809     // then it takes an extra cycle.
1810     if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
1811       ++DefCycle;
1812   } else {
1813     // Assume the worst.
1814     DefCycle = RegNo + 2;
1815   }
1816
1817   return DefCycle;
1818 }
1819
1820 int
1821 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
1822                                  const TargetInstrDesc &DefTID,
1823                                  unsigned DefClass,
1824                                  unsigned DefIdx, unsigned DefAlign) const {
1825   int RegNo = (int)(DefIdx+1) - DefTID.getNumOperands() + 1;
1826   if (RegNo <= 0)
1827     // Def is the address writeback.
1828     return ItinData->getOperandCycle(DefClass, DefIdx);
1829
1830   int DefCycle;
1831   if (Subtarget.isCortexA8()) {
1832     // 4 registers would be issued: 1, 2, 1.
1833     // 5 registers would be issued: 1, 2, 2.
1834     DefCycle = RegNo / 2;
1835     if (DefCycle < 1)
1836       DefCycle = 1;
1837     // Result latency is issue cycle + 2: E2.
1838     DefCycle += 2;
1839   } else if (Subtarget.isCortexA9()) {
1840     DefCycle = (RegNo / 2);
1841     // If there are odd number of registers or if it's not 64-bit aligned,
1842     // then it takes an extra AGU (Address Generation Unit) cycle.
1843     if ((RegNo % 2) || DefAlign < 8)
1844       ++DefCycle;
1845     // Result latency is AGU cycles + 2.
1846     DefCycle += 2;
1847   } else {
1848     // Assume the worst.
1849     DefCycle = RegNo + 2;
1850   }
1851
1852   return DefCycle;
1853 }
1854
1855 int
1856 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
1857                                   const TargetInstrDesc &UseTID,
1858                                   unsigned UseClass,
1859                                   unsigned UseIdx, unsigned UseAlign) const {
1860   int RegNo = (int)(UseIdx+1) - UseTID.getNumOperands() + 1;
1861   if (RegNo <= 0)
1862     return ItinData->getOperandCycle(UseClass, UseIdx);
1863
1864   int UseCycle;
1865   if (Subtarget.isCortexA8()) {
1866     // (regno / 2) + (regno % 2) + 1
1867     UseCycle = RegNo / 2 + 1;
1868     if (RegNo % 2)
1869       ++UseCycle;
1870   } else if (Subtarget.isCortexA9()) {
1871     UseCycle = RegNo;
1872     bool isSStore = false;
1873
1874     switch (UseTID.getOpcode()) {
1875     default: break;
1876     case ARM::VSTMSIA:
1877     case ARM::VSTMSDB:
1878     case ARM::VSTMSIA_UPD:
1879     case ARM::VSTMSDB_UPD:
1880       isSStore = true;
1881       break;
1882     }
1883
1884     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
1885     // then it takes an extra cycle.
1886     if ((isSStore && (RegNo % 2)) || UseAlign < 8)
1887       ++UseCycle;
1888   } else {
1889     // Assume the worst.
1890     UseCycle = RegNo + 2;
1891   }
1892
1893   return UseCycle;
1894 }
1895
1896 int
1897 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
1898                                  const TargetInstrDesc &UseTID,
1899                                  unsigned UseClass,
1900                                  unsigned UseIdx, unsigned UseAlign) const {
1901   int RegNo = (int)(UseIdx+1) - UseTID.getNumOperands() + 1;
1902   if (RegNo <= 0)
1903     return ItinData->getOperandCycle(UseClass, UseIdx);
1904
1905   int UseCycle;
1906   if (Subtarget.isCortexA8()) {
1907     UseCycle = RegNo / 2;
1908     if (UseCycle < 2)
1909       UseCycle = 2;
1910     // Read in E3.
1911     UseCycle += 2;
1912   } else if (Subtarget.isCortexA9()) {
1913     UseCycle = (RegNo / 2);
1914     // If there are odd number of registers or if it's not 64-bit aligned,
1915     // then it takes an extra AGU (Address Generation Unit) cycle.
1916     if ((RegNo % 2) || UseAlign < 8)
1917       ++UseCycle;
1918   } else {
1919     // Assume the worst.
1920     UseCycle = 1;
1921   }
1922   return UseCycle;
1923 }
1924
1925 int
1926 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1927                                     const TargetInstrDesc &DefTID,
1928                                     unsigned DefIdx, unsigned DefAlign,
1929                                     const TargetInstrDesc &UseTID,
1930                                     unsigned UseIdx, unsigned UseAlign) const {
1931   unsigned DefClass = DefTID.getSchedClass();
1932   unsigned UseClass = UseTID.getSchedClass();
1933
1934   if (DefIdx < DefTID.getNumDefs() && UseIdx < UseTID.getNumOperands())
1935     return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1936
1937   // This may be a def / use of a variable_ops instruction, the operand
1938   // latency might be determinable dynamically. Let the target try to
1939   // figure it out.
1940   int DefCycle = -1;
1941   bool LdmBypass = false;
1942   switch (DefTID.getOpcode()) {
1943   default:
1944     DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
1945     break;
1946
1947   case ARM::VLDMDIA:
1948   case ARM::VLDMDDB:
1949   case ARM::VLDMDIA_UPD:
1950   case ARM::VLDMDDB_UPD:
1951   case ARM::VLDMSIA:
1952   case ARM::VLDMSDB:
1953   case ARM::VLDMSIA_UPD:
1954   case ARM::VLDMSDB_UPD:
1955     DefCycle = getVLDMDefCycle(ItinData, DefTID, DefClass, DefIdx, DefAlign);
1956     break;
1957
1958   case ARM::LDMIA_RET:
1959   case ARM::LDMIA:
1960   case ARM::LDMDA:
1961   case ARM::LDMDB:
1962   case ARM::LDMIB:
1963   case ARM::LDMIA_UPD:
1964   case ARM::LDMDA_UPD:
1965   case ARM::LDMDB_UPD:
1966   case ARM::LDMIB_UPD:
1967   case ARM::tLDMIA:
1968   case ARM::tLDMIA_UPD:
1969   case ARM::tPUSH:
1970   case ARM::t2LDMIA_RET:
1971   case ARM::t2LDMIA:
1972   case ARM::t2LDMDB:
1973   case ARM::t2LDMIA_UPD:
1974   case ARM::t2LDMDB_UPD:
1975     LdmBypass = 1;
1976     DefCycle = getLDMDefCycle(ItinData, DefTID, DefClass, DefIdx, DefAlign);
1977     break;
1978   }
1979
1980   if (DefCycle == -1)
1981     // We can't seem to determine the result latency of the def, assume it's 2.
1982     DefCycle = 2;
1983
1984   int UseCycle = -1;
1985   switch (UseTID.getOpcode()) {
1986   default:
1987     UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
1988     break;
1989
1990   case ARM::VSTMDIA:
1991   case ARM::VSTMDDB:
1992   case ARM::VSTMDIA_UPD:
1993   case ARM::VSTMDDB_UPD:
1994   case ARM::VSTMSIA:
1995   case ARM::VSTMSDB:
1996   case ARM::VSTMSIA_UPD:
1997   case ARM::VSTMSDB_UPD:
1998     UseCycle = getVSTMUseCycle(ItinData, UseTID, UseClass, UseIdx, UseAlign);
1999     break;
2000
2001   case ARM::STMIA:
2002   case ARM::STMDA:
2003   case ARM::STMDB:
2004   case ARM::STMIB:
2005   case ARM::STMIA_UPD:
2006   case ARM::STMDA_UPD:
2007   case ARM::STMDB_UPD:
2008   case ARM::STMIB_UPD:
2009   case ARM::tSTMIA:
2010   case ARM::tSTMIA_UPD:
2011   case ARM::tPOP_RET:
2012   case ARM::tPOP:
2013   case ARM::t2STMIA:
2014   case ARM::t2STMDB:
2015   case ARM::t2STMIA_UPD:
2016   case ARM::t2STMDB_UPD:
2017     UseCycle = getSTMUseCycle(ItinData, UseTID, UseClass, UseIdx, UseAlign);
2018     break;
2019   }
2020
2021   if (UseCycle == -1)
2022     // Assume it's read in the first stage.
2023     UseCycle = 1;
2024
2025   UseCycle = DefCycle - UseCycle + 1;
2026   if (UseCycle > 0) {
2027     if (LdmBypass) {
2028       // It's a variable_ops instruction so we can't use DefIdx here. Just use
2029       // first def operand.
2030       if (ItinData->hasPipelineForwarding(DefClass, DefTID.getNumOperands()-1,
2031                                           UseClass, UseIdx))
2032         --UseCycle;
2033     } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
2034                                                UseClass, UseIdx)) {
2035       --UseCycle;
2036     }
2037   }
2038
2039   return UseCycle;
2040 }
2041
2042 int
2043 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2044                              const MachineInstr *DefMI, unsigned DefIdx,
2045                              const MachineInstr *UseMI, unsigned UseIdx) const {
2046   if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
2047       DefMI->isRegSequence() || DefMI->isImplicitDef())
2048     return 1;
2049
2050   const TargetInstrDesc &DefTID = DefMI->getDesc();
2051   if (!ItinData || ItinData->isEmpty())
2052     return DefTID.mayLoad() ? 3 : 1;
2053
2054
2055   const TargetInstrDesc &UseTID = UseMI->getDesc();
2056   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
2057   if (DefMO.getReg() == ARM::CPSR) {
2058     if (DefMI->getOpcode() == ARM::FMSTAT) {
2059       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
2060       return Subtarget.isCortexA9() ? 1 : 20;
2061     }
2062
2063     // CPSR set and branch can be paired in the same cycle.
2064     if (UseTID.isBranch())
2065       return 0;
2066   }
2067
2068   unsigned DefAlign = DefMI->hasOneMemOperand()
2069     ? (*DefMI->memoperands_begin())->getAlignment() : 0;
2070   unsigned UseAlign = UseMI->hasOneMemOperand()
2071     ? (*UseMI->memoperands_begin())->getAlignment() : 0;
2072   int Latency = getOperandLatency(ItinData, DefTID, DefIdx, DefAlign,
2073                                   UseTID, UseIdx, UseAlign);
2074
2075   if (Latency > 1 &&
2076       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2077     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2078     // variants are one cycle cheaper.
2079     switch (DefTID.getOpcode()) {
2080     default: break;
2081     case ARM::LDRrs:
2082     case ARM::LDRBrs: {
2083       unsigned ShOpVal = DefMI->getOperand(3).getImm();
2084       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2085       if (ShImm == 0 ||
2086           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2087         --Latency;
2088       break;
2089     }
2090     case ARM::t2LDRs:
2091     case ARM::t2LDRBs:
2092     case ARM::t2LDRHs:
2093     case ARM::t2LDRSHs: {
2094       // Thumb2 mode: lsl only.
2095       unsigned ShAmt = DefMI->getOperand(3).getImm();
2096       if (ShAmt == 0 || ShAmt == 2)
2097         --Latency;
2098       break;
2099     }
2100     }
2101   }
2102
2103   return Latency;
2104 }
2105
2106 int
2107 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2108                                     SDNode *DefNode, unsigned DefIdx,
2109                                     SDNode *UseNode, unsigned UseIdx) const {
2110   if (!DefNode->isMachineOpcode())
2111     return 1;
2112
2113   const TargetInstrDesc &DefTID = get(DefNode->getMachineOpcode());
2114   if (!ItinData || ItinData->isEmpty())
2115     return DefTID.mayLoad() ? 3 : 1;
2116
2117   if (!UseNode->isMachineOpcode()) {
2118     int Latency = ItinData->getOperandCycle(DefTID.getSchedClass(), DefIdx);
2119     if (Subtarget.isCortexA9())
2120       return Latency <= 2 ? 1 : Latency - 1;
2121     else
2122       return Latency <= 3 ? 1 : Latency - 2;
2123   }
2124
2125   const TargetInstrDesc &UseTID = get(UseNode->getMachineOpcode());
2126   const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
2127   unsigned DefAlign = !DefMN->memoperands_empty()
2128     ? (*DefMN->memoperands_begin())->getAlignment() : 0;
2129   const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
2130   unsigned UseAlign = !UseMN->memoperands_empty()
2131     ? (*UseMN->memoperands_begin())->getAlignment() : 0;
2132   int Latency = getOperandLatency(ItinData, DefTID, DefIdx, DefAlign,
2133                                   UseTID, UseIdx, UseAlign);
2134
2135   if (Latency > 1 &&
2136       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2137     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2138     // variants are one cycle cheaper.
2139     switch (DefTID.getOpcode()) {
2140     default: break;
2141     case ARM::LDRrs:
2142     case ARM::LDRBrs: {
2143       unsigned ShOpVal =
2144         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2145       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2146       if (ShImm == 0 ||
2147           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2148         --Latency;
2149       break;
2150     }
2151     case ARM::t2LDRs:
2152     case ARM::t2LDRBs:
2153     case ARM::t2LDRHs:
2154     case ARM::t2LDRSHs: {
2155       // Thumb2 mode: lsl only.
2156       unsigned ShAmt =
2157         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2158       if (ShAmt == 0 || ShAmt == 2)
2159         --Latency;
2160       break;
2161     }
2162     }
2163   }
2164
2165   return Latency;
2166 }
2167
2168 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2169                                       const MachineInstr *MI,
2170                                       unsigned *PredCost) const {
2171   if (MI->isCopyLike() || MI->isInsertSubreg() ||
2172       MI->isRegSequence() || MI->isImplicitDef())
2173     return 1;
2174
2175   if (!ItinData || ItinData->isEmpty())
2176     return 1;
2177
2178   const TargetInstrDesc &TID = MI->getDesc();
2179   unsigned Class = TID.getSchedClass();
2180   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
2181   if (PredCost && TID.hasImplicitDefOfPhysReg(ARM::CPSR))
2182     // When predicated, CPSR is an additional source operand for CPSR updating
2183     // instructions, this apparently increases their latencies.
2184     *PredCost = 1;
2185   if (UOps)
2186     return ItinData->getStageLatency(Class);
2187   return getNumMicroOps(ItinData, MI);
2188 }
2189
2190 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2191                                       SDNode *Node) const {
2192   if (!Node->isMachineOpcode())
2193     return 1;
2194
2195   if (!ItinData || ItinData->isEmpty())
2196     return 1;
2197
2198   unsigned Opcode = Node->getMachineOpcode();
2199   switch (Opcode) {
2200   default:
2201     return ItinData->getStageLatency(get(Opcode).getSchedClass());
2202   case ARM::VLDMQIA:
2203   case ARM::VLDMQDB:
2204   case ARM::VSTMQIA:
2205   case ARM::VSTMQDB:
2206     return 2;
2207   }
2208 }
2209
2210 bool ARMBaseInstrInfo::
2211 hasHighOperandLatency(const InstrItineraryData *ItinData,
2212                       const MachineRegisterInfo *MRI,
2213                       const MachineInstr *DefMI, unsigned DefIdx,
2214                       const MachineInstr *UseMI, unsigned UseIdx) const {
2215   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2216   unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
2217   if (Subtarget.isCortexA8() &&
2218       (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
2219     // CortexA8 VFP instructions are not pipelined.
2220     return true;
2221
2222   // Hoist VFP / NEON instructions with 4 or higher latency.
2223   int Latency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
2224   if (Latency <= 3)
2225     return false;
2226   return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
2227          UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
2228 }
2229
2230 bool ARMBaseInstrInfo::
2231 hasLowDefLatency(const InstrItineraryData *ItinData,
2232                  const MachineInstr *DefMI, unsigned DefIdx) const {
2233   if (!ItinData || ItinData->isEmpty())
2234     return false;
2235
2236   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2237   if (DDomain == ARMII::DomainGeneral) {
2238     unsigned DefClass = DefMI->getDesc().getSchedClass();
2239     int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2240     return (DefCycle != -1 && DefCycle <= 2);
2241   }
2242   return false;
2243 }
2244
2245 bool
2246 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
2247                                      unsigned &AddSubOpc,
2248                                      bool &NegAcc, bool &HasLane) const {
2249   DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
2250   if (I == MLxEntryMap.end())
2251     return false;
2252
2253   const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
2254   MulOpc = Entry.MulOpc;
2255   AddSubOpc = Entry.AddSubOpc;
2256   NegAcc = Entry.NegAcc;
2257   HasLane = Entry.HasLane;
2258   return true;
2259 }