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