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