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