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