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