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