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