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