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