ARM: remove unnecessary state-tracking during frame lowering.
[oota-llvm.git] / lib / Target / ARM / ARMBaseInstrInfo.cpp
1 //===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===//
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 "ARM.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMFeatures.h"
19 #include "ARMHazardRecognizer.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGNodes.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/Support/BranchProbability.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39
40 #define GET_INSTRINFO_CTOR
41 #include "ARMGenInstrInfo.inc"
42
43 using namespace llvm;
44
45 static cl::opt<bool>
46 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
47                cl::desc("Enable ARM 2-addr to 3-addr conv"));
48
49 static cl::opt<bool>
50 WidenVMOVS("widen-vmovs", cl::Hidden, cl::init(true),
51            cl::desc("Widen ARM vmovs to vmovd when possible"));
52
53 static cl::opt<unsigned>
54 SwiftPartialUpdateClearance("swift-partial-update-clearance",
55      cl::Hidden, cl::init(12),
56      cl::desc("Clearance before partial register updates"));
57
58 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
59 struct ARM_MLxEntry {
60   uint16_t MLxOpc;     // MLA / MLS opcode
61   uint16_t MulOpc;     // Expanded multiplication opcode
62   uint16_t AddSubOpc;  // Expanded add / sub opcode
63   bool NegAcc;         // True if the acc is negated before the add / sub.
64   bool HasLane;        // True if instruction has an extra "lane" operand.
65 };
66
67 static const ARM_MLxEntry ARM_MLxTable[] = {
68   // MLxOpc,          MulOpc,           AddSubOpc,       NegAcc, HasLane
69   // fp scalar ops
70   { ARM::VMLAS,       ARM::VMULS,       ARM::VADDS,      false,  false },
71   { ARM::VMLSS,       ARM::VMULS,       ARM::VSUBS,      false,  false },
72   { ARM::VMLAD,       ARM::VMULD,       ARM::VADDD,      false,  false },
73   { ARM::VMLSD,       ARM::VMULD,       ARM::VSUBD,      false,  false },
74   { ARM::VNMLAS,      ARM::VNMULS,      ARM::VSUBS,      true,   false },
75   { ARM::VNMLSS,      ARM::VMULS,       ARM::VSUBS,      true,   false },
76   { ARM::VNMLAD,      ARM::VNMULD,      ARM::VSUBD,      true,   false },
77   { ARM::VNMLSD,      ARM::VMULD,       ARM::VSUBD,      true,   false },
78
79   // fp SIMD ops
80   { ARM::VMLAfd,      ARM::VMULfd,      ARM::VADDfd,     false,  false },
81   { ARM::VMLSfd,      ARM::VMULfd,      ARM::VSUBfd,     false,  false },
82   { ARM::VMLAfq,      ARM::VMULfq,      ARM::VADDfq,     false,  false },
83   { ARM::VMLSfq,      ARM::VMULfq,      ARM::VSUBfq,     false,  false },
84   { ARM::VMLAslfd,    ARM::VMULslfd,    ARM::VADDfd,     false,  true  },
85   { ARM::VMLSslfd,    ARM::VMULslfd,    ARM::VSUBfd,     false,  true  },
86   { ARM::VMLAslfq,    ARM::VMULslfq,    ARM::VADDfq,     false,  true  },
87   { ARM::VMLSslfq,    ARM::VMULslfq,    ARM::VSUBfq,     false,  true  },
88 };
89
90 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
91   : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
92     Subtarget(STI) {
93   for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
94     if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
95       assert(false && "Duplicated entries?");
96     MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
97     MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
98   }
99 }
100
101 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
102 // currently defaults to no prepass hazard recognizer.
103 ScheduleHazardRecognizer *ARMBaseInstrInfo::
104 CreateTargetHazardRecognizer(const TargetMachine *TM,
105                              const ScheduleDAG *DAG) const {
106   if (usePreRAHazardRecognizer()) {
107     const InstrItineraryData *II = TM->getInstrItineraryData();
108     return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
109   }
110   return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
111 }
112
113 ScheduleHazardRecognizer *ARMBaseInstrInfo::
114 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
115                                    const ScheduleDAG *DAG) const {
116   if (Subtarget.isThumb2() || Subtarget.hasVFP2())
117     return (ScheduleHazardRecognizer *)new ARMHazardRecognizer(II, DAG);
118   return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
119 }
120
121 MachineInstr *
122 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
123                                         MachineBasicBlock::iterator &MBBI,
124                                         LiveVariables *LV) const {
125   // FIXME: Thumb2 support.
126
127   if (!EnableARM3Addr)
128     return NULL;
129
130   MachineInstr *MI = MBBI;
131   MachineFunction &MF = *MI->getParent()->getParent();
132   uint64_t TSFlags = MI->getDesc().TSFlags;
133   bool isPre = false;
134   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
135   default: return NULL;
136   case ARMII::IndexModePre:
137     isPre = true;
138     break;
139   case ARMII::IndexModePost:
140     break;
141   }
142
143   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
144   // operation.
145   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
146   if (MemOpc == 0)
147     return NULL;
148
149   MachineInstr *UpdateMI = NULL;
150   MachineInstr *MemMI = NULL;
151   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
152   const MCInstrDesc &MCID = MI->getDesc();
153   unsigned NumOps = MCID.getNumOperands();
154   bool isLoad = !MI->mayStore();
155   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
156   const MachineOperand &Base = MI->getOperand(2);
157   const MachineOperand &Offset = MI->getOperand(NumOps-3);
158   unsigned WBReg = WB.getReg();
159   unsigned BaseReg = Base.getReg();
160   unsigned OffReg = Offset.getReg();
161   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
162   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
163   switch (AddrMode) {
164   default: llvm_unreachable("Unknown indexed op!");
165   case ARMII::AddrMode2: {
166     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
167     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
168     if (OffReg == 0) {
169       if (ARM_AM::getSOImmVal(Amt) == -1)
170         // Can't encode it in a so_imm operand. This transformation will
171         // add more than 1 instruction. Abandon!
172         return NULL;
173       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
174                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
175         .addReg(BaseReg).addImm(Amt)
176         .addImm(Pred).addReg(0).addReg(0);
177     } else if (Amt != 0) {
178       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
179       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
180       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
181                          get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
182         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
183         .addImm(Pred).addReg(0).addReg(0);
184     } else
185       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
186                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
187         .addReg(BaseReg).addReg(OffReg)
188         .addImm(Pred).addReg(0).addReg(0);
189     break;
190   }
191   case ARMII::AddrMode3 : {
192     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
193     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
194     if (OffReg == 0)
195       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
196       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
197                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
198         .addReg(BaseReg).addImm(Amt)
199         .addImm(Pred).addReg(0).addReg(0);
200     else
201       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
202                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
203         .addReg(BaseReg).addReg(OffReg)
204         .addImm(Pred).addReg(0).addReg(0);
205     break;
206   }
207   }
208
209   std::vector<MachineInstr*> NewMIs;
210   if (isPre) {
211     if (isLoad)
212       MemMI = BuildMI(MF, MI->getDebugLoc(),
213                       get(MemOpc), MI->getOperand(0).getReg())
214         .addReg(WBReg).addImm(0).addImm(Pred);
215     else
216       MemMI = BuildMI(MF, MI->getDebugLoc(),
217                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
218         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
219     NewMIs.push_back(MemMI);
220     NewMIs.push_back(UpdateMI);
221   } else {
222     if (isLoad)
223       MemMI = BuildMI(MF, MI->getDebugLoc(),
224                       get(MemOpc), MI->getOperand(0).getReg())
225         .addReg(BaseReg).addImm(0).addImm(Pred);
226     else
227       MemMI = BuildMI(MF, MI->getDebugLoc(),
228                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
229         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
230     if (WB.isDead())
231       UpdateMI->getOperand(0).setIsDead();
232     NewMIs.push_back(UpdateMI);
233     NewMIs.push_back(MemMI);
234   }
235
236   // Transfer LiveVariables states, kill / dead info.
237   if (LV) {
238     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
239       MachineOperand &MO = MI->getOperand(i);
240       if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
241         unsigned Reg = MO.getReg();
242
243         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
244         if (MO.isDef()) {
245           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
246           if (MO.isDead())
247             LV->addVirtualRegisterDead(Reg, NewMI);
248         }
249         if (MO.isUse() && MO.isKill()) {
250           for (unsigned j = 0; j < 2; ++j) {
251             // Look at the two new MI's in reverse order.
252             MachineInstr *NewMI = NewMIs[j];
253             if (!NewMI->readsRegister(Reg))
254               continue;
255             LV->addVirtualRegisterKilled(Reg, NewMI);
256             if (VI.removeKill(MI))
257               VI.Kills.push_back(NewMI);
258             break;
259           }
260         }
261       }
262     }
263   }
264
265   MFI->insert(MBBI, NewMIs[1]);
266   MFI->insert(MBBI, NewMIs[0]);
267   return NewMIs[0];
268 }
269
270 // Branch analysis.
271 bool
272 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
273                                 MachineBasicBlock *&FBB,
274                                 SmallVectorImpl<MachineOperand> &Cond,
275                                 bool AllowModify) const {
276   TBB = 0;
277   FBB = 0;
278
279   MachineBasicBlock::iterator I = MBB.end();
280   if (I == MBB.begin())
281     return false; // Empty blocks are easy.
282   --I;
283
284   // Walk backwards from the end of the basic block until the branch is
285   // analyzed or we give up.
286   while (isPredicated(I) || I->isTerminator()) {
287
288     // Flag to be raised on unanalyzeable instructions. This is useful in cases
289     // where we want to clean up on the end of the basic block before we bail
290     // out.
291     bool CantAnalyze = false;
292
293     // Skip over DEBUG values and predicated nonterminators.
294     while (I->isDebugValue() || !I->isTerminator()) {
295       if (I == MBB.begin())
296         return false;
297       --I;
298     }
299
300     if (isIndirectBranchOpcode(I->getOpcode()) ||
301         isJumpTableBranchOpcode(I->getOpcode())) {
302       // Indirect branches and jump tables can't be analyzed, but we still want
303       // to clean up any instructions at the tail of the basic block.
304       CantAnalyze = true;
305     } else if (isUncondBranchOpcode(I->getOpcode())) {
306       TBB = I->getOperand(0).getMBB();
307     } else if (isCondBranchOpcode(I->getOpcode())) {
308       // Bail out if we encounter multiple conditional branches.
309       if (!Cond.empty())
310         return true;
311
312       assert(!FBB && "FBB should have been null.");
313       FBB = TBB;
314       TBB = I->getOperand(0).getMBB();
315       Cond.push_back(I->getOperand(1));
316       Cond.push_back(I->getOperand(2));
317     } else if (I->isReturn()) {
318       // Returns can't be analyzed, but we should run cleanup.
319       CantAnalyze = !isPredicated(I);
320     } else {
321       // We encountered other unrecognized terminator. Bail out immediately.
322       return true;
323     }
324
325     // Cleanup code - to be run for unpredicated unconditional branches and
326     //                returns.
327     if (!isPredicated(I) &&
328           (isUncondBranchOpcode(I->getOpcode()) ||
329            isIndirectBranchOpcode(I->getOpcode()) ||
330            isJumpTableBranchOpcode(I->getOpcode()) ||
331            I->isReturn())) {
332       // Forget any previous condition branch information - it no longer applies.
333       Cond.clear();
334       FBB = 0;
335
336       // If we can modify the function, delete everything below this
337       // unconditional branch.
338       if (AllowModify) {
339         MachineBasicBlock::iterator DI = llvm::next(I);
340         while (DI != MBB.end()) {
341           MachineInstr *InstToDelete = DI;
342           ++DI;
343           InstToDelete->eraseFromParent();
344         }
345       }
346     }
347
348     if (CantAnalyze)
349       return true;
350
351     if (I == MBB.begin())
352       return false;
353
354     --I;
355   }
356
357   // We made it past the terminators without bailing out - we must have
358   // analyzed this branch successfully.
359   return false;
360 }
361
362
363 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
364   MachineBasicBlock::iterator I = MBB.end();
365   if (I == MBB.begin()) return 0;
366   --I;
367   while (I->isDebugValue()) {
368     if (I == MBB.begin())
369       return 0;
370     --I;
371   }
372   if (!isUncondBranchOpcode(I->getOpcode()) &&
373       !isCondBranchOpcode(I->getOpcode()))
374     return 0;
375
376   // Remove the branch.
377   I->eraseFromParent();
378
379   I = MBB.end();
380
381   if (I == MBB.begin()) return 1;
382   --I;
383   if (!isCondBranchOpcode(I->getOpcode()))
384     return 1;
385
386   // Remove the branch.
387   I->eraseFromParent();
388   return 2;
389 }
390
391 unsigned
392 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
393                                MachineBasicBlock *FBB,
394                                const SmallVectorImpl<MachineOperand> &Cond,
395                                DebugLoc DL) const {
396   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
397   int BOpc   = !AFI->isThumbFunction()
398     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
399   int BccOpc = !AFI->isThumbFunction()
400     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
401   bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
402
403   // Shouldn't be a fall through.
404   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
405   assert((Cond.size() == 2 || Cond.size() == 0) &&
406          "ARM branch conditions have two components!");
407
408   if (FBB == 0) {
409     if (Cond.empty()) { // Unconditional branch?
410       if (isThumb)
411         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).addImm(ARMCC::AL).addReg(0);
412       else
413         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
414     } else
415       BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
416         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
417     return 1;
418   }
419
420   // Two-way conditional branch.
421   BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
422     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
423   if (isThumb)
424     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).addImm(ARMCC::AL).addReg(0);
425   else
426     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
427   return 2;
428 }
429
430 bool ARMBaseInstrInfo::
431 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
432   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
433   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
434   return false;
435 }
436
437 bool ARMBaseInstrInfo::isPredicated(const MachineInstr *MI) const {
438   if (MI->isBundle()) {
439     MachineBasicBlock::const_instr_iterator I = MI;
440     MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
441     while (++I != E && I->isInsideBundle()) {
442       int PIdx = I->findFirstPredOperandIdx();
443       if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
444         return true;
445     }
446     return false;
447   }
448
449   int PIdx = MI->findFirstPredOperandIdx();
450   return PIdx != -1 && MI->getOperand(PIdx).getImm() != ARMCC::AL;
451 }
452
453 bool ARMBaseInstrInfo::
454 PredicateInstruction(MachineInstr *MI,
455                      const SmallVectorImpl<MachineOperand> &Pred) const {
456   unsigned Opc = MI->getOpcode();
457   if (isUncondBranchOpcode(Opc)) {
458     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
459     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
460       .addImm(Pred[0].getImm())
461       .addReg(Pred[1].getReg());
462     return true;
463   }
464
465   int PIdx = MI->findFirstPredOperandIdx();
466   if (PIdx != -1) {
467     MachineOperand &PMO = MI->getOperand(PIdx);
468     PMO.setImm(Pred[0].getImm());
469     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
470     return true;
471   }
472   return false;
473 }
474
475 bool ARMBaseInstrInfo::
476 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
477                   const SmallVectorImpl<MachineOperand> &Pred2) const {
478   if (Pred1.size() > 2 || Pred2.size() > 2)
479     return false;
480
481   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
482   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
483   if (CC1 == CC2)
484     return true;
485
486   switch (CC1) {
487   default:
488     return false;
489   case ARMCC::AL:
490     return true;
491   case ARMCC::HS:
492     return CC2 == ARMCC::HI;
493   case ARMCC::LS:
494     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
495   case ARMCC::GE:
496     return CC2 == ARMCC::GT;
497   case ARMCC::LE:
498     return CC2 == ARMCC::LT;
499   }
500 }
501
502 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
503                                     std::vector<MachineOperand> &Pred) const {
504   bool Found = false;
505   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
506     const MachineOperand &MO = MI->getOperand(i);
507     if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) ||
508         (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) {
509       Pred.push_back(MO);
510       Found = true;
511     }
512   }
513
514   return Found;
515 }
516
517 /// isPredicable - Return true if the specified instruction can be predicated.
518 /// By default, this returns true for every instruction with a
519 /// PredicateOperand.
520 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
521   if (!MI->isPredicable())
522     return false;
523
524   ARMFunctionInfo *AFI =
525     MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
526
527   if (AFI->isThumb2Function()) {
528     if (getSubtarget().hasV8Ops())
529       return isV8EligibleForIT(MI);
530   } else { // non-Thumb
531     if ((MI->getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
532       return false;
533   }
534
535   return true;
536 }
537
538 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
539 LLVM_ATTRIBUTE_NOINLINE
540 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
541                                 unsigned JTI);
542 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
543                                 unsigned JTI) {
544   assert(JTI < JT.size());
545   return JT[JTI].MBBs.size();
546 }
547
548 /// GetInstSize - Return the size of the specified MachineInstr.
549 ///
550 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
551   const MachineBasicBlock &MBB = *MI->getParent();
552   const MachineFunction *MF = MBB.getParent();
553   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
554
555   const MCInstrDesc &MCID = MI->getDesc();
556   if (MCID.getSize())
557     return MCID.getSize();
558
559   // If this machine instr is an inline asm, measure it.
560   if (MI->getOpcode() == ARM::INLINEASM)
561     return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
562   if (MI->isLabel())
563     return 0;
564   unsigned Opc = MI->getOpcode();
565   switch (Opc) {
566   case TargetOpcode::IMPLICIT_DEF:
567   case TargetOpcode::KILL:
568   case TargetOpcode::PROLOG_LABEL:
569   case TargetOpcode::EH_LABEL:
570   case TargetOpcode::DBG_VALUE:
571     return 0;
572   case TargetOpcode::BUNDLE:
573     return getInstBundleLength(MI);
574   case ARM::MOVi16_ga_pcrel:
575   case ARM::MOVTi16_ga_pcrel:
576   case ARM::t2MOVi16_ga_pcrel:
577   case ARM::t2MOVTi16_ga_pcrel:
578     return 4;
579   case ARM::MOVi32imm:
580   case ARM::t2MOVi32imm:
581     return 8;
582   case ARM::CONSTPOOL_ENTRY:
583     // If this machine instr is a constant pool entry, its size is recorded as
584     // operand #2.
585     return MI->getOperand(2).getImm();
586   case ARM::Int_eh_sjlj_longjmp:
587     return 16;
588   case ARM::tInt_eh_sjlj_longjmp:
589     return 10;
590   case ARM::Int_eh_sjlj_setjmp:
591   case ARM::Int_eh_sjlj_setjmp_nofp:
592     return 20;
593   case ARM::tInt_eh_sjlj_setjmp:
594   case ARM::t2Int_eh_sjlj_setjmp:
595   case ARM::t2Int_eh_sjlj_setjmp_nofp:
596     return 12;
597   case ARM::BR_JTr:
598   case ARM::BR_JTm:
599   case ARM::BR_JTadd:
600   case ARM::tBR_JTr:
601   case ARM::t2BR_JT:
602   case ARM::t2TBB_JT:
603   case ARM::t2TBH_JT: {
604     // These are jumptable branches, i.e. a branch followed by an inlined
605     // jumptable. The size is 4 + 4 * number of entries. For TBB, each
606     // entry is one byte; TBH two byte each.
607     unsigned EntrySize = (Opc == ARM::t2TBB_JT)
608       ? 1 : ((Opc == ARM::t2TBH_JT) ? 2 : 4);
609     unsigned NumOps = MCID.getNumOperands();
610     MachineOperand JTOP =
611       MI->getOperand(NumOps - (MI->isPredicable() ? 3 : 2));
612     unsigned JTI = JTOP.getIndex();
613     const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
614     assert(MJTI != 0);
615     const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
616     assert(JTI < JT.size());
617     // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
618     // 4 aligned. The assembler / linker may add 2 byte padding just before
619     // the JT entries.  The size does not include this padding; the
620     // constant islands pass does separate bookkeeping for it.
621     // FIXME: If we know the size of the function is less than (1 << 16) *2
622     // bytes, we can use 16-bit entries instead. Then there won't be an
623     // alignment issue.
624     unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
625     unsigned NumEntries = getNumJTEntries(JT, JTI);
626     if (Opc == ARM::t2TBB_JT && (NumEntries & 1))
627       // Make sure the instruction that follows TBB is 2-byte aligned.
628       // FIXME: Constant island pass should insert an "ALIGN" instruction
629       // instead.
630       ++NumEntries;
631     return NumEntries * EntrySize + InstSize;
632   }
633   default:
634     // Otherwise, pseudo-instruction sizes are zero.
635     return 0;
636   }
637 }
638
639 unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr *MI) const {
640   unsigned Size = 0;
641   MachineBasicBlock::const_instr_iterator I = MI;
642   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
643   while (++I != E && I->isInsideBundle()) {
644     assert(!I->isBundle() && "No nested bundle!");
645     Size += GetInstSizeInBytes(&*I);
646   }
647   return Size;
648 }
649
650 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
651                                    MachineBasicBlock::iterator I, DebugLoc DL,
652                                    unsigned DestReg, unsigned SrcReg,
653                                    bool KillSrc) const {
654   bool GPRDest = ARM::GPRRegClass.contains(DestReg);
655   bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
656
657   if (GPRDest && GPRSrc) {
658     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
659                                     .addReg(SrcReg, getKillRegState(KillSrc))));
660     return;
661   }
662
663   bool SPRDest = ARM::SPRRegClass.contains(DestReg);
664   bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
665
666   unsigned Opc = 0;
667   if (SPRDest && SPRSrc)
668     Opc = ARM::VMOVS;
669   else if (GPRDest && SPRSrc)
670     Opc = ARM::VMOVRS;
671   else if (SPRDest && GPRSrc)
672     Opc = ARM::VMOVSR;
673   else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
674     Opc = ARM::VMOVD;
675   else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
676     Opc = ARM::VORRq;
677
678   if (Opc) {
679     MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
680     MIB.addReg(SrcReg, getKillRegState(KillSrc));
681     if (Opc == ARM::VORRq)
682       MIB.addReg(SrcReg, getKillRegState(KillSrc));
683     AddDefaultPred(MIB);
684     return;
685   }
686
687   // Handle register classes that require multiple instructions.
688   unsigned BeginIdx = 0;
689   unsigned SubRegs = 0;
690   int Spacing = 1;
691
692   // Use VORRq when possible.
693   if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
694     Opc = ARM::VORRq;
695     BeginIdx = ARM::qsub_0;
696     SubRegs = 2;
697   } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
698     Opc = ARM::VORRq;
699     BeginIdx = ARM::qsub_0;
700     SubRegs = 4;
701   // Fall back to VMOVD.
702   } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
703     Opc = ARM::VMOVD;
704     BeginIdx = ARM::dsub_0;
705     SubRegs = 2;
706   } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
707     Opc = ARM::VMOVD;
708     BeginIdx = ARM::dsub_0;
709     SubRegs = 3;
710   } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
711     Opc = ARM::VMOVD;
712     BeginIdx = ARM::dsub_0;
713     SubRegs = 4;
714   } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
715     Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
716     BeginIdx = ARM::gsub_0;
717     SubRegs = 2;
718   } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
719     Opc = ARM::VMOVD;
720     BeginIdx = ARM::dsub_0;
721     SubRegs = 2;
722     Spacing = 2;
723   } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
724     Opc = ARM::VMOVD;
725     BeginIdx = ARM::dsub_0;
726     SubRegs = 3;
727     Spacing = 2;
728   } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
729     Opc = ARM::VMOVD;
730     BeginIdx = ARM::dsub_0;
731     SubRegs = 4;
732     Spacing = 2;
733   }
734
735   assert(Opc && "Impossible reg-to-reg copy");
736
737   const TargetRegisterInfo *TRI = &getRegisterInfo();
738   MachineInstrBuilder Mov;
739
740   // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
741   if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
742     BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
743     Spacing = -Spacing;
744   }
745 #ifndef NDEBUG
746   SmallSet<unsigned, 4> DstRegs;
747 #endif
748   for (unsigned i = 0; i != SubRegs; ++i) {
749     unsigned Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
750     unsigned Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
751     assert(Dst && Src && "Bad sub-register");
752 #ifndef NDEBUG
753     assert(!DstRegs.count(Src) && "destructive vector copy");
754     DstRegs.insert(Dst);
755 #endif
756     Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
757     // VORR takes two source operands.
758     if (Opc == ARM::VORRq)
759       Mov.addReg(Src);
760     Mov = AddDefaultPred(Mov);
761     // MOVr can set CC.
762     if (Opc == ARM::MOVr)
763       Mov = AddDefaultCC(Mov);
764   }
765   // Add implicit super-register defs and kills to the last instruction.
766   Mov->addRegisterDefined(DestReg, TRI);
767   if (KillSrc)
768     Mov->addRegisterKilled(SrcReg, TRI);
769 }
770
771 const MachineInstrBuilder &
772 ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
773                           unsigned SubIdx, unsigned State,
774                           const TargetRegisterInfo *TRI) const {
775   if (!SubIdx)
776     return MIB.addReg(Reg, State);
777
778   if (TargetRegisterInfo::isPhysicalRegister(Reg))
779     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
780   return MIB.addReg(Reg, State, SubIdx);
781 }
782
783 void ARMBaseInstrInfo::
784 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
785                     unsigned SrcReg, bool isKill, int FI,
786                     const TargetRegisterClass *RC,
787                     const TargetRegisterInfo *TRI) const {
788   DebugLoc DL;
789   if (I != MBB.end()) DL = I->getDebugLoc();
790   MachineFunction &MF = *MBB.getParent();
791   MachineFrameInfo &MFI = *MF.getFrameInfo();
792   unsigned Align = MFI.getObjectAlignment(FI);
793
794   MachineMemOperand *MMO =
795     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
796                             MachineMemOperand::MOStore,
797                             MFI.getObjectSize(FI),
798                             Align);
799
800   switch (RC->getSize()) {
801     case 4:
802       if (ARM::GPRRegClass.hasSubClassEq(RC)) {
803         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
804                    .addReg(SrcReg, getKillRegState(isKill))
805                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
806       } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
807         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
808                    .addReg(SrcReg, getKillRegState(isKill))
809                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
810       } else
811         llvm_unreachable("Unknown reg class!");
812       break;
813     case 8:
814       if (ARM::DPRRegClass.hasSubClassEq(RC)) {
815         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
816                    .addReg(SrcReg, getKillRegState(isKill))
817                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
818       } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
819         if (Subtarget.hasV5TEOps()) {
820           MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::STRD));
821           AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
822           AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
823           MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO);
824
825           AddDefaultPred(MIB);
826         } else {
827           // Fallback to STM instruction, which has existed since the dawn of
828           // time.
829           MachineInstrBuilder MIB =
830             AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STMIA))
831                              .addFrameIndex(FI).addMemOperand(MMO));
832           AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
833           AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
834         }
835       } else
836         llvm_unreachable("Unknown reg class!");
837       break;
838     case 16:
839       if (ARM::DPairRegClass.hasSubClassEq(RC)) {
840         // Use aligned spills if the stack can be realigned.
841         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
842           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64))
843                      .addFrameIndex(FI).addImm(16)
844                      .addReg(SrcReg, getKillRegState(isKill))
845                      .addMemOperand(MMO));
846         } else {
847           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
848                      .addReg(SrcReg, getKillRegState(isKill))
849                      .addFrameIndex(FI)
850                      .addMemOperand(MMO));
851         }
852       } else
853         llvm_unreachable("Unknown reg class!");
854       break;
855     case 24:
856       if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
857         // Use aligned spills if the stack can be realigned.
858         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
859           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64TPseudo))
860                      .addFrameIndex(FI).addImm(16)
861                      .addReg(SrcReg, getKillRegState(isKill))
862                      .addMemOperand(MMO));
863         } else {
864           MachineInstrBuilder MIB =
865           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
866                        .addFrameIndex(FI))
867                        .addMemOperand(MMO);
868           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
869           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
870           AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
871         }
872       } else
873         llvm_unreachable("Unknown reg class!");
874       break;
875     case 32:
876       if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
877         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
878           // FIXME: It's possible to only store part of the QQ register if the
879           // spilled def has a sub-register index.
880           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
881                      .addFrameIndex(FI).addImm(16)
882                      .addReg(SrcReg, getKillRegState(isKill))
883                      .addMemOperand(MMO));
884         } else {
885           MachineInstrBuilder MIB =
886           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
887                        .addFrameIndex(FI))
888                        .addMemOperand(MMO);
889           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
890           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
891           MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
892                 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
893         }
894       } else
895         llvm_unreachable("Unknown reg class!");
896       break;
897     case 64:
898       if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
899         MachineInstrBuilder MIB =
900           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
901                          .addFrameIndex(FI))
902                          .addMemOperand(MMO);
903         MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
904         MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
905         MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
906         MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
907         MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
908         MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
909         MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
910               AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
911       } else
912         llvm_unreachable("Unknown reg class!");
913       break;
914     default:
915       llvm_unreachable("Unknown reg class!");
916   }
917 }
918
919 unsigned
920 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
921                                      int &FrameIndex) const {
922   switch (MI->getOpcode()) {
923   default: break;
924   case ARM::STRrs:
925   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
926     if (MI->getOperand(1).isFI() &&
927         MI->getOperand(2).isReg() &&
928         MI->getOperand(3).isImm() &&
929         MI->getOperand(2).getReg() == 0 &&
930         MI->getOperand(3).getImm() == 0) {
931       FrameIndex = MI->getOperand(1).getIndex();
932       return MI->getOperand(0).getReg();
933     }
934     break;
935   case ARM::STRi12:
936   case ARM::t2STRi12:
937   case ARM::tSTRspi:
938   case ARM::VSTRD:
939   case ARM::VSTRS:
940     if (MI->getOperand(1).isFI() &&
941         MI->getOperand(2).isImm() &&
942         MI->getOperand(2).getImm() == 0) {
943       FrameIndex = MI->getOperand(1).getIndex();
944       return MI->getOperand(0).getReg();
945     }
946     break;
947   case ARM::VST1q64:
948   case ARM::VST1d64TPseudo:
949   case ARM::VST1d64QPseudo:
950     if (MI->getOperand(0).isFI() &&
951         MI->getOperand(2).getSubReg() == 0) {
952       FrameIndex = MI->getOperand(0).getIndex();
953       return MI->getOperand(2).getReg();
954     }
955     break;
956   case ARM::VSTMQIA:
957     if (MI->getOperand(1).isFI() &&
958         MI->getOperand(0).getSubReg() == 0) {
959       FrameIndex = MI->getOperand(1).getIndex();
960       return MI->getOperand(0).getReg();
961     }
962     break;
963   }
964
965   return 0;
966 }
967
968 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
969                                                     int &FrameIndex) const {
970   const MachineMemOperand *Dummy;
971   return MI->mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex);
972 }
973
974 void ARMBaseInstrInfo::
975 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
976                      unsigned DestReg, int FI,
977                      const TargetRegisterClass *RC,
978                      const TargetRegisterInfo *TRI) const {
979   DebugLoc DL;
980   if (I != MBB.end()) DL = I->getDebugLoc();
981   MachineFunction &MF = *MBB.getParent();
982   MachineFrameInfo &MFI = *MF.getFrameInfo();
983   unsigned Align = MFI.getObjectAlignment(FI);
984   MachineMemOperand *MMO =
985     MF.getMachineMemOperand(
986                     MachinePointerInfo::getFixedStack(FI),
987                             MachineMemOperand::MOLoad,
988                             MFI.getObjectSize(FI),
989                             Align);
990
991   switch (RC->getSize()) {
992   case 4:
993     if (ARM::GPRRegClass.hasSubClassEq(RC)) {
994       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
995                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
996
997     } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
998       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
999                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
1000     } else
1001       llvm_unreachable("Unknown reg class!");
1002     break;
1003   case 8:
1004     if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1005       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
1006                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
1007     } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1008       MachineInstrBuilder MIB;
1009
1010       if (Subtarget.hasV5TEOps()) {
1011         MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
1012         AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1013         AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1014         MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO);
1015
1016         AddDefaultPred(MIB);
1017       } else {
1018         // Fallback to LDM instruction, which has existed since the dawn of
1019         // time.
1020         MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDMIA))
1021                                  .addFrameIndex(FI).addMemOperand(MMO));
1022         MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1023         MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1024       }
1025
1026       if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1027         MIB.addReg(DestReg, RegState::ImplicitDefine);
1028     } else
1029       llvm_unreachable("Unknown reg class!");
1030     break;
1031   case 16:
1032     if (ARM::DPairRegClass.hasSubClassEq(RC)) {
1033       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1034         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
1035                      .addFrameIndex(FI).addImm(16)
1036                      .addMemOperand(MMO));
1037       } else {
1038         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
1039                        .addFrameIndex(FI)
1040                        .addMemOperand(MMO));
1041       }
1042     } else
1043       llvm_unreachable("Unknown reg class!");
1044     break;
1045   case 24:
1046     if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1047       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1048         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
1049                      .addFrameIndex(FI).addImm(16)
1050                      .addMemOperand(MMO));
1051       } else {
1052         MachineInstrBuilder MIB =
1053           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1054                          .addFrameIndex(FI)
1055                          .addMemOperand(MMO));
1056         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1057         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1058         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1059         if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1060           MIB.addReg(DestReg, RegState::ImplicitDefine);
1061       }
1062     } else
1063       llvm_unreachable("Unknown reg class!");
1064     break;
1065    case 32:
1066     if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1067       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1068         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
1069                      .addFrameIndex(FI).addImm(16)
1070                      .addMemOperand(MMO));
1071       } else {
1072         MachineInstrBuilder MIB =
1073         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1074                        .addFrameIndex(FI))
1075                        .addMemOperand(MMO);
1076         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1077         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1078         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1079         MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1080         if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1081           MIB.addReg(DestReg, RegState::ImplicitDefine);
1082       }
1083     } else
1084       llvm_unreachable("Unknown reg class!");
1085     break;
1086   case 64:
1087     if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1088       MachineInstrBuilder MIB =
1089       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1090                      .addFrameIndex(FI))
1091                      .addMemOperand(MMO);
1092       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1093       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1094       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1095       MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1096       MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
1097       MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
1098       MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
1099       MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
1100       if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1101         MIB.addReg(DestReg, RegState::ImplicitDefine);
1102     } else
1103       llvm_unreachable("Unknown reg class!");
1104     break;
1105   default:
1106     llvm_unreachable("Unknown regclass!");
1107   }
1108 }
1109
1110 unsigned
1111 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
1112                                       int &FrameIndex) const {
1113   switch (MI->getOpcode()) {
1114   default: break;
1115   case ARM::LDRrs:
1116   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
1117     if (MI->getOperand(1).isFI() &&
1118         MI->getOperand(2).isReg() &&
1119         MI->getOperand(3).isImm() &&
1120         MI->getOperand(2).getReg() == 0 &&
1121         MI->getOperand(3).getImm() == 0) {
1122       FrameIndex = MI->getOperand(1).getIndex();
1123       return MI->getOperand(0).getReg();
1124     }
1125     break;
1126   case ARM::LDRi12:
1127   case ARM::t2LDRi12:
1128   case ARM::tLDRspi:
1129   case ARM::VLDRD:
1130   case ARM::VLDRS:
1131     if (MI->getOperand(1).isFI() &&
1132         MI->getOperand(2).isImm() &&
1133         MI->getOperand(2).getImm() == 0) {
1134       FrameIndex = MI->getOperand(1).getIndex();
1135       return MI->getOperand(0).getReg();
1136     }
1137     break;
1138   case ARM::VLD1q64:
1139   case ARM::VLD1d64TPseudo:
1140   case ARM::VLD1d64QPseudo:
1141     if (MI->getOperand(1).isFI() &&
1142         MI->getOperand(0).getSubReg() == 0) {
1143       FrameIndex = MI->getOperand(1).getIndex();
1144       return MI->getOperand(0).getReg();
1145     }
1146     break;
1147   case ARM::VLDMQIA:
1148     if (MI->getOperand(1).isFI() &&
1149         MI->getOperand(0).getSubReg() == 0) {
1150       FrameIndex = MI->getOperand(1).getIndex();
1151       return MI->getOperand(0).getReg();
1152     }
1153     break;
1154   }
1155
1156   return 0;
1157 }
1158
1159 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI,
1160                                              int &FrameIndex) const {
1161   const MachineMemOperand *Dummy;
1162   return MI->mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex);
1163 }
1164
1165 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const{
1166   // This hook gets to expand COPY instructions before they become
1167   // copyPhysReg() calls.  Look for VMOVS instructions that can legally be
1168   // widened to VMOVD.  We prefer the VMOVD when possible because it may be
1169   // changed into a VORR that can go down the NEON pipeline.
1170   if (!WidenVMOVS || !MI->isCopy() || Subtarget.isCortexA15())
1171     return false;
1172
1173   // Look for a copy between even S-registers.  That is where we keep floats
1174   // when using NEON v2f32 instructions for f32 arithmetic.
1175   unsigned DstRegS = MI->getOperand(0).getReg();
1176   unsigned SrcRegS = MI->getOperand(1).getReg();
1177   if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1178     return false;
1179
1180   const TargetRegisterInfo *TRI = &getRegisterInfo();
1181   unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1182                                               &ARM::DPRRegClass);
1183   unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1184                                               &ARM::DPRRegClass);
1185   if (!DstRegD || !SrcRegD)
1186     return false;
1187
1188   // We want to widen this into a DstRegD = VMOVD SrcRegD copy.  This is only
1189   // legal if the COPY already defines the full DstRegD, and it isn't a
1190   // sub-register insertion.
1191   if (!MI->definesRegister(DstRegD, TRI) || MI->readsRegister(DstRegD, TRI))
1192     return false;
1193
1194   // A dead copy shouldn't show up here, but reject it just in case.
1195   if (MI->getOperand(0).isDead())
1196     return false;
1197
1198   // All clear, widen the COPY.
1199   DEBUG(dbgs() << "widening:    " << *MI);
1200   MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
1201
1202   // Get rid of the old <imp-def> of DstRegD.  Leave it if it defines a Q-reg
1203   // or some other super-register.
1204   int ImpDefIdx = MI->findRegisterDefOperandIdx(DstRegD);
1205   if (ImpDefIdx != -1)
1206     MI->RemoveOperand(ImpDefIdx);
1207
1208   // Change the opcode and operands.
1209   MI->setDesc(get(ARM::VMOVD));
1210   MI->getOperand(0).setReg(DstRegD);
1211   MI->getOperand(1).setReg(SrcRegD);
1212   AddDefaultPred(MIB);
1213
1214   // We are now reading SrcRegD instead of SrcRegS.  This may upset the
1215   // register scavenger and machine verifier, so we need to indicate that we
1216   // are reading an undefined value from SrcRegD, but a proper value from
1217   // SrcRegS.
1218   MI->getOperand(1).setIsUndef();
1219   MIB.addReg(SrcRegS, RegState::Implicit);
1220
1221   // SrcRegD may actually contain an unrelated value in the ssub_1
1222   // sub-register.  Don't kill it.  Only kill the ssub_0 sub-register.
1223   if (MI->getOperand(1).isKill()) {
1224     MI->getOperand(1).setIsKill(false);
1225     MI->addRegisterKilled(SrcRegS, TRI, true);
1226   }
1227
1228   DEBUG(dbgs() << "replaced by: " << *MI);
1229   return true;
1230 }
1231
1232 /// Create a copy of a const pool value. Update CPI to the new index and return
1233 /// the label UID.
1234 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1235   MachineConstantPool *MCP = MF.getConstantPool();
1236   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1237
1238   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1239   assert(MCPE.isMachineConstantPoolEntry() &&
1240          "Expecting a machine constantpool entry!");
1241   ARMConstantPoolValue *ACPV =
1242     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1243
1244   unsigned PCLabelId = AFI->createPICLabelUId();
1245   ARMConstantPoolValue *NewCPV = 0;
1246   // FIXME: The below assumes PIC relocation model and that the function
1247   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1248   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1249   // instructions, so that's probably OK, but is PIC always correct when
1250   // we get here?
1251   if (ACPV->isGlobalValue())
1252     NewCPV = ARMConstantPoolConstant::
1253       Create(cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId,
1254              ARMCP::CPValue, 4);
1255   else if (ACPV->isExtSymbol())
1256     NewCPV = ARMConstantPoolSymbol::
1257       Create(MF.getFunction()->getContext(),
1258              cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1259   else if (ACPV->isBlockAddress())
1260     NewCPV = ARMConstantPoolConstant::
1261       Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1262              ARMCP::CPBlockAddress, 4);
1263   else if (ACPV->isLSDA())
1264     NewCPV = ARMConstantPoolConstant::Create(MF.getFunction(), PCLabelId,
1265                                              ARMCP::CPLSDA, 4);
1266   else if (ACPV->isMachineBasicBlock())
1267     NewCPV = ARMConstantPoolMBB::
1268       Create(MF.getFunction()->getContext(),
1269              cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1270   else
1271     llvm_unreachable("Unexpected ARM constantpool value type!!");
1272   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1273   return PCLabelId;
1274 }
1275
1276 void ARMBaseInstrInfo::
1277 reMaterialize(MachineBasicBlock &MBB,
1278               MachineBasicBlock::iterator I,
1279               unsigned DestReg, unsigned SubIdx,
1280               const MachineInstr *Orig,
1281               const TargetRegisterInfo &TRI) const {
1282   unsigned Opcode = Orig->getOpcode();
1283   switch (Opcode) {
1284   default: {
1285     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1286     MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1287     MBB.insert(I, MI);
1288     break;
1289   }
1290   case ARM::tLDRpci_pic:
1291   case ARM::t2LDRpci_pic: {
1292     MachineFunction &MF = *MBB.getParent();
1293     unsigned CPI = Orig->getOperand(1).getIndex();
1294     unsigned PCLabelId = duplicateCPV(MF, CPI);
1295     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1296                                       DestReg)
1297       .addConstantPoolIndex(CPI).addImm(PCLabelId);
1298     MIB->setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1299     break;
1300   }
1301   }
1302 }
1303
1304 MachineInstr *
1305 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1306   MachineInstr *MI = TargetInstrInfo::duplicate(Orig, MF);
1307   switch(Orig->getOpcode()) {
1308   case ARM::tLDRpci_pic:
1309   case ARM::t2LDRpci_pic: {
1310     unsigned CPI = Orig->getOperand(1).getIndex();
1311     unsigned PCLabelId = duplicateCPV(MF, CPI);
1312     Orig->getOperand(1).setIndex(CPI);
1313     Orig->getOperand(2).setImm(PCLabelId);
1314     break;
1315   }
1316   }
1317   return MI;
1318 }
1319
1320 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1321                                         const MachineInstr *MI1,
1322                                         const MachineRegisterInfo *MRI) const {
1323   int Opcode = MI0->getOpcode();
1324   if (Opcode == ARM::t2LDRpci ||
1325       Opcode == ARM::t2LDRpci_pic ||
1326       Opcode == ARM::tLDRpci ||
1327       Opcode == ARM::tLDRpci_pic ||
1328       Opcode == ARM::MOV_ga_dyn ||
1329       Opcode == ARM::MOV_ga_pcrel ||
1330       Opcode == ARM::MOV_ga_pcrel_ldr ||
1331       Opcode == ARM::t2MOV_ga_dyn ||
1332       Opcode == ARM::t2MOV_ga_pcrel) {
1333     if (MI1->getOpcode() != Opcode)
1334       return false;
1335     if (MI0->getNumOperands() != MI1->getNumOperands())
1336       return false;
1337
1338     const MachineOperand &MO0 = MI0->getOperand(1);
1339     const MachineOperand &MO1 = MI1->getOperand(1);
1340     if (MO0.getOffset() != MO1.getOffset())
1341       return false;
1342
1343     if (Opcode == ARM::MOV_ga_dyn ||
1344         Opcode == ARM::MOV_ga_pcrel ||
1345         Opcode == ARM::MOV_ga_pcrel_ldr ||
1346         Opcode == ARM::t2MOV_ga_dyn ||
1347         Opcode == ARM::t2MOV_ga_pcrel)
1348       // Ignore the PC labels.
1349       return MO0.getGlobal() == MO1.getGlobal();
1350
1351     const MachineFunction *MF = MI0->getParent()->getParent();
1352     const MachineConstantPool *MCP = MF->getConstantPool();
1353     int CPI0 = MO0.getIndex();
1354     int CPI1 = MO1.getIndex();
1355     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1356     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1357     bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1358     bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1359     if (isARMCP0 && isARMCP1) {
1360       ARMConstantPoolValue *ACPV0 =
1361         static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1362       ARMConstantPoolValue *ACPV1 =
1363         static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1364       return ACPV0->hasSameValue(ACPV1);
1365     } else if (!isARMCP0 && !isARMCP1) {
1366       return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1367     }
1368     return false;
1369   } else if (Opcode == ARM::PICLDR) {
1370     if (MI1->getOpcode() != Opcode)
1371       return false;
1372     if (MI0->getNumOperands() != MI1->getNumOperands())
1373       return false;
1374
1375     unsigned Addr0 = MI0->getOperand(1).getReg();
1376     unsigned Addr1 = MI1->getOperand(1).getReg();
1377     if (Addr0 != Addr1) {
1378       if (!MRI ||
1379           !TargetRegisterInfo::isVirtualRegister(Addr0) ||
1380           !TargetRegisterInfo::isVirtualRegister(Addr1))
1381         return false;
1382
1383       // This assumes SSA form.
1384       MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1385       MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1386       // Check if the loaded value, e.g. a constantpool of a global address, are
1387       // the same.
1388       if (!produceSameValue(Def0, Def1, MRI))
1389         return false;
1390     }
1391
1392     for (unsigned i = 3, e = MI0->getNumOperands(); i != e; ++i) {
1393       // %vreg12<def> = PICLDR %vreg11, 0, pred:14, pred:%noreg
1394       const MachineOperand &MO0 = MI0->getOperand(i);
1395       const MachineOperand &MO1 = MI1->getOperand(i);
1396       if (!MO0.isIdenticalTo(MO1))
1397         return false;
1398     }
1399     return true;
1400   }
1401
1402   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1403 }
1404
1405 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1406 /// determine if two loads are loading from the same base address. It should
1407 /// only return true if the base pointers are the same and the only differences
1408 /// between the two addresses is the offset. It also returns the offsets by
1409 /// reference.
1410 ///
1411 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1412 /// is permanently disabled.
1413 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1414                                                int64_t &Offset1,
1415                                                int64_t &Offset2) const {
1416   // Don't worry about Thumb: just ARM and Thumb2.
1417   if (Subtarget.isThumb1Only()) return false;
1418
1419   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1420     return false;
1421
1422   switch (Load1->getMachineOpcode()) {
1423   default:
1424     return false;
1425   case ARM::LDRi12:
1426   case ARM::LDRBi12:
1427   case ARM::LDRD:
1428   case ARM::LDRH:
1429   case ARM::LDRSB:
1430   case ARM::LDRSH:
1431   case ARM::VLDRD:
1432   case ARM::VLDRS:
1433   case ARM::t2LDRi8:
1434   case ARM::t2LDRBi8:
1435   case ARM::t2LDRDi8:
1436   case ARM::t2LDRSHi8:
1437   case ARM::t2LDRi12:
1438   case ARM::t2LDRBi12:
1439   case ARM::t2LDRSHi12:
1440     break;
1441   }
1442
1443   switch (Load2->getMachineOpcode()) {
1444   default:
1445     return false;
1446   case ARM::LDRi12:
1447   case ARM::LDRBi12:
1448   case ARM::LDRD:
1449   case ARM::LDRH:
1450   case ARM::LDRSB:
1451   case ARM::LDRSH:
1452   case ARM::VLDRD:
1453   case ARM::VLDRS:
1454   case ARM::t2LDRi8:
1455   case ARM::t2LDRBi8:
1456   case ARM::t2LDRSHi8:
1457   case ARM::t2LDRi12:
1458   case ARM::t2LDRBi12:
1459   case ARM::t2LDRSHi12:
1460     break;
1461   }
1462
1463   // Check if base addresses and chain operands match.
1464   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1465       Load1->getOperand(4) != Load2->getOperand(4))
1466     return false;
1467
1468   // Index should be Reg0.
1469   if (Load1->getOperand(3) != Load2->getOperand(3))
1470     return false;
1471
1472   // Determine the offsets.
1473   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1474       isa<ConstantSDNode>(Load2->getOperand(1))) {
1475     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1476     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1477     return true;
1478   }
1479
1480   return false;
1481 }
1482
1483 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1484 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1485 /// be scheduled togther. On some targets if two loads are loading from
1486 /// addresses in the same cache line, it's better if they are scheduled
1487 /// together. This function takes two integers that represent the load offsets
1488 /// from the common base address. It returns true if it decides it's desirable
1489 /// to schedule the two loads together. "NumLoads" is the number of loads that
1490 /// have already been scheduled after Load1.
1491 ///
1492 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1493 /// is permanently disabled.
1494 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1495                                                int64_t Offset1, int64_t Offset2,
1496                                                unsigned NumLoads) const {
1497   // Don't worry about Thumb: just ARM and Thumb2.
1498   if (Subtarget.isThumb1Only()) return false;
1499
1500   assert(Offset2 > Offset1);
1501
1502   if ((Offset2 - Offset1) / 8 > 64)
1503     return false;
1504
1505   // Check if the machine opcodes are different. If they are different
1506   // then we consider them to not be of the same base address,
1507   // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
1508   // In this case, they are considered to be the same because they are different
1509   // encoding forms of the same basic instruction.
1510   if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
1511       !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
1512          Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
1513         (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
1514          Load2->getMachineOpcode() == ARM::t2LDRBi8)))
1515     return false;  // FIXME: overly conservative?
1516
1517   // Four loads in a row should be sufficient.
1518   if (NumLoads >= 3)
1519     return false;
1520
1521   return true;
1522 }
1523
1524 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1525                                             const MachineBasicBlock *MBB,
1526                                             const MachineFunction &MF) const {
1527   // Debug info is never a scheduling boundary. It's necessary to be explicit
1528   // due to the special treatment of IT instructions below, otherwise a
1529   // dbg_value followed by an IT will result in the IT instruction being
1530   // considered a scheduling hazard, which is wrong. It should be the actual
1531   // instruction preceding the dbg_value instruction(s), just like it is
1532   // when debug info is not present.
1533   if (MI->isDebugValue())
1534     return false;
1535
1536   // Terminators and labels can't be scheduled around.
1537   if (MI->isTerminator() || MI->isLabel())
1538     return true;
1539
1540   // Treat the start of the IT block as a scheduling boundary, but schedule
1541   // t2IT along with all instructions following it.
1542   // FIXME: This is a big hammer. But the alternative is to add all potential
1543   // true and anti dependencies to IT block instructions as implicit operands
1544   // to the t2IT instruction. The added compile time and complexity does not
1545   // seem worth it.
1546   MachineBasicBlock::const_iterator I = MI;
1547   // Make sure to skip any dbg_value instructions
1548   while (++I != MBB->end() && I->isDebugValue())
1549     ;
1550   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1551     return true;
1552
1553   // Don't attempt to schedule around any instruction that defines
1554   // a stack-oriented pointer, as it's unlikely to be profitable. This
1555   // saves compile time, because it doesn't require every single
1556   // stack slot reference to depend on the instruction that does the
1557   // modification.
1558   // Calls don't actually change the stack pointer, even if they have imp-defs.
1559   // No ARM calling conventions change the stack pointer. (X86 calling
1560   // conventions sometimes do).
1561   if (!MI->isCall() && MI->definesRegister(ARM::SP))
1562     return true;
1563
1564   return false;
1565 }
1566
1567 bool ARMBaseInstrInfo::
1568 isProfitableToIfCvt(MachineBasicBlock &MBB,
1569                     unsigned NumCycles, unsigned ExtraPredCycles,
1570                     const BranchProbability &Probability) const {
1571   if (!NumCycles)
1572     return false;
1573
1574   // Attempt to estimate the relative costs of predication versus branching.
1575   unsigned UnpredCost = Probability.getNumerator() * NumCycles;
1576   UnpredCost /= Probability.getDenominator();
1577   UnpredCost += 1; // The branch itself
1578   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1579
1580   return (NumCycles + ExtraPredCycles) <= UnpredCost;
1581 }
1582
1583 bool ARMBaseInstrInfo::
1584 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1585                     unsigned TCycles, unsigned TExtra,
1586                     MachineBasicBlock &FMBB,
1587                     unsigned FCycles, unsigned FExtra,
1588                     const BranchProbability &Probability) const {
1589   if (!TCycles || !FCycles)
1590     return false;
1591
1592   // Attempt to estimate the relative costs of predication versus branching.
1593   unsigned TUnpredCost = Probability.getNumerator() * TCycles;
1594   TUnpredCost /= Probability.getDenominator();
1595
1596   uint32_t Comp = Probability.getDenominator() - Probability.getNumerator();
1597   unsigned FUnpredCost = Comp * FCycles;
1598   FUnpredCost /= Probability.getDenominator();
1599
1600   unsigned UnpredCost = TUnpredCost + FUnpredCost;
1601   UnpredCost += 1; // The branch itself
1602   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1603
1604   return (TCycles + FCycles + TExtra + FExtra) <= UnpredCost;
1605 }
1606
1607 bool
1608 ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
1609                                             MachineBasicBlock &FMBB) const {
1610   // Reduce false anti-dependencies to let Swift's out-of-order execution
1611   // engine do its thing.
1612   return Subtarget.isSwift();
1613 }
1614
1615 /// getInstrPredicate - If instruction is predicated, returns its predicate
1616 /// condition, otherwise returns AL. It also returns the condition code
1617 /// register by reference.
1618 ARMCC::CondCodes
1619 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1620   int PIdx = MI->findFirstPredOperandIdx();
1621   if (PIdx == -1) {
1622     PredReg = 0;
1623     return ARMCC::AL;
1624   }
1625
1626   PredReg = MI->getOperand(PIdx+1).getReg();
1627   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1628 }
1629
1630
1631 int llvm::getMatchingCondBranchOpcode(int Opc) {
1632   if (Opc == ARM::B)
1633     return ARM::Bcc;
1634   if (Opc == ARM::tB)
1635     return ARM::tBcc;
1636   if (Opc == ARM::t2B)
1637     return ARM::t2Bcc;
1638
1639   llvm_unreachable("Unknown unconditional branch opcode!");
1640 }
1641
1642 /// commuteInstruction - Handle commutable instructions.
1643 MachineInstr *
1644 ARMBaseInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
1645   switch (MI->getOpcode()) {
1646   case ARM::MOVCCr:
1647   case ARM::t2MOVCCr: {
1648     // MOVCC can be commuted by inverting the condition.
1649     unsigned PredReg = 0;
1650     ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
1651     // MOVCC AL can't be inverted. Shouldn't happen.
1652     if (CC == ARMCC::AL || PredReg != ARM::CPSR)
1653       return NULL;
1654     MI = TargetInstrInfo::commuteInstruction(MI, NewMI);
1655     if (!MI)
1656       return NULL;
1657     // After swapping the MOVCC operands, also invert the condition.
1658     MI->getOperand(MI->findFirstPredOperandIdx())
1659       .setImm(ARMCC::getOppositeCondition(CC));
1660     return MI;
1661   }
1662   }
1663   return TargetInstrInfo::commuteInstruction(MI, NewMI);
1664 }
1665
1666 /// Identify instructions that can be folded into a MOVCC instruction, and
1667 /// return the defining instruction.
1668 static MachineInstr *canFoldIntoMOVCC(unsigned Reg,
1669                                       const MachineRegisterInfo &MRI,
1670                                       const TargetInstrInfo *TII) {
1671   if (!TargetRegisterInfo::isVirtualRegister(Reg))
1672     return 0;
1673   if (!MRI.hasOneNonDBGUse(Reg))
1674     return 0;
1675   MachineInstr *MI = MRI.getVRegDef(Reg);
1676   if (!MI)
1677     return 0;
1678   // MI is folded into the MOVCC by predicating it.
1679   if (!MI->isPredicable())
1680     return 0;
1681   // Check if MI has any non-dead defs or physreg uses. This also detects
1682   // predicated instructions which will be reading CPSR.
1683   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
1684     const MachineOperand &MO = MI->getOperand(i);
1685     // Reject frame index operands, PEI can't handle the predicated pseudos.
1686     if (MO.isFI() || MO.isCPI() || MO.isJTI())
1687       return 0;
1688     if (!MO.isReg())
1689       continue;
1690     // MI can't have any tied operands, that would conflict with predication.
1691     if (MO.isTied())
1692       return 0;
1693     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1694       return 0;
1695     if (MO.isDef() && !MO.isDead())
1696       return 0;
1697   }
1698   bool DontMoveAcrossStores = true;
1699   if (!MI->isSafeToMove(TII, /* AliasAnalysis = */ 0, DontMoveAcrossStores))
1700     return 0;
1701   return MI;
1702 }
1703
1704 bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr *MI,
1705                                      SmallVectorImpl<MachineOperand> &Cond,
1706                                      unsigned &TrueOp, unsigned &FalseOp,
1707                                      bool &Optimizable) const {
1708   assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) &&
1709          "Unknown select instruction");
1710   // MOVCC operands:
1711   // 0: Def.
1712   // 1: True use.
1713   // 2: False use.
1714   // 3: Condition code.
1715   // 4: CPSR use.
1716   TrueOp = 1;
1717   FalseOp = 2;
1718   Cond.push_back(MI->getOperand(3));
1719   Cond.push_back(MI->getOperand(4));
1720   // We can always fold a def.
1721   Optimizable = true;
1722   return false;
1723 }
1724
1725 MachineInstr *ARMBaseInstrInfo::optimizeSelect(MachineInstr *MI,
1726                                                bool PreferFalse) const {
1727   assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) &&
1728          "Unknown select instruction");
1729   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1730   MachineInstr *DefMI = canFoldIntoMOVCC(MI->getOperand(2).getReg(), MRI, this);
1731   bool Invert = !DefMI;
1732   if (!DefMI)
1733     DefMI = canFoldIntoMOVCC(MI->getOperand(1).getReg(), MRI, this);
1734   if (!DefMI)
1735     return 0;
1736
1737   // Find new register class to use.
1738   MachineOperand FalseReg = MI->getOperand(Invert ? 2 : 1);
1739   unsigned       DestReg  = MI->getOperand(0).getReg();
1740   const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());
1741   if (!MRI.constrainRegClass(DestReg, PreviousClass))
1742     return 0;
1743
1744   // Create a new predicated version of DefMI.
1745   // Rfalse is the first use.
1746   MachineInstrBuilder NewMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1747                                       DefMI->getDesc(), DestReg);
1748
1749   // Copy all the DefMI operands, excluding its (null) predicate.
1750   const MCInstrDesc &DefDesc = DefMI->getDesc();
1751   for (unsigned i = 1, e = DefDesc.getNumOperands();
1752        i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
1753     NewMI.addOperand(DefMI->getOperand(i));
1754
1755   unsigned CondCode = MI->getOperand(3).getImm();
1756   if (Invert)
1757     NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
1758   else
1759     NewMI.addImm(CondCode);
1760   NewMI.addOperand(MI->getOperand(4));
1761
1762   // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
1763   if (NewMI->hasOptionalDef())
1764     AddDefaultCC(NewMI);
1765
1766   // The output register value when the predicate is false is an implicit
1767   // register operand tied to the first def.
1768   // The tie makes the register allocator ensure the FalseReg is allocated the
1769   // same register as operand 0.
1770   FalseReg.setImplicit();
1771   NewMI.addOperand(FalseReg);
1772   NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
1773
1774   // The caller will erase MI, but not DefMI.
1775   DefMI->eraseFromParent();
1776   return NewMI;
1777 }
1778
1779 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
1780 /// instruction is encoded with an 'S' bit is determined by the optional CPSR
1781 /// def operand.
1782 ///
1783 /// This will go away once we can teach tblgen how to set the optional CPSR def
1784 /// operand itself.
1785 struct AddSubFlagsOpcodePair {
1786   uint16_t PseudoOpc;
1787   uint16_t MachineOpc;
1788 };
1789
1790 static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
1791   {ARM::ADDSri, ARM::ADDri},
1792   {ARM::ADDSrr, ARM::ADDrr},
1793   {ARM::ADDSrsi, ARM::ADDrsi},
1794   {ARM::ADDSrsr, ARM::ADDrsr},
1795
1796   {ARM::SUBSri, ARM::SUBri},
1797   {ARM::SUBSrr, ARM::SUBrr},
1798   {ARM::SUBSrsi, ARM::SUBrsi},
1799   {ARM::SUBSrsr, ARM::SUBrsr},
1800
1801   {ARM::RSBSri, ARM::RSBri},
1802   {ARM::RSBSrsi, ARM::RSBrsi},
1803   {ARM::RSBSrsr, ARM::RSBrsr},
1804
1805   {ARM::t2ADDSri, ARM::t2ADDri},
1806   {ARM::t2ADDSrr, ARM::t2ADDrr},
1807   {ARM::t2ADDSrs, ARM::t2ADDrs},
1808
1809   {ARM::t2SUBSri, ARM::t2SUBri},
1810   {ARM::t2SUBSrr, ARM::t2SUBrr},
1811   {ARM::t2SUBSrs, ARM::t2SUBrs},
1812
1813   {ARM::t2RSBSri, ARM::t2RSBri},
1814   {ARM::t2RSBSrs, ARM::t2RSBrs},
1815 };
1816
1817 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
1818   for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
1819     if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
1820       return AddSubFlagsOpcodeMap[i].MachineOpc;
1821   return 0;
1822 }
1823
1824 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1825                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1826                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1827                                ARMCC::CondCodes Pred, unsigned PredReg,
1828                                const ARMBaseInstrInfo &TII, unsigned MIFlags) {
1829   if (NumBytes == 0 && DestReg != BaseReg) {
1830     BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
1831       .addReg(BaseReg, RegState::Kill)
1832       .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1833       .setMIFlags(MIFlags);
1834     return;
1835   }
1836
1837   bool isSub = NumBytes < 0;
1838   if (isSub) NumBytes = -NumBytes;
1839
1840   while (NumBytes) {
1841     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1842     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1843     assert(ThisVal && "Didn't extract field correctly");
1844
1845     // We will handle these bits from offset, clear them.
1846     NumBytes &= ~ThisVal;
1847
1848     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1849
1850     // Build the new ADD / SUB.
1851     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1852     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1853       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1854       .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1855       .setMIFlags(MIFlags);
1856     BaseReg = DestReg;
1857   }
1858 }
1859
1860 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1861                                 unsigned FrameReg, int &Offset,
1862                                 const ARMBaseInstrInfo &TII) {
1863   unsigned Opcode = MI.getOpcode();
1864   const MCInstrDesc &Desc = MI.getDesc();
1865   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1866   bool isSub = false;
1867
1868   // Memory operands in inline assembly always use AddrMode2.
1869   if (Opcode == ARM::INLINEASM)
1870     AddrMode = ARMII::AddrMode2;
1871
1872   if (Opcode == ARM::ADDri) {
1873     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1874     if (Offset == 0) {
1875       // Turn it into a move.
1876       MI.setDesc(TII.get(ARM::MOVr));
1877       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1878       MI.RemoveOperand(FrameRegIdx+1);
1879       Offset = 0;
1880       return true;
1881     } else if (Offset < 0) {
1882       Offset = -Offset;
1883       isSub = true;
1884       MI.setDesc(TII.get(ARM::SUBri));
1885     }
1886
1887     // Common case: small offset, fits into instruction.
1888     if (ARM_AM::getSOImmVal(Offset) != -1) {
1889       // Replace the FrameIndex with sp / fp
1890       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1891       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1892       Offset = 0;
1893       return true;
1894     }
1895
1896     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1897     // as possible.
1898     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1899     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1900
1901     // We will handle these bits from offset, clear them.
1902     Offset &= ~ThisImmVal;
1903
1904     // Get the properly encoded SOImmVal field.
1905     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1906            "Bit extraction didn't work?");
1907     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1908  } else {
1909     unsigned ImmIdx = 0;
1910     int InstrOffs = 0;
1911     unsigned NumBits = 0;
1912     unsigned Scale = 1;
1913     switch (AddrMode) {
1914     case ARMII::AddrMode_i12: {
1915       ImmIdx = FrameRegIdx + 1;
1916       InstrOffs = MI.getOperand(ImmIdx).getImm();
1917       NumBits = 12;
1918       break;
1919     }
1920     case ARMII::AddrMode2: {
1921       ImmIdx = FrameRegIdx+2;
1922       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1923       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1924         InstrOffs *= -1;
1925       NumBits = 12;
1926       break;
1927     }
1928     case ARMII::AddrMode3: {
1929       ImmIdx = FrameRegIdx+2;
1930       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1931       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1932         InstrOffs *= -1;
1933       NumBits = 8;
1934       break;
1935     }
1936     case ARMII::AddrMode4:
1937     case ARMII::AddrMode6:
1938       // Can't fold any offset even if it's zero.
1939       return false;
1940     case ARMII::AddrMode5: {
1941       ImmIdx = FrameRegIdx+1;
1942       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1943       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1944         InstrOffs *= -1;
1945       NumBits = 8;
1946       Scale = 4;
1947       break;
1948     }
1949     default:
1950       llvm_unreachable("Unsupported addressing mode!");
1951     }
1952
1953     Offset += InstrOffs * Scale;
1954     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1955     if (Offset < 0) {
1956       Offset = -Offset;
1957       isSub = true;
1958     }
1959
1960     // Attempt to fold address comp. if opcode has offset bits
1961     if (NumBits > 0) {
1962       // Common case: small offset, fits into instruction.
1963       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1964       int ImmedOffset = Offset / Scale;
1965       unsigned Mask = (1 << NumBits) - 1;
1966       if ((unsigned)Offset <= Mask * Scale) {
1967         // Replace the FrameIndex with sp
1968         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1969         // FIXME: When addrmode2 goes away, this will simplify (like the
1970         // T2 version), as the LDR.i12 versions don't need the encoding
1971         // tricks for the offset value.
1972         if (isSub) {
1973           if (AddrMode == ARMII::AddrMode_i12)
1974             ImmedOffset = -ImmedOffset;
1975           else
1976             ImmedOffset |= 1 << NumBits;
1977         }
1978         ImmOp.ChangeToImmediate(ImmedOffset);
1979         Offset = 0;
1980         return true;
1981       }
1982
1983       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1984       ImmedOffset = ImmedOffset & Mask;
1985       if (isSub) {
1986         if (AddrMode == ARMII::AddrMode_i12)
1987           ImmedOffset = -ImmedOffset;
1988         else
1989           ImmedOffset |= 1 << NumBits;
1990       }
1991       ImmOp.ChangeToImmediate(ImmedOffset);
1992       Offset &= ~(Mask*Scale);
1993     }
1994   }
1995
1996   Offset = (isSub) ? -Offset : Offset;
1997   return Offset == 0;
1998 }
1999
2000 /// analyzeCompare - For a comparison instruction, return the source registers
2001 /// in SrcReg and SrcReg2 if having two register operands, and the value it
2002 /// compares against in CmpValue. Return true if the comparison instruction
2003 /// can be analyzed.
2004 bool ARMBaseInstrInfo::
2005 analyzeCompare(const MachineInstr *MI, unsigned &SrcReg, unsigned &SrcReg2,
2006                int &CmpMask, int &CmpValue) const {
2007   switch (MI->getOpcode()) {
2008   default: break;
2009   case ARM::CMPri:
2010   case ARM::t2CMPri:
2011     SrcReg = MI->getOperand(0).getReg();
2012     SrcReg2 = 0;
2013     CmpMask = ~0;
2014     CmpValue = MI->getOperand(1).getImm();
2015     return true;
2016   case ARM::CMPrr:
2017   case ARM::t2CMPrr:
2018     SrcReg = MI->getOperand(0).getReg();
2019     SrcReg2 = MI->getOperand(1).getReg();
2020     CmpMask = ~0;
2021     CmpValue = 0;
2022     return true;
2023   case ARM::TSTri:
2024   case ARM::t2TSTri:
2025     SrcReg = MI->getOperand(0).getReg();
2026     SrcReg2 = 0;
2027     CmpMask = MI->getOperand(1).getImm();
2028     CmpValue = 0;
2029     return true;
2030   }
2031
2032   return false;
2033 }
2034
2035 /// isSuitableForMask - Identify a suitable 'and' instruction that
2036 /// operates on the given source register and applies the same mask
2037 /// as a 'tst' instruction. Provide a limited look-through for copies.
2038 /// When successful, MI will hold the found instruction.
2039 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
2040                               int CmpMask, bool CommonUse) {
2041   switch (MI->getOpcode()) {
2042     case ARM::ANDri:
2043     case ARM::t2ANDri:
2044       if (CmpMask != MI->getOperand(2).getImm())
2045         return false;
2046       if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
2047         return true;
2048       break;
2049     case ARM::COPY: {
2050       // Walk down one instruction which is potentially an 'and'.
2051       const MachineInstr &Copy = *MI;
2052       MachineBasicBlock::iterator AND(
2053         llvm::next(MachineBasicBlock::iterator(MI)));
2054       if (AND == MI->getParent()->end()) return false;
2055       MI = AND;
2056       return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
2057                                CmpMask, true);
2058     }
2059   }
2060
2061   return false;
2062 }
2063
2064 /// getSwappedCondition - assume the flags are set by MI(a,b), return
2065 /// the condition code if we modify the instructions such that flags are
2066 /// set by MI(b,a).
2067 inline static ARMCC::CondCodes getSwappedCondition(ARMCC::CondCodes CC) {
2068   switch (CC) {
2069   default: return ARMCC::AL;
2070   case ARMCC::EQ: return ARMCC::EQ;
2071   case ARMCC::NE: return ARMCC::NE;
2072   case ARMCC::HS: return ARMCC::LS;
2073   case ARMCC::LO: return ARMCC::HI;
2074   case ARMCC::HI: return ARMCC::LO;
2075   case ARMCC::LS: return ARMCC::HS;
2076   case ARMCC::GE: return ARMCC::LE;
2077   case ARMCC::LT: return ARMCC::GT;
2078   case ARMCC::GT: return ARMCC::LT;
2079   case ARMCC::LE: return ARMCC::GE;
2080   }
2081 }
2082
2083 /// isRedundantFlagInstr - check whether the first instruction, whose only
2084 /// purpose is to update flags, can be made redundant.
2085 /// CMPrr can be made redundant by SUBrr if the operands are the same.
2086 /// CMPri can be made redundant by SUBri if the operands are the same.
2087 /// This function can be extended later on.
2088 inline static bool isRedundantFlagInstr(MachineInstr *CmpI, unsigned SrcReg,
2089                                         unsigned SrcReg2, int ImmValue,
2090                                         MachineInstr *OI) {
2091   if ((CmpI->getOpcode() == ARM::CMPrr ||
2092        CmpI->getOpcode() == ARM::t2CMPrr) &&
2093       (OI->getOpcode() == ARM::SUBrr ||
2094        OI->getOpcode() == ARM::t2SUBrr) &&
2095       ((OI->getOperand(1).getReg() == SrcReg &&
2096         OI->getOperand(2).getReg() == SrcReg2) ||
2097        (OI->getOperand(1).getReg() == SrcReg2 &&
2098         OI->getOperand(2).getReg() == SrcReg)))
2099     return true;
2100
2101   if ((CmpI->getOpcode() == ARM::CMPri ||
2102        CmpI->getOpcode() == ARM::t2CMPri) &&
2103       (OI->getOpcode() == ARM::SUBri ||
2104        OI->getOpcode() == ARM::t2SUBri) &&
2105       OI->getOperand(1).getReg() == SrcReg &&
2106       OI->getOperand(2).getImm() == ImmValue)
2107     return true;
2108   return false;
2109 }
2110
2111 /// optimizeCompareInstr - Convert the instruction supplying the argument to the
2112 /// comparison into one that sets the zero bit in the flags register;
2113 /// Remove a redundant Compare instruction if an earlier instruction can set the
2114 /// flags in the same way as Compare.
2115 /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
2116 /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
2117 /// condition code of instructions which use the flags.
2118 bool ARMBaseInstrInfo::
2119 optimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, unsigned SrcReg2,
2120                      int CmpMask, int CmpValue,
2121                      const MachineRegisterInfo *MRI) const {
2122   // Get the unique definition of SrcReg.
2123   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2124   if (!MI) return false;
2125
2126   // Masked compares sometimes use the same register as the corresponding 'and'.
2127   if (CmpMask != ~0) {
2128     if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(MI)) {
2129       MI = 0;
2130       for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
2131            UE = MRI->use_end(); UI != UE; ++UI) {
2132         if (UI->getParent() != CmpInstr->getParent()) continue;
2133         MachineInstr *PotentialAND = &*UI;
2134         if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
2135             isPredicated(PotentialAND))
2136           continue;
2137         MI = PotentialAND;
2138         break;
2139       }
2140       if (!MI) return false;
2141     }
2142   }
2143
2144   // Get ready to iterate backward from CmpInstr.
2145   MachineBasicBlock::iterator I = CmpInstr, E = MI,
2146                               B = CmpInstr->getParent()->begin();
2147
2148   // Early exit if CmpInstr is at the beginning of the BB.
2149   if (I == B) return false;
2150
2151   // There are two possible candidates which can be changed to set CPSR:
2152   // One is MI, the other is a SUB instruction.
2153   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
2154   // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
2155   MachineInstr *Sub = NULL;
2156   if (SrcReg2 != 0)
2157     // MI is not a candidate for CMPrr.
2158     MI = NULL;
2159   else if (MI->getParent() != CmpInstr->getParent() || CmpValue != 0) {
2160     // Conservatively refuse to convert an instruction which isn't in the same
2161     // BB as the comparison.
2162     // For CMPri, we need to check Sub, thus we can't return here.
2163     if (CmpInstr->getOpcode() == ARM::CMPri ||
2164        CmpInstr->getOpcode() == ARM::t2CMPri)
2165       MI = NULL;
2166     else
2167       return false;
2168   }
2169
2170   // Check that CPSR isn't set between the comparison instruction and the one we
2171   // want to change. At the same time, search for Sub.
2172   const TargetRegisterInfo *TRI = &getRegisterInfo();
2173   --I;
2174   for (; I != E; --I) {
2175     const MachineInstr &Instr = *I;
2176
2177     if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
2178         Instr.readsRegister(ARM::CPSR, TRI))
2179       // This instruction modifies or uses CPSR after the one we want to
2180       // change. We can't do this transformation.
2181       return false;
2182
2183     // Check whether CmpInstr can be made redundant by the current instruction.
2184     if (isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpValue, &*I)) {
2185       Sub = &*I;
2186       break;
2187     }
2188
2189     if (I == B)
2190       // The 'and' is below the comparison instruction.
2191       return false;
2192   }
2193
2194   // Return false if no candidates exist.
2195   if (!MI && !Sub)
2196     return false;
2197
2198   // The single candidate is called MI.
2199   if (!MI) MI = Sub;
2200
2201   // We can't use a predicated instruction - it doesn't always write the flags.
2202   if (isPredicated(MI))
2203     return false;
2204
2205   switch (MI->getOpcode()) {
2206   default: break;
2207   case ARM::RSBrr:
2208   case ARM::RSBri:
2209   case ARM::RSCrr:
2210   case ARM::RSCri:
2211   case ARM::ADDrr:
2212   case ARM::ADDri:
2213   case ARM::ADCrr:
2214   case ARM::ADCri:
2215   case ARM::SUBrr:
2216   case ARM::SUBri:
2217   case ARM::SBCrr:
2218   case ARM::SBCri:
2219   case ARM::t2RSBri:
2220   case ARM::t2ADDrr:
2221   case ARM::t2ADDri:
2222   case ARM::t2ADCrr:
2223   case ARM::t2ADCri:
2224   case ARM::t2SUBrr:
2225   case ARM::t2SUBri:
2226   case ARM::t2SBCrr:
2227   case ARM::t2SBCri:
2228   case ARM::ANDrr:
2229   case ARM::ANDri:
2230   case ARM::t2ANDrr:
2231   case ARM::t2ANDri:
2232   case ARM::ORRrr:
2233   case ARM::ORRri:
2234   case ARM::t2ORRrr:
2235   case ARM::t2ORRri:
2236   case ARM::EORrr:
2237   case ARM::EORri:
2238   case ARM::t2EORrr:
2239   case ARM::t2EORri: {
2240     // Scan forward for the use of CPSR
2241     // When checking against MI: if it's a conditional code requires
2242     // checking of V bit, then this is not safe to do.
2243     // It is safe to remove CmpInstr if CPSR is redefined or killed.
2244     // If we are done with the basic block, we need to check whether CPSR is
2245     // live-out.
2246     SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
2247         OperandsToUpdate;
2248     bool isSafe = false;
2249     I = CmpInstr;
2250     E = CmpInstr->getParent()->end();
2251     while (!isSafe && ++I != E) {
2252       const MachineInstr &Instr = *I;
2253       for (unsigned IO = 0, EO = Instr.getNumOperands();
2254            !isSafe && IO != EO; ++IO) {
2255         const MachineOperand &MO = Instr.getOperand(IO);
2256         if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
2257           isSafe = true;
2258           break;
2259         }
2260         if (!MO.isReg() || MO.getReg() != ARM::CPSR)
2261           continue;
2262         if (MO.isDef()) {
2263           isSafe = true;
2264           break;
2265         }
2266         // Condition code is after the operand before CPSR.
2267         ARMCC::CondCodes CC = (ARMCC::CondCodes)Instr.getOperand(IO-1).getImm();
2268         if (Sub) {
2269           ARMCC::CondCodes NewCC = getSwappedCondition(CC);
2270           if (NewCC == ARMCC::AL)
2271             return false;
2272           // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
2273           // on CMP needs to be updated to be based on SUB.
2274           // Push the condition code operands to OperandsToUpdate.
2275           // If it is safe to remove CmpInstr, the condition code of these
2276           // operands will be modified.
2277           if (SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
2278               Sub->getOperand(2).getReg() == SrcReg)
2279             OperandsToUpdate.push_back(std::make_pair(&((*I).getOperand(IO-1)),
2280                                                       NewCC));
2281         }
2282         else
2283           switch (CC) {
2284           default:
2285             // CPSR can be used multiple times, we should continue.
2286             break;
2287           case ARMCC::VS:
2288           case ARMCC::VC:
2289           case ARMCC::GE:
2290           case ARMCC::LT:
2291           case ARMCC::GT:
2292           case ARMCC::LE:
2293             return false;
2294           }
2295       }
2296     }
2297
2298     // If CPSR is not killed nor re-defined, we should check whether it is
2299     // live-out. If it is live-out, do not optimize.
2300     if (!isSafe) {
2301       MachineBasicBlock *MBB = CmpInstr->getParent();
2302       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
2303                SE = MBB->succ_end(); SI != SE; ++SI)
2304         if ((*SI)->isLiveIn(ARM::CPSR))
2305           return false;
2306     }
2307
2308     // Toggle the optional operand to CPSR.
2309     MI->getOperand(5).setReg(ARM::CPSR);
2310     MI->getOperand(5).setIsDef(true);
2311     assert(!isPredicated(MI) && "Can't use flags from predicated instruction");
2312     CmpInstr->eraseFromParent();
2313
2314     // Modify the condition code of operands in OperandsToUpdate.
2315     // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2316     // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2317     for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
2318       OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
2319     return true;
2320   }
2321   }
2322
2323   return false;
2324 }
2325
2326 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
2327                                      MachineInstr *DefMI, unsigned Reg,
2328                                      MachineRegisterInfo *MRI) const {
2329   // Fold large immediates into add, sub, or, xor.
2330   unsigned DefOpc = DefMI->getOpcode();
2331   if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
2332     return false;
2333   if (!DefMI->getOperand(1).isImm())
2334     // Could be t2MOVi32imm <ga:xx>
2335     return false;
2336
2337   if (!MRI->hasOneNonDBGUse(Reg))
2338     return false;
2339
2340   const MCInstrDesc &DefMCID = DefMI->getDesc();
2341   if (DefMCID.hasOptionalDef()) {
2342     unsigned NumOps = DefMCID.getNumOperands();
2343     const MachineOperand &MO = DefMI->getOperand(NumOps-1);
2344     if (MO.getReg() == ARM::CPSR && !MO.isDead())
2345       // If DefMI defines CPSR and it is not dead, it's obviously not safe
2346       // to delete DefMI.
2347       return false;
2348   }
2349
2350   const MCInstrDesc &UseMCID = UseMI->getDesc();
2351   if (UseMCID.hasOptionalDef()) {
2352     unsigned NumOps = UseMCID.getNumOperands();
2353     if (UseMI->getOperand(NumOps-1).getReg() == ARM::CPSR)
2354       // If the instruction sets the flag, do not attempt this optimization
2355       // since it may change the semantics of the code.
2356       return false;
2357   }
2358
2359   unsigned UseOpc = UseMI->getOpcode();
2360   unsigned NewUseOpc = 0;
2361   uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
2362   uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
2363   bool Commute = false;
2364   switch (UseOpc) {
2365   default: return false;
2366   case ARM::SUBrr:
2367   case ARM::ADDrr:
2368   case ARM::ORRrr:
2369   case ARM::EORrr:
2370   case ARM::t2SUBrr:
2371   case ARM::t2ADDrr:
2372   case ARM::t2ORRrr:
2373   case ARM::t2EORrr: {
2374     Commute = UseMI->getOperand(2).getReg() != Reg;
2375     switch (UseOpc) {
2376     default: break;
2377     case ARM::SUBrr: {
2378       if (Commute)
2379         return false;
2380       ImmVal = -ImmVal;
2381       NewUseOpc = ARM::SUBri;
2382       // Fallthrough
2383     }
2384     case ARM::ADDrr:
2385     case ARM::ORRrr:
2386     case ARM::EORrr: {
2387       if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
2388         return false;
2389       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
2390       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
2391       switch (UseOpc) {
2392       default: break;
2393       case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
2394       case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
2395       case ARM::EORrr: NewUseOpc = ARM::EORri; break;
2396       }
2397       break;
2398     }
2399     case ARM::t2SUBrr: {
2400       if (Commute)
2401         return false;
2402       ImmVal = -ImmVal;
2403       NewUseOpc = ARM::t2SUBri;
2404       // Fallthrough
2405     }
2406     case ARM::t2ADDrr:
2407     case ARM::t2ORRrr:
2408     case ARM::t2EORrr: {
2409       if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
2410         return false;
2411       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
2412       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
2413       switch (UseOpc) {
2414       default: break;
2415       case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
2416       case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
2417       case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
2418       }
2419       break;
2420     }
2421     }
2422   }
2423   }
2424
2425   unsigned OpIdx = Commute ? 2 : 1;
2426   unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
2427   bool isKill = UseMI->getOperand(OpIdx).isKill();
2428   unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
2429   AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
2430                                       UseMI, UseMI->getDebugLoc(),
2431                                       get(NewUseOpc), NewReg)
2432                               .addReg(Reg1, getKillRegState(isKill))
2433                               .addImm(SOImmValV1)));
2434   UseMI->setDesc(get(NewUseOpc));
2435   UseMI->getOperand(1).setReg(NewReg);
2436   UseMI->getOperand(1).setIsKill();
2437   UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
2438   DefMI->eraseFromParent();
2439   return true;
2440 }
2441
2442 static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
2443                                         const MachineInstr *MI) {
2444   switch (MI->getOpcode()) {
2445   default: {
2446     const MCInstrDesc &Desc = MI->getDesc();
2447     int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
2448     assert(UOps >= 0 && "bad # UOps");
2449     return UOps;
2450   }
2451
2452   case ARM::LDRrs:
2453   case ARM::LDRBrs:
2454   case ARM::STRrs:
2455   case ARM::STRBrs: {
2456     unsigned ShOpVal = MI->getOperand(3).getImm();
2457     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2458     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2459     if (!isSub &&
2460         (ShImm == 0 ||
2461          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2462           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2463       return 1;
2464     return 2;
2465   }
2466
2467   case ARM::LDRH:
2468   case ARM::STRH: {
2469     if (!MI->getOperand(2).getReg())
2470       return 1;
2471
2472     unsigned ShOpVal = MI->getOperand(3).getImm();
2473     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2474     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2475     if (!isSub &&
2476         (ShImm == 0 ||
2477          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2478           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2479       return 1;
2480     return 2;
2481   }
2482
2483   case ARM::LDRSB:
2484   case ARM::LDRSH:
2485     return (ARM_AM::getAM3Op(MI->getOperand(3).getImm()) == ARM_AM::sub) ? 3:2;
2486
2487   case ARM::LDRSB_POST:
2488   case ARM::LDRSH_POST: {
2489     unsigned Rt = MI->getOperand(0).getReg();
2490     unsigned Rm = MI->getOperand(3).getReg();
2491     return (Rt == Rm) ? 4 : 3;
2492   }
2493
2494   case ARM::LDR_PRE_REG:
2495   case ARM::LDRB_PRE_REG: {
2496     unsigned Rt = MI->getOperand(0).getReg();
2497     unsigned Rm = MI->getOperand(3).getReg();
2498     if (Rt == Rm)
2499       return 3;
2500     unsigned ShOpVal = MI->getOperand(4).getImm();
2501     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2502     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2503     if (!isSub &&
2504         (ShImm == 0 ||
2505          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2506           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2507       return 2;
2508     return 3;
2509   }
2510
2511   case ARM::STR_PRE_REG:
2512   case ARM::STRB_PRE_REG: {
2513     unsigned ShOpVal = MI->getOperand(4).getImm();
2514     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2515     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2516     if (!isSub &&
2517         (ShImm == 0 ||
2518          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2519           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2520       return 2;
2521     return 3;
2522   }
2523
2524   case ARM::LDRH_PRE:
2525   case ARM::STRH_PRE: {
2526     unsigned Rt = MI->getOperand(0).getReg();
2527     unsigned Rm = MI->getOperand(3).getReg();
2528     if (!Rm)
2529       return 2;
2530     if (Rt == Rm)
2531       return 3;
2532     return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub)
2533       ? 3 : 2;
2534   }
2535
2536   case ARM::LDR_POST_REG:
2537   case ARM::LDRB_POST_REG:
2538   case ARM::LDRH_POST: {
2539     unsigned Rt = MI->getOperand(0).getReg();
2540     unsigned Rm = MI->getOperand(3).getReg();
2541     return (Rt == Rm) ? 3 : 2;
2542   }
2543
2544   case ARM::LDR_PRE_IMM:
2545   case ARM::LDRB_PRE_IMM:
2546   case ARM::LDR_POST_IMM:
2547   case ARM::LDRB_POST_IMM:
2548   case ARM::STRB_POST_IMM:
2549   case ARM::STRB_POST_REG:
2550   case ARM::STRB_PRE_IMM:
2551   case ARM::STRH_POST:
2552   case ARM::STR_POST_IMM:
2553   case ARM::STR_POST_REG:
2554   case ARM::STR_PRE_IMM:
2555     return 2;
2556
2557   case ARM::LDRSB_PRE:
2558   case ARM::LDRSH_PRE: {
2559     unsigned Rm = MI->getOperand(3).getReg();
2560     if (Rm == 0)
2561       return 3;
2562     unsigned Rt = MI->getOperand(0).getReg();
2563     if (Rt == Rm)
2564       return 4;
2565     unsigned ShOpVal = MI->getOperand(4).getImm();
2566     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2567     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2568     if (!isSub &&
2569         (ShImm == 0 ||
2570          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2571           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2572       return 3;
2573     return 4;
2574   }
2575
2576   case ARM::LDRD: {
2577     unsigned Rt = MI->getOperand(0).getReg();
2578     unsigned Rn = MI->getOperand(2).getReg();
2579     unsigned Rm = MI->getOperand(3).getReg();
2580     if (Rm)
2581       return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3;
2582     return (Rt == Rn) ? 3 : 2;
2583   }
2584
2585   case ARM::STRD: {
2586     unsigned Rm = MI->getOperand(3).getReg();
2587     if (Rm)
2588       return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3;
2589     return 2;
2590   }
2591
2592   case ARM::LDRD_POST:
2593   case ARM::t2LDRD_POST:
2594     return 3;
2595
2596   case ARM::STRD_POST:
2597   case ARM::t2STRD_POST:
2598     return 4;
2599
2600   case ARM::LDRD_PRE: {
2601     unsigned Rt = MI->getOperand(0).getReg();
2602     unsigned Rn = MI->getOperand(3).getReg();
2603     unsigned Rm = MI->getOperand(4).getReg();
2604     if (Rm)
2605       return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4;
2606     return (Rt == Rn) ? 4 : 3;
2607   }
2608
2609   case ARM::t2LDRD_PRE: {
2610     unsigned Rt = MI->getOperand(0).getReg();
2611     unsigned Rn = MI->getOperand(3).getReg();
2612     return (Rt == Rn) ? 4 : 3;
2613   }
2614
2615   case ARM::STRD_PRE: {
2616     unsigned Rm = MI->getOperand(4).getReg();
2617     if (Rm)
2618       return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4;
2619     return 3;
2620   }
2621
2622   case ARM::t2STRD_PRE:
2623     return 3;
2624
2625   case ARM::t2LDR_POST:
2626   case ARM::t2LDRB_POST:
2627   case ARM::t2LDRB_PRE:
2628   case ARM::t2LDRSBi12:
2629   case ARM::t2LDRSBi8:
2630   case ARM::t2LDRSBpci:
2631   case ARM::t2LDRSBs:
2632   case ARM::t2LDRH_POST:
2633   case ARM::t2LDRH_PRE:
2634   case ARM::t2LDRSBT:
2635   case ARM::t2LDRSB_POST:
2636   case ARM::t2LDRSB_PRE:
2637   case ARM::t2LDRSH_POST:
2638   case ARM::t2LDRSH_PRE:
2639   case ARM::t2LDRSHi12:
2640   case ARM::t2LDRSHi8:
2641   case ARM::t2LDRSHpci:
2642   case ARM::t2LDRSHs:
2643     return 2;
2644
2645   case ARM::t2LDRDi8: {
2646     unsigned Rt = MI->getOperand(0).getReg();
2647     unsigned Rn = MI->getOperand(2).getReg();
2648     return (Rt == Rn) ? 3 : 2;
2649   }
2650
2651   case ARM::t2STRB_POST:
2652   case ARM::t2STRB_PRE:
2653   case ARM::t2STRBs:
2654   case ARM::t2STRDi8:
2655   case ARM::t2STRH_POST:
2656   case ARM::t2STRH_PRE:
2657   case ARM::t2STRHs:
2658   case ARM::t2STR_POST:
2659   case ARM::t2STR_PRE:
2660   case ARM::t2STRs:
2661     return 2;
2662   }
2663 }
2664
2665 // Return the number of 32-bit words loaded by LDM or stored by STM. If this
2666 // can't be easily determined return 0 (missing MachineMemOperand).
2667 //
2668 // FIXME: The current MachineInstr design does not support relying on machine
2669 // mem operands to determine the width of a memory access. Instead, we expect
2670 // the target to provide this information based on the instruction opcode and
2671 // operands. However, using MachineMemOperand is a the best solution now for
2672 // two reasons:
2673 //
2674 // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
2675 // operands. This is much more dangerous than using the MachineMemOperand
2676 // sizes because CodeGen passes can insert/remove optional machine operands. In
2677 // fact, it's totally incorrect for preRA passes and appears to be wrong for
2678 // postRA passes as well.
2679 //
2680 // 2) getNumLDMAddresses is only used by the scheduling machine model and any
2681 // machine model that calls this should handle the unknown (zero size) case.
2682 //
2683 // Long term, we should require a target hook that verifies MachineMemOperand
2684 // sizes during MC lowering. That target hook should be local to MC lowering
2685 // because we can't ensure that it is aware of other MI forms. Doing this will
2686 // ensure that MachineMemOperands are correctly propagated through all passes.
2687 unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr *MI) const {
2688   unsigned Size = 0;
2689   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
2690          E = MI->memoperands_end(); I != E; ++I) {
2691     Size += (*I)->getSize();
2692   }
2693   return Size / 4;
2694 }
2695
2696 unsigned
2697 ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
2698                                  const MachineInstr *MI) const {
2699   if (!ItinData || ItinData->isEmpty())
2700     return 1;
2701
2702   const MCInstrDesc &Desc = MI->getDesc();
2703   unsigned Class = Desc.getSchedClass();
2704   int ItinUOps = ItinData->getNumMicroOps(Class);
2705   if (ItinUOps >= 0) {
2706     if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
2707       return getNumMicroOpsSwiftLdSt(ItinData, MI);
2708
2709     return ItinUOps;
2710   }
2711
2712   unsigned Opc = MI->getOpcode();
2713   switch (Opc) {
2714   default:
2715     llvm_unreachable("Unexpected multi-uops instruction!");
2716   case ARM::VLDMQIA:
2717   case ARM::VSTMQIA:
2718     return 2;
2719
2720   // The number of uOps for load / store multiple are determined by the number
2721   // registers.
2722   //
2723   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
2724   // same cycle. The scheduling for the first load / store must be done
2725   // separately by assuming the address is not 64-bit aligned.
2726   //
2727   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
2728   // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
2729   // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
2730   case ARM::VLDMDIA:
2731   case ARM::VLDMDIA_UPD:
2732   case ARM::VLDMDDB_UPD:
2733   case ARM::VLDMSIA:
2734   case ARM::VLDMSIA_UPD:
2735   case ARM::VLDMSDB_UPD:
2736   case ARM::VSTMDIA:
2737   case ARM::VSTMDIA_UPD:
2738   case ARM::VSTMDDB_UPD:
2739   case ARM::VSTMSIA:
2740   case ARM::VSTMSIA_UPD:
2741   case ARM::VSTMSDB_UPD: {
2742     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
2743     return (NumRegs / 2) + (NumRegs % 2) + 1;
2744   }
2745
2746   case ARM::LDMIA_RET:
2747   case ARM::LDMIA:
2748   case ARM::LDMDA:
2749   case ARM::LDMDB:
2750   case ARM::LDMIB:
2751   case ARM::LDMIA_UPD:
2752   case ARM::LDMDA_UPD:
2753   case ARM::LDMDB_UPD:
2754   case ARM::LDMIB_UPD:
2755   case ARM::STMIA:
2756   case ARM::STMDA:
2757   case ARM::STMDB:
2758   case ARM::STMIB:
2759   case ARM::STMIA_UPD:
2760   case ARM::STMDA_UPD:
2761   case ARM::STMDB_UPD:
2762   case ARM::STMIB_UPD:
2763   case ARM::tLDMIA:
2764   case ARM::tLDMIA_UPD:
2765   case ARM::tSTMIA_UPD:
2766   case ARM::tPOP_RET:
2767   case ARM::tPOP:
2768   case ARM::tPUSH:
2769   case ARM::t2LDMIA_RET:
2770   case ARM::t2LDMIA:
2771   case ARM::t2LDMDB:
2772   case ARM::t2LDMIA_UPD:
2773   case ARM::t2LDMDB_UPD:
2774   case ARM::t2STMIA:
2775   case ARM::t2STMDB:
2776   case ARM::t2STMIA_UPD:
2777   case ARM::t2STMDB_UPD: {
2778     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
2779     if (Subtarget.isSwift()) {
2780       int UOps = 1 + NumRegs;  // One for address computation, one for each ld / st.
2781       switch (Opc) {
2782       default: break;
2783       case ARM::VLDMDIA_UPD:
2784       case ARM::VLDMDDB_UPD:
2785       case ARM::VLDMSIA_UPD:
2786       case ARM::VLDMSDB_UPD:
2787       case ARM::VSTMDIA_UPD:
2788       case ARM::VSTMDDB_UPD:
2789       case ARM::VSTMSIA_UPD:
2790       case ARM::VSTMSDB_UPD:
2791       case ARM::LDMIA_UPD:
2792       case ARM::LDMDA_UPD:
2793       case ARM::LDMDB_UPD:
2794       case ARM::LDMIB_UPD:
2795       case ARM::STMIA_UPD:
2796       case ARM::STMDA_UPD:
2797       case ARM::STMDB_UPD:
2798       case ARM::STMIB_UPD:
2799       case ARM::tLDMIA_UPD:
2800       case ARM::tSTMIA_UPD:
2801       case ARM::t2LDMIA_UPD:
2802       case ARM::t2LDMDB_UPD:
2803       case ARM::t2STMIA_UPD:
2804       case ARM::t2STMDB_UPD:
2805         ++UOps; // One for base register writeback.
2806         break;
2807       case ARM::LDMIA_RET:
2808       case ARM::tPOP_RET:
2809       case ARM::t2LDMIA_RET:
2810         UOps += 2; // One for base reg wb, one for write to pc.
2811         break;
2812       }
2813       return UOps;
2814     } else if (Subtarget.isCortexA8()) {
2815       if (NumRegs < 4)
2816         return 2;
2817       // 4 registers would be issued: 2, 2.
2818       // 5 registers would be issued: 2, 2, 1.
2819       int A8UOps = (NumRegs / 2);
2820       if (NumRegs % 2)
2821         ++A8UOps;
2822       return A8UOps;
2823     } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2824       int A9UOps = (NumRegs / 2);
2825       // If there are odd number of registers or if it's not 64-bit aligned,
2826       // then it takes an extra AGU (Address Generation Unit) cycle.
2827       if ((NumRegs % 2) ||
2828           !MI->hasOneMemOperand() ||
2829           (*MI->memoperands_begin())->getAlignment() < 8)
2830         ++A9UOps;
2831       return A9UOps;
2832     } else {
2833       // Assume the worst.
2834       return NumRegs;
2835     }
2836   }
2837   }
2838 }
2839
2840 int
2841 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
2842                                   const MCInstrDesc &DefMCID,
2843                                   unsigned DefClass,
2844                                   unsigned DefIdx, unsigned DefAlign) const {
2845   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2846   if (RegNo <= 0)
2847     // Def is the address writeback.
2848     return ItinData->getOperandCycle(DefClass, DefIdx);
2849
2850   int DefCycle;
2851   if (Subtarget.isCortexA8()) {
2852     // (regno / 2) + (regno % 2) + 1
2853     DefCycle = RegNo / 2 + 1;
2854     if (RegNo % 2)
2855       ++DefCycle;
2856   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2857     DefCycle = RegNo;
2858     bool isSLoad = false;
2859
2860     switch (DefMCID.getOpcode()) {
2861     default: break;
2862     case ARM::VLDMSIA:
2863     case ARM::VLDMSIA_UPD:
2864     case ARM::VLDMSDB_UPD:
2865       isSLoad = true;
2866       break;
2867     }
2868
2869     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2870     // then it takes an extra cycle.
2871     if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
2872       ++DefCycle;
2873   } else {
2874     // Assume the worst.
2875     DefCycle = RegNo + 2;
2876   }
2877
2878   return DefCycle;
2879 }
2880
2881 int
2882 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
2883                                  const MCInstrDesc &DefMCID,
2884                                  unsigned DefClass,
2885                                  unsigned DefIdx, unsigned DefAlign) const {
2886   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2887   if (RegNo <= 0)
2888     // Def is the address writeback.
2889     return ItinData->getOperandCycle(DefClass, DefIdx);
2890
2891   int DefCycle;
2892   if (Subtarget.isCortexA8()) {
2893     // 4 registers would be issued: 1, 2, 1.
2894     // 5 registers would be issued: 1, 2, 2.
2895     DefCycle = RegNo / 2;
2896     if (DefCycle < 1)
2897       DefCycle = 1;
2898     // Result latency is issue cycle + 2: E2.
2899     DefCycle += 2;
2900   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2901     DefCycle = (RegNo / 2);
2902     // If there are odd number of registers or if it's not 64-bit aligned,
2903     // then it takes an extra AGU (Address Generation Unit) cycle.
2904     if ((RegNo % 2) || DefAlign < 8)
2905       ++DefCycle;
2906     // Result latency is AGU cycles + 2.
2907     DefCycle += 2;
2908   } else {
2909     // Assume the worst.
2910     DefCycle = RegNo + 2;
2911   }
2912
2913   return DefCycle;
2914 }
2915
2916 int
2917 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
2918                                   const MCInstrDesc &UseMCID,
2919                                   unsigned UseClass,
2920                                   unsigned UseIdx, unsigned UseAlign) const {
2921   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2922   if (RegNo <= 0)
2923     return ItinData->getOperandCycle(UseClass, UseIdx);
2924
2925   int UseCycle;
2926   if (Subtarget.isCortexA8()) {
2927     // (regno / 2) + (regno % 2) + 1
2928     UseCycle = RegNo / 2 + 1;
2929     if (RegNo % 2)
2930       ++UseCycle;
2931   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2932     UseCycle = RegNo;
2933     bool isSStore = false;
2934
2935     switch (UseMCID.getOpcode()) {
2936     default: break;
2937     case ARM::VSTMSIA:
2938     case ARM::VSTMSIA_UPD:
2939     case ARM::VSTMSDB_UPD:
2940       isSStore = true;
2941       break;
2942     }
2943
2944     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2945     // then it takes an extra cycle.
2946     if ((isSStore && (RegNo % 2)) || UseAlign < 8)
2947       ++UseCycle;
2948   } else {
2949     // Assume the worst.
2950     UseCycle = RegNo + 2;
2951   }
2952
2953   return UseCycle;
2954 }
2955
2956 int
2957 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
2958                                  const MCInstrDesc &UseMCID,
2959                                  unsigned UseClass,
2960                                  unsigned UseIdx, unsigned UseAlign) const {
2961   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2962   if (RegNo <= 0)
2963     return ItinData->getOperandCycle(UseClass, UseIdx);
2964
2965   int UseCycle;
2966   if (Subtarget.isCortexA8()) {
2967     UseCycle = RegNo / 2;
2968     if (UseCycle < 2)
2969       UseCycle = 2;
2970     // Read in E3.
2971     UseCycle += 2;
2972   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2973     UseCycle = (RegNo / 2);
2974     // If there are odd number of registers or if it's not 64-bit aligned,
2975     // then it takes an extra AGU (Address Generation Unit) cycle.
2976     if ((RegNo % 2) || UseAlign < 8)
2977       ++UseCycle;
2978   } else {
2979     // Assume the worst.
2980     UseCycle = 1;
2981   }
2982   return UseCycle;
2983 }
2984
2985 int
2986 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2987                                     const MCInstrDesc &DefMCID,
2988                                     unsigned DefIdx, unsigned DefAlign,
2989                                     const MCInstrDesc &UseMCID,
2990                                     unsigned UseIdx, unsigned UseAlign) const {
2991   unsigned DefClass = DefMCID.getSchedClass();
2992   unsigned UseClass = UseMCID.getSchedClass();
2993
2994   if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
2995     return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
2996
2997   // This may be a def / use of a variable_ops instruction, the operand
2998   // latency might be determinable dynamically. Let the target try to
2999   // figure it out.
3000   int DefCycle = -1;
3001   bool LdmBypass = false;
3002   switch (DefMCID.getOpcode()) {
3003   default:
3004     DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3005     break;
3006
3007   case ARM::VLDMDIA:
3008   case ARM::VLDMDIA_UPD:
3009   case ARM::VLDMDDB_UPD:
3010   case ARM::VLDMSIA:
3011   case ARM::VLDMSIA_UPD:
3012   case ARM::VLDMSDB_UPD:
3013     DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3014     break;
3015
3016   case ARM::LDMIA_RET:
3017   case ARM::LDMIA:
3018   case ARM::LDMDA:
3019   case ARM::LDMDB:
3020   case ARM::LDMIB:
3021   case ARM::LDMIA_UPD:
3022   case ARM::LDMDA_UPD:
3023   case ARM::LDMDB_UPD:
3024   case ARM::LDMIB_UPD:
3025   case ARM::tLDMIA:
3026   case ARM::tLDMIA_UPD:
3027   case ARM::tPUSH:
3028   case ARM::t2LDMIA_RET:
3029   case ARM::t2LDMIA:
3030   case ARM::t2LDMDB:
3031   case ARM::t2LDMIA_UPD:
3032   case ARM::t2LDMDB_UPD:
3033     LdmBypass = 1;
3034     DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3035     break;
3036   }
3037
3038   if (DefCycle == -1)
3039     // We can't seem to determine the result latency of the def, assume it's 2.
3040     DefCycle = 2;
3041
3042   int UseCycle = -1;
3043   switch (UseMCID.getOpcode()) {
3044   default:
3045     UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
3046     break;
3047
3048   case ARM::VSTMDIA:
3049   case ARM::VSTMDIA_UPD:
3050   case ARM::VSTMDDB_UPD:
3051   case ARM::VSTMSIA:
3052   case ARM::VSTMSIA_UPD:
3053   case ARM::VSTMSDB_UPD:
3054     UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3055     break;
3056
3057   case ARM::STMIA:
3058   case ARM::STMDA:
3059   case ARM::STMDB:
3060   case ARM::STMIB:
3061   case ARM::STMIA_UPD:
3062   case ARM::STMDA_UPD:
3063   case ARM::STMDB_UPD:
3064   case ARM::STMIB_UPD:
3065   case ARM::tSTMIA_UPD:
3066   case ARM::tPOP_RET:
3067   case ARM::tPOP:
3068   case ARM::t2STMIA:
3069   case ARM::t2STMDB:
3070   case ARM::t2STMIA_UPD:
3071   case ARM::t2STMDB_UPD:
3072     UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3073     break;
3074   }
3075
3076   if (UseCycle == -1)
3077     // Assume it's read in the first stage.
3078     UseCycle = 1;
3079
3080   UseCycle = DefCycle - UseCycle + 1;
3081   if (UseCycle > 0) {
3082     if (LdmBypass) {
3083       // It's a variable_ops instruction so we can't use DefIdx here. Just use
3084       // first def operand.
3085       if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
3086                                           UseClass, UseIdx))
3087         --UseCycle;
3088     } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
3089                                                UseClass, UseIdx)) {
3090       --UseCycle;
3091     }
3092   }
3093
3094   return UseCycle;
3095 }
3096
3097 static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
3098                                            const MachineInstr *MI, unsigned Reg,
3099                                            unsigned &DefIdx, unsigned &Dist) {
3100   Dist = 0;
3101
3102   MachineBasicBlock::const_iterator I = MI; ++I;
3103   MachineBasicBlock::const_instr_iterator II =
3104     llvm::prior(I.getInstrIterator());
3105   assert(II->isInsideBundle() && "Empty bundle?");
3106
3107   int Idx = -1;
3108   while (II->isInsideBundle()) {
3109     Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
3110     if (Idx != -1)
3111       break;
3112     --II;
3113     ++Dist;
3114   }
3115
3116   assert(Idx != -1 && "Cannot find bundled definition!");
3117   DefIdx = Idx;
3118   return II;
3119 }
3120
3121 static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
3122                                            const MachineInstr *MI, unsigned Reg,
3123                                            unsigned &UseIdx, unsigned &Dist) {
3124   Dist = 0;
3125
3126   MachineBasicBlock::const_instr_iterator II = MI; ++II;
3127   assert(II->isInsideBundle() && "Empty bundle?");
3128   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
3129
3130   // FIXME: This doesn't properly handle multiple uses.
3131   int Idx = -1;
3132   while (II != E && II->isInsideBundle()) {
3133     Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
3134     if (Idx != -1)
3135       break;
3136     if (II->getOpcode() != ARM::t2IT)
3137       ++Dist;
3138     ++II;
3139   }
3140
3141   if (Idx == -1) {
3142     Dist = 0;
3143     return 0;
3144   }
3145
3146   UseIdx = Idx;
3147   return II;
3148 }
3149
3150 /// Return the number of cycles to add to (or subtract from) the static
3151 /// itinerary based on the def opcode and alignment. The caller will ensure that
3152 /// adjusted latency is at least one cycle.
3153 static int adjustDefLatency(const ARMSubtarget &Subtarget,
3154                             const MachineInstr *DefMI,
3155                             const MCInstrDesc *DefMCID, unsigned DefAlign) {
3156   int Adjust = 0;
3157   if (Subtarget.isCortexA8() || Subtarget.isLikeA9()) {
3158     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
3159     // variants are one cycle cheaper.
3160     switch (DefMCID->getOpcode()) {
3161     default: break;
3162     case ARM::LDRrs:
3163     case ARM::LDRBrs: {
3164       unsigned ShOpVal = DefMI->getOperand(3).getImm();
3165       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3166       if (ShImm == 0 ||
3167           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3168         --Adjust;
3169       break;
3170     }
3171     case ARM::t2LDRs:
3172     case ARM::t2LDRBs:
3173     case ARM::t2LDRHs:
3174     case ARM::t2LDRSHs: {
3175       // Thumb2 mode: lsl only.
3176       unsigned ShAmt = DefMI->getOperand(3).getImm();
3177       if (ShAmt == 0 || ShAmt == 2)
3178         --Adjust;
3179       break;
3180     }
3181     }
3182   } else if (Subtarget.isSwift()) {
3183     // FIXME: Properly handle all of the latency adjustments for address
3184     // writeback.
3185     switch (DefMCID->getOpcode()) {
3186     default: break;
3187     case ARM::LDRrs:
3188     case ARM::LDRBrs: {
3189       unsigned ShOpVal = DefMI->getOperand(3).getImm();
3190       bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3191       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3192       if (!isSub &&
3193           (ShImm == 0 ||
3194            ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3195             ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3196         Adjust -= 2;
3197       else if (!isSub &&
3198                ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
3199         --Adjust;
3200       break;
3201     }
3202     case ARM::t2LDRs:
3203     case ARM::t2LDRBs:
3204     case ARM::t2LDRHs:
3205     case ARM::t2LDRSHs: {
3206       // Thumb2 mode: lsl only.
3207       unsigned ShAmt = DefMI->getOperand(3).getImm();
3208       if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
3209         Adjust -= 2;
3210       break;
3211     }
3212     }
3213   }
3214
3215   if (DefAlign < 8 && Subtarget.isLikeA9()) {
3216     switch (DefMCID->getOpcode()) {
3217     default: break;
3218     case ARM::VLD1q8:
3219     case ARM::VLD1q16:
3220     case ARM::VLD1q32:
3221     case ARM::VLD1q64:
3222     case ARM::VLD1q8wb_fixed:
3223     case ARM::VLD1q16wb_fixed:
3224     case ARM::VLD1q32wb_fixed:
3225     case ARM::VLD1q64wb_fixed:
3226     case ARM::VLD1q8wb_register:
3227     case ARM::VLD1q16wb_register:
3228     case ARM::VLD1q32wb_register:
3229     case ARM::VLD1q64wb_register:
3230     case ARM::VLD2d8:
3231     case ARM::VLD2d16:
3232     case ARM::VLD2d32:
3233     case ARM::VLD2q8:
3234     case ARM::VLD2q16:
3235     case ARM::VLD2q32:
3236     case ARM::VLD2d8wb_fixed:
3237     case ARM::VLD2d16wb_fixed:
3238     case ARM::VLD2d32wb_fixed:
3239     case ARM::VLD2q8wb_fixed:
3240     case ARM::VLD2q16wb_fixed:
3241     case ARM::VLD2q32wb_fixed:
3242     case ARM::VLD2d8wb_register:
3243     case ARM::VLD2d16wb_register:
3244     case ARM::VLD2d32wb_register:
3245     case ARM::VLD2q8wb_register:
3246     case ARM::VLD2q16wb_register:
3247     case ARM::VLD2q32wb_register:
3248     case ARM::VLD3d8:
3249     case ARM::VLD3d16:
3250     case ARM::VLD3d32:
3251     case ARM::VLD1d64T:
3252     case ARM::VLD3d8_UPD:
3253     case ARM::VLD3d16_UPD:
3254     case ARM::VLD3d32_UPD:
3255     case ARM::VLD1d64Twb_fixed:
3256     case ARM::VLD1d64Twb_register:
3257     case ARM::VLD3q8_UPD:
3258     case ARM::VLD3q16_UPD:
3259     case ARM::VLD3q32_UPD:
3260     case ARM::VLD4d8:
3261     case ARM::VLD4d16:
3262     case ARM::VLD4d32:
3263     case ARM::VLD1d64Q:
3264     case ARM::VLD4d8_UPD:
3265     case ARM::VLD4d16_UPD:
3266     case ARM::VLD4d32_UPD:
3267     case ARM::VLD1d64Qwb_fixed:
3268     case ARM::VLD1d64Qwb_register:
3269     case ARM::VLD4q8_UPD:
3270     case ARM::VLD4q16_UPD:
3271     case ARM::VLD4q32_UPD:
3272     case ARM::VLD1DUPq8:
3273     case ARM::VLD1DUPq16:
3274     case ARM::VLD1DUPq32:
3275     case ARM::VLD1DUPq8wb_fixed:
3276     case ARM::VLD1DUPq16wb_fixed:
3277     case ARM::VLD1DUPq32wb_fixed:
3278     case ARM::VLD1DUPq8wb_register:
3279     case ARM::VLD1DUPq16wb_register:
3280     case ARM::VLD1DUPq32wb_register:
3281     case ARM::VLD2DUPd8:
3282     case ARM::VLD2DUPd16:
3283     case ARM::VLD2DUPd32:
3284     case ARM::VLD2DUPd8wb_fixed:
3285     case ARM::VLD2DUPd16wb_fixed:
3286     case ARM::VLD2DUPd32wb_fixed:
3287     case ARM::VLD2DUPd8wb_register:
3288     case ARM::VLD2DUPd16wb_register:
3289     case ARM::VLD2DUPd32wb_register:
3290     case ARM::VLD4DUPd8:
3291     case ARM::VLD4DUPd16:
3292     case ARM::VLD4DUPd32:
3293     case ARM::VLD4DUPd8_UPD:
3294     case ARM::VLD4DUPd16_UPD:
3295     case ARM::VLD4DUPd32_UPD:
3296     case ARM::VLD1LNd8:
3297     case ARM::VLD1LNd16:
3298     case ARM::VLD1LNd32:
3299     case ARM::VLD1LNd8_UPD:
3300     case ARM::VLD1LNd16_UPD:
3301     case ARM::VLD1LNd32_UPD:
3302     case ARM::VLD2LNd8:
3303     case ARM::VLD2LNd16:
3304     case ARM::VLD2LNd32:
3305     case ARM::VLD2LNq16:
3306     case ARM::VLD2LNq32:
3307     case ARM::VLD2LNd8_UPD:
3308     case ARM::VLD2LNd16_UPD:
3309     case ARM::VLD2LNd32_UPD:
3310     case ARM::VLD2LNq16_UPD:
3311     case ARM::VLD2LNq32_UPD:
3312     case ARM::VLD4LNd8:
3313     case ARM::VLD4LNd16:
3314     case ARM::VLD4LNd32:
3315     case ARM::VLD4LNq16:
3316     case ARM::VLD4LNq32:
3317     case ARM::VLD4LNd8_UPD:
3318     case ARM::VLD4LNd16_UPD:
3319     case ARM::VLD4LNd32_UPD:
3320     case ARM::VLD4LNq16_UPD:
3321     case ARM::VLD4LNq32_UPD:
3322       // If the address is not 64-bit aligned, the latencies of these
3323       // instructions increases by one.
3324       ++Adjust;
3325       break;
3326     }
3327   }
3328   return Adjust;
3329 }
3330
3331
3332
3333 int
3334 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3335                                     const MachineInstr *DefMI, unsigned DefIdx,
3336                                     const MachineInstr *UseMI,
3337                                     unsigned UseIdx) const {
3338   // No operand latency. The caller may fall back to getInstrLatency.
3339   if (!ItinData || ItinData->isEmpty())
3340     return -1;
3341
3342   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
3343   unsigned Reg = DefMO.getReg();
3344   const MCInstrDesc *DefMCID = &DefMI->getDesc();
3345   const MCInstrDesc *UseMCID = &UseMI->getDesc();
3346
3347   unsigned DefAdj = 0;
3348   if (DefMI->isBundle()) {
3349     DefMI = getBundledDefMI(&getRegisterInfo(), DefMI, Reg, DefIdx, DefAdj);
3350     DefMCID = &DefMI->getDesc();
3351   }
3352   if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
3353       DefMI->isRegSequence() || DefMI->isImplicitDef()) {
3354     return 1;
3355   }
3356
3357   unsigned UseAdj = 0;
3358   if (UseMI->isBundle()) {
3359     unsigned NewUseIdx;
3360     const MachineInstr *NewUseMI = getBundledUseMI(&getRegisterInfo(), UseMI,
3361                                                    Reg, NewUseIdx, UseAdj);
3362     if (!NewUseMI)
3363       return -1;
3364
3365     UseMI = NewUseMI;
3366     UseIdx = NewUseIdx;
3367     UseMCID = &UseMI->getDesc();
3368   }
3369
3370   if (Reg == ARM::CPSR) {
3371     if (DefMI->getOpcode() == ARM::FMSTAT) {
3372       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
3373       return Subtarget.isLikeA9() ? 1 : 20;
3374     }
3375
3376     // CPSR set and branch can be paired in the same cycle.
3377     if (UseMI->isBranch())
3378       return 0;
3379
3380     // Otherwise it takes the instruction latency (generally one).
3381     unsigned Latency = getInstrLatency(ItinData, DefMI);
3382
3383     // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
3384     // its uses. Instructions which are otherwise scheduled between them may
3385     // incur a code size penalty (not able to use the CPSR setting 16-bit
3386     // instructions).
3387     if (Latency > 0 && Subtarget.isThumb2()) {
3388       const MachineFunction *MF = DefMI->getParent()->getParent();
3389       if (MF->getFunction()->getAttributes().
3390             hasAttribute(AttributeSet::FunctionIndex,
3391                          Attribute::OptimizeForSize))
3392         --Latency;
3393     }
3394     return Latency;
3395   }
3396
3397   if (DefMO.isImplicit() || UseMI->getOperand(UseIdx).isImplicit())
3398     return -1;
3399
3400   unsigned DefAlign = DefMI->hasOneMemOperand()
3401     ? (*DefMI->memoperands_begin())->getAlignment() : 0;
3402   unsigned UseAlign = UseMI->hasOneMemOperand()
3403     ? (*UseMI->memoperands_begin())->getAlignment() : 0;
3404
3405   // Get the itinerary's latency if possible, and handle variable_ops.
3406   int Latency = getOperandLatency(ItinData, *DefMCID, DefIdx, DefAlign,
3407                                   *UseMCID, UseIdx, UseAlign);
3408   // Unable to find operand latency. The caller may resort to getInstrLatency.
3409   if (Latency < 0)
3410     return Latency;
3411
3412   // Adjust for IT block position.
3413   int Adj = DefAdj + UseAdj;
3414
3415   // Adjust for dynamic def-side opcode variants not captured by the itinerary.
3416   Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
3417   if (Adj >= 0 || (int)Latency > -Adj) {
3418     return Latency + Adj;
3419   }
3420   // Return the itinerary latency, which may be zero but not less than zero.
3421   return Latency;
3422 }
3423
3424 int
3425 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3426                                     SDNode *DefNode, unsigned DefIdx,
3427                                     SDNode *UseNode, unsigned UseIdx) const {
3428   if (!DefNode->isMachineOpcode())
3429     return 1;
3430
3431   const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
3432
3433   if (isZeroCost(DefMCID.Opcode))
3434     return 0;
3435
3436   if (!ItinData || ItinData->isEmpty())
3437     return DefMCID.mayLoad() ? 3 : 1;
3438
3439   if (!UseNode->isMachineOpcode()) {
3440     int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
3441     if (Subtarget.isLikeA9() || Subtarget.isSwift())
3442       return Latency <= 2 ? 1 : Latency - 1;
3443     else
3444       return Latency <= 3 ? 1 : Latency - 2;
3445   }
3446
3447   const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
3448   const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
3449   unsigned DefAlign = !DefMN->memoperands_empty()
3450     ? (*DefMN->memoperands_begin())->getAlignment() : 0;
3451   const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
3452   unsigned UseAlign = !UseMN->memoperands_empty()
3453     ? (*UseMN->memoperands_begin())->getAlignment() : 0;
3454   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
3455                                   UseMCID, UseIdx, UseAlign);
3456
3457   if (Latency > 1 &&
3458       (Subtarget.isCortexA8() || Subtarget.isLikeA9())) {
3459     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
3460     // variants are one cycle cheaper.
3461     switch (DefMCID.getOpcode()) {
3462     default: break;
3463     case ARM::LDRrs:
3464     case ARM::LDRBrs: {
3465       unsigned ShOpVal =
3466         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3467       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3468       if (ShImm == 0 ||
3469           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3470         --Latency;
3471       break;
3472     }
3473     case ARM::t2LDRs:
3474     case ARM::t2LDRBs:
3475     case ARM::t2LDRHs:
3476     case ARM::t2LDRSHs: {
3477       // Thumb2 mode: lsl only.
3478       unsigned ShAmt =
3479         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3480       if (ShAmt == 0 || ShAmt == 2)
3481         --Latency;
3482       break;
3483     }
3484     }
3485   } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
3486     // FIXME: Properly handle all of the latency adjustments for address
3487     // writeback.
3488     switch (DefMCID.getOpcode()) {
3489     default: break;
3490     case ARM::LDRrs:
3491     case ARM::LDRBrs: {
3492       unsigned ShOpVal =
3493         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3494       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3495       if (ShImm == 0 ||
3496           ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3497            ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3498         Latency -= 2;
3499       else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
3500         --Latency;
3501       break;
3502     }
3503     case ARM::t2LDRs:
3504     case ARM::t2LDRBs:
3505     case ARM::t2LDRHs:
3506     case ARM::t2LDRSHs: {
3507       // Thumb2 mode: lsl 0-3 only.
3508       Latency -= 2;
3509       break;
3510     }
3511     }
3512   }
3513
3514   if (DefAlign < 8 && Subtarget.isLikeA9())
3515     switch (DefMCID.getOpcode()) {
3516     default: break;
3517     case ARM::VLD1q8:
3518     case ARM::VLD1q16:
3519     case ARM::VLD1q32:
3520     case ARM::VLD1q64:
3521     case ARM::VLD1q8wb_register:
3522     case ARM::VLD1q16wb_register:
3523     case ARM::VLD1q32wb_register:
3524     case ARM::VLD1q64wb_register:
3525     case ARM::VLD1q8wb_fixed:
3526     case ARM::VLD1q16wb_fixed:
3527     case ARM::VLD1q32wb_fixed:
3528     case ARM::VLD1q64wb_fixed:
3529     case ARM::VLD2d8:
3530     case ARM::VLD2d16:
3531     case ARM::VLD2d32:
3532     case ARM::VLD2q8Pseudo:
3533     case ARM::VLD2q16Pseudo:
3534     case ARM::VLD2q32Pseudo:
3535     case ARM::VLD2d8wb_fixed:
3536     case ARM::VLD2d16wb_fixed:
3537     case ARM::VLD2d32wb_fixed:
3538     case ARM::VLD2q8PseudoWB_fixed:
3539     case ARM::VLD2q16PseudoWB_fixed:
3540     case ARM::VLD2q32PseudoWB_fixed:
3541     case ARM::VLD2d8wb_register:
3542     case ARM::VLD2d16wb_register:
3543     case ARM::VLD2d32wb_register:
3544     case ARM::VLD2q8PseudoWB_register:
3545     case ARM::VLD2q16PseudoWB_register:
3546     case ARM::VLD2q32PseudoWB_register:
3547     case ARM::VLD3d8Pseudo:
3548     case ARM::VLD3d16Pseudo:
3549     case ARM::VLD3d32Pseudo:
3550     case ARM::VLD1d64TPseudo:
3551     case ARM::VLD3d8Pseudo_UPD:
3552     case ARM::VLD3d16Pseudo_UPD:
3553     case ARM::VLD3d32Pseudo_UPD:
3554     case ARM::VLD3q8Pseudo_UPD:
3555     case ARM::VLD3q16Pseudo_UPD:
3556     case ARM::VLD3q32Pseudo_UPD:
3557     case ARM::VLD3q8oddPseudo:
3558     case ARM::VLD3q16oddPseudo:
3559     case ARM::VLD3q32oddPseudo:
3560     case ARM::VLD3q8oddPseudo_UPD:
3561     case ARM::VLD3q16oddPseudo_UPD:
3562     case ARM::VLD3q32oddPseudo_UPD:
3563     case ARM::VLD4d8Pseudo:
3564     case ARM::VLD4d16Pseudo:
3565     case ARM::VLD4d32Pseudo:
3566     case ARM::VLD1d64QPseudo:
3567     case ARM::VLD4d8Pseudo_UPD:
3568     case ARM::VLD4d16Pseudo_UPD:
3569     case ARM::VLD4d32Pseudo_UPD:
3570     case ARM::VLD4q8Pseudo_UPD:
3571     case ARM::VLD4q16Pseudo_UPD:
3572     case ARM::VLD4q32Pseudo_UPD:
3573     case ARM::VLD4q8oddPseudo:
3574     case ARM::VLD4q16oddPseudo:
3575     case ARM::VLD4q32oddPseudo:
3576     case ARM::VLD4q8oddPseudo_UPD:
3577     case ARM::VLD4q16oddPseudo_UPD:
3578     case ARM::VLD4q32oddPseudo_UPD:
3579     case ARM::VLD1DUPq8:
3580     case ARM::VLD1DUPq16:
3581     case ARM::VLD1DUPq32:
3582     case ARM::VLD1DUPq8wb_fixed:
3583     case ARM::VLD1DUPq16wb_fixed:
3584     case ARM::VLD1DUPq32wb_fixed:
3585     case ARM::VLD1DUPq8wb_register:
3586     case ARM::VLD1DUPq16wb_register:
3587     case ARM::VLD1DUPq32wb_register:
3588     case ARM::VLD2DUPd8:
3589     case ARM::VLD2DUPd16:
3590     case ARM::VLD2DUPd32:
3591     case ARM::VLD2DUPd8wb_fixed:
3592     case ARM::VLD2DUPd16wb_fixed:
3593     case ARM::VLD2DUPd32wb_fixed:
3594     case ARM::VLD2DUPd8wb_register:
3595     case ARM::VLD2DUPd16wb_register:
3596     case ARM::VLD2DUPd32wb_register:
3597     case ARM::VLD4DUPd8Pseudo:
3598     case ARM::VLD4DUPd16Pseudo:
3599     case ARM::VLD4DUPd32Pseudo:
3600     case ARM::VLD4DUPd8Pseudo_UPD:
3601     case ARM::VLD4DUPd16Pseudo_UPD:
3602     case ARM::VLD4DUPd32Pseudo_UPD:
3603     case ARM::VLD1LNq8Pseudo:
3604     case ARM::VLD1LNq16Pseudo:
3605     case ARM::VLD1LNq32Pseudo:
3606     case ARM::VLD1LNq8Pseudo_UPD:
3607     case ARM::VLD1LNq16Pseudo_UPD:
3608     case ARM::VLD1LNq32Pseudo_UPD:
3609     case ARM::VLD2LNd8Pseudo:
3610     case ARM::VLD2LNd16Pseudo:
3611     case ARM::VLD2LNd32Pseudo:
3612     case ARM::VLD2LNq16Pseudo:
3613     case ARM::VLD2LNq32Pseudo:
3614     case ARM::VLD2LNd8Pseudo_UPD:
3615     case ARM::VLD2LNd16Pseudo_UPD:
3616     case ARM::VLD2LNd32Pseudo_UPD:
3617     case ARM::VLD2LNq16Pseudo_UPD:
3618     case ARM::VLD2LNq32Pseudo_UPD:
3619     case ARM::VLD4LNd8Pseudo:
3620     case ARM::VLD4LNd16Pseudo:
3621     case ARM::VLD4LNd32Pseudo:
3622     case ARM::VLD4LNq16Pseudo:
3623     case ARM::VLD4LNq32Pseudo:
3624     case ARM::VLD4LNd8Pseudo_UPD:
3625     case ARM::VLD4LNd16Pseudo_UPD:
3626     case ARM::VLD4LNd32Pseudo_UPD:
3627     case ARM::VLD4LNq16Pseudo_UPD:
3628     case ARM::VLD4LNq32Pseudo_UPD:
3629       // If the address is not 64-bit aligned, the latencies of these
3630       // instructions increases by one.
3631       ++Latency;
3632       break;
3633     }
3634
3635   return Latency;
3636 }
3637
3638 unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr *MI) const {
3639    if (MI->isCopyLike() || MI->isInsertSubreg() ||
3640       MI->isRegSequence() || MI->isImplicitDef())
3641     return 0;
3642
3643   if (MI->isBundle())
3644     return 0;
3645
3646   const MCInstrDesc &MCID = MI->getDesc();
3647
3648   if (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR)) {
3649     // When predicated, CPSR is an additional source operand for CPSR updating
3650     // instructions, this apparently increases their latencies.
3651     return 1;
3652   }
3653   return 0;
3654 }
3655
3656 unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
3657                                            const MachineInstr *MI,
3658                                            unsigned *PredCost) const {
3659   if (MI->isCopyLike() || MI->isInsertSubreg() ||
3660       MI->isRegSequence() || MI->isImplicitDef())
3661     return 1;
3662
3663   // An instruction scheduler typically runs on unbundled instructions, however
3664   // other passes may query the latency of a bundled instruction.
3665   if (MI->isBundle()) {
3666     unsigned Latency = 0;
3667     MachineBasicBlock::const_instr_iterator I = MI;
3668     MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
3669     while (++I != E && I->isInsideBundle()) {
3670       if (I->getOpcode() != ARM::t2IT)
3671         Latency += getInstrLatency(ItinData, I, PredCost);
3672     }
3673     return Latency;
3674   }
3675
3676   const MCInstrDesc &MCID = MI->getDesc();
3677   if (PredCost && (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR))) {
3678     // When predicated, CPSR is an additional source operand for CPSR updating
3679     // instructions, this apparently increases their latencies.
3680     *PredCost = 1;
3681   }
3682   // Be sure to call getStageLatency for an empty itinerary in case it has a
3683   // valid MinLatency property.
3684   if (!ItinData)
3685     return MI->mayLoad() ? 3 : 1;
3686
3687   unsigned Class = MCID.getSchedClass();
3688
3689   // For instructions with variable uops, use uops as latency.
3690   if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
3691     return getNumMicroOps(ItinData, MI);
3692
3693   // For the common case, fall back on the itinerary's latency.
3694   unsigned Latency = ItinData->getStageLatency(Class);
3695
3696   // Adjust for dynamic def-side opcode variants not captured by the itinerary.
3697   unsigned DefAlign = MI->hasOneMemOperand()
3698     ? (*MI->memoperands_begin())->getAlignment() : 0;
3699   int Adj = adjustDefLatency(Subtarget, MI, &MCID, DefAlign);
3700   if (Adj >= 0 || (int)Latency > -Adj) {
3701     return Latency + Adj;
3702   }
3703   return Latency;
3704 }
3705
3706 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
3707                                       SDNode *Node) const {
3708   if (!Node->isMachineOpcode())
3709     return 1;
3710
3711   if (!ItinData || ItinData->isEmpty())
3712     return 1;
3713
3714   unsigned Opcode = Node->getMachineOpcode();
3715   switch (Opcode) {
3716   default:
3717     return ItinData->getStageLatency(get(Opcode).getSchedClass());
3718   case ARM::VLDMQIA:
3719   case ARM::VSTMQIA:
3720     return 2;
3721   }
3722 }
3723
3724 bool ARMBaseInstrInfo::
3725 hasHighOperandLatency(const InstrItineraryData *ItinData,
3726                       const MachineRegisterInfo *MRI,
3727                       const MachineInstr *DefMI, unsigned DefIdx,
3728                       const MachineInstr *UseMI, unsigned UseIdx) const {
3729   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
3730   unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
3731   if (Subtarget.isCortexA8() &&
3732       (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
3733     // CortexA8 VFP instructions are not pipelined.
3734     return true;
3735
3736   // Hoist VFP / NEON instructions with 4 or higher latency.
3737   int Latency = computeOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
3738   if (Latency < 0)
3739     Latency = getInstrLatency(ItinData, DefMI);
3740   if (Latency <= 3)
3741     return false;
3742   return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
3743          UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
3744 }
3745
3746 bool ARMBaseInstrInfo::
3747 hasLowDefLatency(const InstrItineraryData *ItinData,
3748                  const MachineInstr *DefMI, unsigned DefIdx) const {
3749   if (!ItinData || ItinData->isEmpty())
3750     return false;
3751
3752   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
3753   if (DDomain == ARMII::DomainGeneral) {
3754     unsigned DefClass = DefMI->getDesc().getSchedClass();
3755     int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3756     return (DefCycle != -1 && DefCycle <= 2);
3757   }
3758   return false;
3759 }
3760
3761 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr *MI,
3762                                          StringRef &ErrInfo) const {
3763   if (convertAddSubFlagsOpcode(MI->getOpcode())) {
3764     ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
3765     return false;
3766   }
3767   return true;
3768 }
3769
3770 bool
3771 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
3772                                      unsigned &AddSubOpc,
3773                                      bool &NegAcc, bool &HasLane) const {
3774   DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
3775   if (I == MLxEntryMap.end())
3776     return false;
3777
3778   const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
3779   MulOpc = Entry.MulOpc;
3780   AddSubOpc = Entry.AddSubOpc;
3781   NegAcc = Entry.NegAcc;
3782   HasLane = Entry.HasLane;
3783   return true;
3784 }
3785
3786 //===----------------------------------------------------------------------===//
3787 // Execution domains.
3788 //===----------------------------------------------------------------------===//
3789 //
3790 // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
3791 // and some can go down both.  The vmov instructions go down the VFP pipeline,
3792 // but they can be changed to vorr equivalents that are executed by the NEON
3793 // pipeline.
3794 //
3795 // We use the following execution domain numbering:
3796 //
3797 enum ARMExeDomain {
3798   ExeGeneric = 0,
3799   ExeVFP = 1,
3800   ExeNEON = 2
3801 };
3802 //
3803 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
3804 //
3805 std::pair<uint16_t, uint16_t>
3806 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr *MI) const {
3807   // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
3808   // if they are not predicated.
3809   if (MI->getOpcode() == ARM::VMOVD && !isPredicated(MI))
3810     return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
3811
3812   // CortexA9 is particularly picky about mixing the two and wants these
3813   // converted.
3814   if (Subtarget.isCortexA9() && !isPredicated(MI) &&
3815       (MI->getOpcode() == ARM::VMOVRS ||
3816        MI->getOpcode() == ARM::VMOVSR ||
3817        MI->getOpcode() == ARM::VMOVS))
3818     return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
3819
3820   // No other instructions can be swizzled, so just determine their domain.
3821   unsigned Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
3822
3823   if (Domain & ARMII::DomainNEON)
3824     return std::make_pair(ExeNEON, 0);
3825
3826   // Certain instructions can go either way on Cortex-A8.
3827   // Treat them as NEON instructions.
3828   if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
3829     return std::make_pair(ExeNEON, 0);
3830
3831   if (Domain & ARMII::DomainVFP)
3832     return std::make_pair(ExeVFP, 0);
3833
3834   return std::make_pair(ExeGeneric, 0);
3835 }
3836
3837 static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
3838                                             unsigned SReg, unsigned &Lane) {
3839   unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
3840   Lane = 0;
3841
3842   if (DReg != ARM::NoRegister)
3843    return DReg;
3844
3845   Lane = 1;
3846   DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
3847
3848   assert(DReg && "S-register with no D super-register?");
3849   return DReg;
3850 }
3851
3852 /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
3853 /// set ImplicitSReg to a register number that must be marked as implicit-use or
3854 /// zero if no register needs to be defined as implicit-use.
3855 ///
3856 /// If the function cannot determine if an SPR should be marked implicit use or
3857 /// not, it returns false.
3858 ///
3859 /// This function handles cases where an instruction is being modified from taking
3860 /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
3861 /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
3862 /// lane of the DPR).
3863 ///
3864 /// If the other SPR is defined, an implicit-use of it should be added. Else,
3865 /// (including the case where the DPR itself is defined), it should not.
3866 ///
3867 static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
3868                                        MachineInstr *MI,
3869                                        unsigned DReg, unsigned Lane,
3870                                        unsigned &ImplicitSReg) {
3871   // If the DPR is defined or used already, the other SPR lane will be chained
3872   // correctly, so there is nothing to be done.
3873   if (MI->definesRegister(DReg, TRI) || MI->readsRegister(DReg, TRI)) {
3874     ImplicitSReg = 0;
3875     return true;
3876   }
3877
3878   // Otherwise we need to go searching to see if the SPR is set explicitly.
3879   ImplicitSReg = TRI->getSubReg(DReg,
3880                                 (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
3881   MachineBasicBlock::LivenessQueryResult LQR =
3882     MI->getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
3883
3884   if (LQR == MachineBasicBlock::LQR_Live)
3885     return true;
3886   else if (LQR == MachineBasicBlock::LQR_Unknown)
3887     return false;
3888
3889   // If the register is known not to be live, there is no need to add an
3890   // implicit-use.
3891   ImplicitSReg = 0;
3892   return true;
3893 }
3894
3895 void
3896 ARMBaseInstrInfo::setExecutionDomain(MachineInstr *MI, unsigned Domain) const {
3897   unsigned DstReg, SrcReg, DReg;
3898   unsigned Lane;
3899   MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
3900   const TargetRegisterInfo *TRI = &getRegisterInfo();
3901   switch (MI->getOpcode()) {
3902     default:
3903       llvm_unreachable("cannot handle opcode!");
3904       break;
3905     case ARM::VMOVD:
3906       if (Domain != ExeNEON)
3907         break;
3908
3909       // Zap the predicate operands.
3910       assert(!isPredicated(MI) && "Cannot predicate a VORRd");
3911
3912       // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
3913       DstReg = MI->getOperand(0).getReg();
3914       SrcReg = MI->getOperand(1).getReg();
3915
3916       for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
3917         MI->RemoveOperand(i-1);
3918
3919       // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
3920       MI->setDesc(get(ARM::VORRd));
3921       AddDefaultPred(MIB.addReg(DstReg, RegState::Define)
3922                         .addReg(SrcReg)
3923                         .addReg(SrcReg));
3924       break;
3925     case ARM::VMOVRS:
3926       if (Domain != ExeNEON)
3927         break;
3928       assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
3929
3930       // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
3931       DstReg = MI->getOperand(0).getReg();
3932       SrcReg = MI->getOperand(1).getReg();
3933
3934       for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
3935         MI->RemoveOperand(i-1);
3936
3937       DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
3938
3939       // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
3940       // Note that DSrc has been widened and the other lane may be undef, which
3941       // contaminates the entire register.
3942       MI->setDesc(get(ARM::VGETLNi32));
3943       AddDefaultPred(MIB.addReg(DstReg, RegState::Define)
3944                         .addReg(DReg, RegState::Undef)
3945                         .addImm(Lane));
3946
3947       // The old source should be an implicit use, otherwise we might think it
3948       // was dead before here.
3949       MIB.addReg(SrcReg, RegState::Implicit);
3950       break;
3951     case ARM::VMOVSR: {
3952       if (Domain != ExeNEON)
3953         break;
3954       assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
3955
3956       // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
3957       DstReg = MI->getOperand(0).getReg();
3958       SrcReg = MI->getOperand(1).getReg();
3959
3960       DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
3961
3962       unsigned ImplicitSReg;
3963       if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
3964         break;
3965
3966       for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
3967         MI->RemoveOperand(i-1);
3968
3969       // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
3970       // Again DDst may be undefined at the beginning of this instruction.
3971       MI->setDesc(get(ARM::VSETLNi32));
3972       MIB.addReg(DReg, RegState::Define)
3973          .addReg(DReg, getUndefRegState(!MI->readsRegister(DReg, TRI)))
3974          .addReg(SrcReg)
3975          .addImm(Lane);
3976       AddDefaultPred(MIB);
3977
3978       // The narrower destination must be marked as set to keep previous chains
3979       // in place.
3980       MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
3981       if (ImplicitSReg != 0)
3982         MIB.addReg(ImplicitSReg, RegState::Implicit);
3983       break;
3984     }
3985     case ARM::VMOVS: {
3986       if (Domain != ExeNEON)
3987         break;
3988
3989       // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
3990       DstReg = MI->getOperand(0).getReg();
3991       SrcReg = MI->getOperand(1).getReg();
3992
3993       unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
3994       DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
3995       DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
3996
3997       unsigned ImplicitSReg;
3998       if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
3999         break;
4000
4001       for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4002         MI->RemoveOperand(i-1);
4003
4004       if (DSrc == DDst) {
4005         // Destination can be:
4006         //     %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
4007         MI->setDesc(get(ARM::VDUPLN32d));
4008         MIB.addReg(DDst, RegState::Define)
4009            .addReg(DDst, getUndefRegState(!MI->readsRegister(DDst, TRI)))
4010            .addImm(SrcLane);
4011         AddDefaultPred(MIB);
4012
4013         // Neither the source or the destination are naturally represented any
4014         // more, so add them in manually.
4015         MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
4016         MIB.addReg(SrcReg, RegState::Implicit);
4017         if (ImplicitSReg != 0)
4018           MIB.addReg(ImplicitSReg, RegState::Implicit);
4019         break;
4020       }
4021
4022       // In general there's no single instruction that can perform an S <-> S
4023       // move in NEON space, but a pair of VEXT instructions *can* do the
4024       // job. It turns out that the VEXTs needed will only use DSrc once, with
4025       // the position based purely on the combination of lane-0 and lane-1
4026       // involved. For example
4027       //     vmov s0, s2 -> vext.32 d0, d0, d1, #1  vext.32 d0, d0, d0, #1
4028       //     vmov s1, s3 -> vext.32 d0, d1, d0, #1  vext.32 d0, d0, d0, #1
4029       //     vmov s0, s3 -> vext.32 d0, d0, d0, #1  vext.32 d0, d1, d0, #1
4030       //     vmov s1, s2 -> vext.32 d0, d0, d0, #1  vext.32 d0, d0, d1, #1
4031       //
4032       // Pattern of the MachineInstrs is:
4033       //     %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
4034       MachineInstrBuilder NewMIB;
4035       NewMIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4036                        get(ARM::VEXTd32), DDst);
4037
4038       // On the first instruction, both DSrc and DDst may be <undef> if present.
4039       // Specifically when the original instruction didn't have them as an
4040       // <imp-use>.
4041       unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
4042       bool CurUndef = !MI->readsRegister(CurReg, TRI);
4043       NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
4044
4045       CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
4046       CurUndef = !MI->readsRegister(CurReg, TRI);
4047       NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
4048
4049       NewMIB.addImm(1);
4050       AddDefaultPred(NewMIB);
4051
4052       if (SrcLane == DstLane)
4053         NewMIB.addReg(SrcReg, RegState::Implicit);
4054
4055       MI->setDesc(get(ARM::VEXTd32));
4056       MIB.addReg(DDst, RegState::Define);
4057
4058       // On the second instruction, DDst has definitely been defined above, so
4059       // it is not <undef>. DSrc, if present, can be <undef> as above.
4060       CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
4061       CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI);
4062       MIB.addReg(CurReg, getUndefRegState(CurUndef));
4063
4064       CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
4065       CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI);
4066       MIB.addReg(CurReg, getUndefRegState(CurUndef));
4067
4068       MIB.addImm(1);
4069       AddDefaultPred(MIB);
4070
4071       if (SrcLane != DstLane)
4072         MIB.addReg(SrcReg, RegState::Implicit);
4073
4074       // As before, the original destination is no longer represented, add it
4075       // implicitly.
4076       MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
4077       if (ImplicitSReg != 0)
4078         MIB.addReg(ImplicitSReg, RegState::Implicit);
4079       break;
4080     }
4081   }
4082
4083 }
4084
4085 //===----------------------------------------------------------------------===//
4086 // Partial register updates
4087 //===----------------------------------------------------------------------===//
4088 //
4089 // Swift renames NEON registers with 64-bit granularity.  That means any
4090 // instruction writing an S-reg implicitly reads the containing D-reg.  The
4091 // problem is mostly avoided by translating f32 operations to v2f32 operations
4092 // on D-registers, but f32 loads are still a problem.
4093 //
4094 // These instructions can load an f32 into a NEON register:
4095 //
4096 // VLDRS - Only writes S, partial D update.
4097 // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
4098 // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
4099 //
4100 // FCONSTD can be used as a dependency-breaking instruction.
4101 unsigned ARMBaseInstrInfo::
4102 getPartialRegUpdateClearance(const MachineInstr *MI,
4103                              unsigned OpNum,
4104                              const TargetRegisterInfo *TRI) const {
4105   if (!SwiftPartialUpdateClearance ||
4106       !(Subtarget.isSwift() || Subtarget.isCortexA15()))
4107     return 0;
4108
4109   assert(TRI && "Need TRI instance");
4110
4111   const MachineOperand &MO = MI->getOperand(OpNum);
4112   if (MO.readsReg())
4113     return 0;
4114   unsigned Reg = MO.getReg();
4115   int UseOp = -1;
4116
4117   switch(MI->getOpcode()) {
4118     // Normal instructions writing only an S-register.
4119   case ARM::VLDRS:
4120   case ARM::FCONSTS:
4121   case ARM::VMOVSR:
4122   case ARM::VMOVv8i8:
4123   case ARM::VMOVv4i16:
4124   case ARM::VMOVv2i32:
4125   case ARM::VMOVv2f32:
4126   case ARM::VMOVv1i64:
4127     UseOp = MI->findRegisterUseOperandIdx(Reg, false, TRI);
4128     break;
4129
4130     // Explicitly reads the dependency.
4131   case ARM::VLD1LNd32:
4132     UseOp = 3;
4133     break;
4134   default:
4135     return 0;
4136   }
4137
4138   // If this instruction actually reads a value from Reg, there is no unwanted
4139   // dependency.
4140   if (UseOp != -1 && MI->getOperand(UseOp).readsReg())
4141     return 0;
4142
4143   // We must be able to clobber the whole D-reg.
4144   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
4145     // Virtual register must be a foo:ssub_0<def,undef> operand.
4146     if (!MO.getSubReg() || MI->readsVirtualRegister(Reg))
4147       return 0;
4148   } else if (ARM::SPRRegClass.contains(Reg)) {
4149     // Physical register: MI must define the full D-reg.
4150     unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
4151                                              &ARM::DPRRegClass);
4152     if (!DReg || !MI->definesRegister(DReg, TRI))
4153       return 0;
4154   }
4155
4156   // MI has an unwanted D-register dependency.
4157   // Avoid defs in the previous N instructrions.
4158   return SwiftPartialUpdateClearance;
4159 }
4160
4161 // Break a partial register dependency after getPartialRegUpdateClearance
4162 // returned non-zero.
4163 void ARMBaseInstrInfo::
4164 breakPartialRegDependency(MachineBasicBlock::iterator MI,
4165                           unsigned OpNum,
4166                           const TargetRegisterInfo *TRI) const {
4167   assert(MI && OpNum < MI->getDesc().getNumDefs() && "OpNum is not a def");
4168   assert(TRI && "Need TRI instance");
4169
4170   const MachineOperand &MO = MI->getOperand(OpNum);
4171   unsigned Reg = MO.getReg();
4172   assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
4173          "Can't break virtual register dependencies.");
4174   unsigned DReg = Reg;
4175
4176   // If MI defines an S-reg, find the corresponding D super-register.
4177   if (ARM::SPRRegClass.contains(Reg)) {
4178     DReg = ARM::D0 + (Reg - ARM::S0) / 2;
4179     assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
4180   }
4181
4182   assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
4183   assert(MI->definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
4184
4185   // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
4186   // the full D-register by loading the same value to both lanes.  The
4187   // instruction is micro-coded with 2 uops, so don't do this until we can
4188   // properly schedule micro-coded instructions.  The dispatcher stalls cause
4189   // too big regressions.
4190
4191   // Insert the dependency-breaking FCONSTD before MI.
4192   // 96 is the encoding of 0.5, but the actual value doesn't matter here.
4193   AddDefaultPred(BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4194                          get(ARM::FCONSTD), DReg).addImm(96));
4195   MI->addRegisterKilled(DReg, TRI, true);
4196 }
4197
4198 bool ARMBaseInstrInfo::hasNOP() const {
4199   return (Subtarget.getFeatureBits() & ARM::HasV6T2Ops) != 0;
4200 }
4201
4202 bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
4203   if (MI->getNumOperands() < 4)
4204     return true;
4205   unsigned ShOpVal = MI->getOperand(3).getImm();
4206   unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
4207   // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
4208   if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
4209       ((ShImm == 1 || ShImm == 2) &&
4210        ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))
4211     return true;
4212
4213   return false;
4214 }