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