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