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