1 //===- AArch64InstrInfo.cpp - AArch64 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 AArch64 implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64InstrInfo.h"
14 #include "AArch64MachineFunctionInfo.h"
15 #include "AArch64Subtarget.h"
16 #include "MCTargetDesc/AArch64AddressingModes.h"
17 #include "Utils/AArch64BaseInfo.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/StackMaps.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/CodeGen/TargetSubtargetInfo.h"
33 #include "llvm/IR/DebugInfoMetadata.h"
34 #include "llvm/IR/DebugLoc.h"
35 #include "llvm/IR/GlobalValue.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/MC/MCInstBuilder.h"
39 #include "llvm/MC/MCInstrDesc.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CodeGen.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include <cassert>
49 #include <cstdint>
50 #include <iterator>
51 #include <utility>
52 
53 using namespace llvm;
54 
55 #define GET_INSTRINFO_CTOR_DTOR
56 #include "AArch64GenInstrInfo.inc"
57 
58 static cl::opt<unsigned> TBZDisplacementBits(
59     "aarch64-tbz-offset-bits", cl::Hidden, cl::init(14),
60     cl::desc("Restrict range of TB[N]Z instructions (DEBUG)"));
61 
62 static cl::opt<unsigned> CBZDisplacementBits(
63     "aarch64-cbz-offset-bits", cl::Hidden, cl::init(19),
64     cl::desc("Restrict range of CB[N]Z instructions (DEBUG)"));
65 
66 static cl::opt<unsigned>
67     BCCDisplacementBits("aarch64-bcc-offset-bits", cl::Hidden, cl::init(19),
68                         cl::desc("Restrict range of Bcc instructions (DEBUG)"));
69 
70 AArch64InstrInfo::AArch64InstrInfo(const AArch64Subtarget &STI)
71     : AArch64GenInstrInfo(AArch64::ADJCALLSTACKDOWN, AArch64::ADJCALLSTACKUP,
72                           AArch64::CATCHRET),
73       RI(STI.getTargetTriple()), Subtarget(STI) {}
74 
75 /// GetInstSize - Return the number of bytes of code the specified
76 /// instruction may be.  This returns the maximum number of bytes.
77 unsigned AArch64InstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
78   const MachineBasicBlock &MBB = *MI.getParent();
79   const MachineFunction *MF = MBB.getParent();
80   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
81 
82   {
83     auto Op = MI.getOpcode();
84     if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR)
85       return getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
86   }
87 
88   // Meta-instructions emit no code.
89   if (MI.isMetaInstruction())
90     return 0;
91 
92   // FIXME: We currently only handle pseudoinstructions that don't get expanded
93   //        before the assembly printer.
94   unsigned NumBytes = 0;
95   const MCInstrDesc &Desc = MI.getDesc();
96 
97   // Size should be preferably set in
98   // llvm/lib/Target/AArch64/AArch64InstrInfo.td (default case).
99   // Specific cases handle instructions of variable sizes
100   switch (Desc.getOpcode()) {
101   default:
102     if (Desc.getSize())
103       return Desc.getSize();
104 
105     // Anything not explicitly designated otherwise (i.e. pseudo-instructions
106     // with fixed constant size but not specified in .td file) is a normal
107     // 4-byte insn.
108     NumBytes = 4;
109     break;
110   case TargetOpcode::STACKMAP:
111     // The upper bound for a stackmap intrinsic is the full length of its shadow
112     NumBytes = StackMapOpers(&MI).getNumPatchBytes();
113     assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
114     break;
115   case TargetOpcode::PATCHPOINT:
116     // The size of the patchpoint intrinsic is the number of bytes requested
117     NumBytes = PatchPointOpers(&MI).getNumPatchBytes();
118     assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
119     break;
120   case TargetOpcode::STATEPOINT:
121     NumBytes = StatepointOpers(&MI).getNumPatchBytes();
122     assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
123     // No patch bytes means a normal call inst is emitted
124     if (NumBytes == 0)
125       NumBytes = 4;
126     break;
127   case AArch64::SPACE:
128     NumBytes = MI.getOperand(1).getImm();
129     break;
130   case TargetOpcode::BUNDLE:
131     NumBytes = getInstBundleLength(MI);
132     break;
133   }
134 
135   return NumBytes;
136 }
137 
138 unsigned AArch64InstrInfo::getInstBundleLength(const MachineInstr &MI) const {
139   unsigned Size = 0;
140   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
141   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
142   while (++I != E && I->isInsideBundle()) {
143     assert(!I->isBundle() && "No nested bundle!");
144     Size += getInstSizeInBytes(*I);
145   }
146   return Size;
147 }
148 
149 static void parseCondBranch(MachineInstr *LastInst, MachineBasicBlock *&Target,
150                             SmallVectorImpl<MachineOperand> &Cond) {
151   // Block ends with fall-through condbranch.
152   switch (LastInst->getOpcode()) {
153   default:
154     llvm_unreachable("Unknown branch instruction?");
155   case AArch64::Bcc:
156     Target = LastInst->getOperand(1).getMBB();
157     Cond.push_back(LastInst->getOperand(0));
158     break;
159   case AArch64::CBZW:
160   case AArch64::CBZX:
161   case AArch64::CBNZW:
162   case AArch64::CBNZX:
163     Target = LastInst->getOperand(1).getMBB();
164     Cond.push_back(MachineOperand::CreateImm(-1));
165     Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
166     Cond.push_back(LastInst->getOperand(0));
167     break;
168   case AArch64::TBZW:
169   case AArch64::TBZX:
170   case AArch64::TBNZW:
171   case AArch64::TBNZX:
172     Target = LastInst->getOperand(2).getMBB();
173     Cond.push_back(MachineOperand::CreateImm(-1));
174     Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
175     Cond.push_back(LastInst->getOperand(0));
176     Cond.push_back(LastInst->getOperand(1));
177   }
178 }
179 
180 static unsigned getBranchDisplacementBits(unsigned Opc) {
181   switch (Opc) {
182   default:
183     llvm_unreachable("unexpected opcode!");
184   case AArch64::B:
185     return 64;
186   case AArch64::TBNZW:
187   case AArch64::TBZW:
188   case AArch64::TBNZX:
189   case AArch64::TBZX:
190     return TBZDisplacementBits;
191   case AArch64::CBNZW:
192   case AArch64::CBZW:
193   case AArch64::CBNZX:
194   case AArch64::CBZX:
195     return CBZDisplacementBits;
196   case AArch64::Bcc:
197     return BCCDisplacementBits;
198   }
199 }
200 
201 bool AArch64InstrInfo::isBranchOffsetInRange(unsigned BranchOp,
202                                              int64_t BrOffset) const {
203   unsigned Bits = getBranchDisplacementBits(BranchOp);
204   assert(Bits >= 3 && "max branch displacement must be enough to jump"
205                       "over conditional branch expansion");
206   return isIntN(Bits, BrOffset / 4);
207 }
208 
209 MachineBasicBlock *
210 AArch64InstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
211   switch (MI.getOpcode()) {
212   default:
213     llvm_unreachable("unexpected opcode!");
214   case AArch64::B:
215     return MI.getOperand(0).getMBB();
216   case AArch64::TBZW:
217   case AArch64::TBNZW:
218   case AArch64::TBZX:
219   case AArch64::TBNZX:
220     return MI.getOperand(2).getMBB();
221   case AArch64::CBZW:
222   case AArch64::CBNZW:
223   case AArch64::CBZX:
224   case AArch64::CBNZX:
225   case AArch64::Bcc:
226     return MI.getOperand(1).getMBB();
227   }
228 }
229 
230 // Branch analysis.
231 bool AArch64InstrInfo::analyzeBranch(MachineBasicBlock &MBB,
232                                      MachineBasicBlock *&TBB,
233                                      MachineBasicBlock *&FBB,
234                                      SmallVectorImpl<MachineOperand> &Cond,
235                                      bool AllowModify) const {
236   // If the block has no terminators, it just falls into the block after it.
237   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
238   if (I == MBB.end())
239     return false;
240 
241   // Skip over SpeculationBarrierEndBB terminators
242   if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
243       I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
244     --I;
245   }
246 
247   if (!isUnpredicatedTerminator(*I))
248     return false;
249 
250   // Get the last instruction in the block.
251   MachineInstr *LastInst = &*I;
252 
253   // If there is only one terminator instruction, process it.
254   unsigned LastOpc = LastInst->getOpcode();
255   if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
256     if (isUncondBranchOpcode(LastOpc)) {
257       TBB = LastInst->getOperand(0).getMBB();
258       return false;
259     }
260     if (isCondBranchOpcode(LastOpc)) {
261       // Block ends with fall-through condbranch.
262       parseCondBranch(LastInst, TBB, Cond);
263       return false;
264     }
265     return true; // Can't handle indirect branch.
266   }
267 
268   // Get the instruction before it if it is a terminator.
269   MachineInstr *SecondLastInst = &*I;
270   unsigned SecondLastOpc = SecondLastInst->getOpcode();
271 
272   // If AllowModify is true and the block ends with two or more unconditional
273   // branches, delete all but the first unconditional branch.
274   if (AllowModify && isUncondBranchOpcode(LastOpc)) {
275     while (isUncondBranchOpcode(SecondLastOpc)) {
276       LastInst->eraseFromParent();
277       LastInst = SecondLastInst;
278       LastOpc = LastInst->getOpcode();
279       if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
280         // Return now the only terminator is an unconditional branch.
281         TBB = LastInst->getOperand(0).getMBB();
282         return false;
283       } else {
284         SecondLastInst = &*I;
285         SecondLastOpc = SecondLastInst->getOpcode();
286       }
287     }
288   }
289 
290   // If we're allowed to modify and the block ends in a unconditional branch
291   // which could simply fallthrough, remove the branch.  (Note: This case only
292   // matters when we can't understand the whole sequence, otherwise it's also
293   // handled by BranchFolding.cpp.)
294   if (AllowModify && isUncondBranchOpcode(LastOpc) &&
295       MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) {
296     LastInst->eraseFromParent();
297     LastInst = SecondLastInst;
298     LastOpc = LastInst->getOpcode();
299     if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
300       assert(!isUncondBranchOpcode(LastOpc) &&
301              "unreachable unconditional branches removed above");
302 
303       if (isCondBranchOpcode(LastOpc)) {
304         // Block ends with fall-through condbranch.
305         parseCondBranch(LastInst, TBB, Cond);
306         return false;
307       }
308       return true; // Can't handle indirect branch.
309     } else {
310       SecondLastInst = &*I;
311       SecondLastOpc = SecondLastInst->getOpcode();
312     }
313   }
314 
315   // If there are three terminators, we don't know what sort of block this is.
316   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I))
317     return true;
318 
319   // If the block ends with a B and a Bcc, handle it.
320   if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
321     parseCondBranch(SecondLastInst, TBB, Cond);
322     FBB = LastInst->getOperand(0).getMBB();
323     return false;
324   }
325 
326   // If the block ends with two unconditional branches, handle it.  The second
327   // one is not executed, so remove it.
328   if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
329     TBB = SecondLastInst->getOperand(0).getMBB();
330     I = LastInst;
331     if (AllowModify)
332       I->eraseFromParent();
333     return false;
334   }
335 
336   // ...likewise if it ends with an indirect branch followed by an unconditional
337   // branch.
338   if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
339     I = LastInst;
340     if (AllowModify)
341       I->eraseFromParent();
342     return true;
343   }
344 
345   // Otherwise, can't handle this.
346   return true;
347 }
348 
349 bool AArch64InstrInfo::analyzeBranchPredicate(MachineBasicBlock &MBB,
350                                               MachineBranchPredicate &MBP,
351                                               bool AllowModify) const {
352   // For the moment, handle only a block which ends with a cb(n)zx followed by
353   // a fallthrough.  Why this?  Because it is a common form.
354   // TODO: Should we handle b.cc?
355 
356   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
357   if (I == MBB.end())
358     return true;
359 
360   // Skip over SpeculationBarrierEndBB terminators
361   if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
362       I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
363     --I;
364   }
365 
366   if (!isUnpredicatedTerminator(*I))
367     return true;
368 
369   // Get the last instruction in the block.
370   MachineInstr *LastInst = &*I;
371   unsigned LastOpc = LastInst->getOpcode();
372   if (!isCondBranchOpcode(LastOpc))
373     return true;
374 
375   switch (LastOpc) {
376   default:
377     return true;
378   case AArch64::CBZW:
379   case AArch64::CBZX:
380   case AArch64::CBNZW:
381   case AArch64::CBNZX:
382     break;
383   };
384 
385   MBP.TrueDest = LastInst->getOperand(1).getMBB();
386   assert(MBP.TrueDest && "expected!");
387   MBP.FalseDest = MBB.getNextNode();
388 
389   MBP.ConditionDef = nullptr;
390   MBP.SingleUseCondition = false;
391 
392   MBP.LHS = LastInst->getOperand(0);
393   MBP.RHS = MachineOperand::CreateImm(0);
394   MBP.Predicate = LastOpc == AArch64::CBNZX ? MachineBranchPredicate::PRED_NE
395                                             : MachineBranchPredicate::PRED_EQ;
396   return false;
397 }
398 
399 bool AArch64InstrInfo::reverseBranchCondition(
400     SmallVectorImpl<MachineOperand> &Cond) const {
401   if (Cond[0].getImm() != -1) {
402     // Regular Bcc
403     AArch64CC::CondCode CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
404     Cond[0].setImm(AArch64CC::getInvertedCondCode(CC));
405   } else {
406     // Folded compare-and-branch
407     switch (Cond[1].getImm()) {
408     default:
409       llvm_unreachable("Unknown conditional branch!");
410     case AArch64::CBZW:
411       Cond[1].setImm(AArch64::CBNZW);
412       break;
413     case AArch64::CBNZW:
414       Cond[1].setImm(AArch64::CBZW);
415       break;
416     case AArch64::CBZX:
417       Cond[1].setImm(AArch64::CBNZX);
418       break;
419     case AArch64::CBNZX:
420       Cond[1].setImm(AArch64::CBZX);
421       break;
422     case AArch64::TBZW:
423       Cond[1].setImm(AArch64::TBNZW);
424       break;
425     case AArch64::TBNZW:
426       Cond[1].setImm(AArch64::TBZW);
427       break;
428     case AArch64::TBZX:
429       Cond[1].setImm(AArch64::TBNZX);
430       break;
431     case AArch64::TBNZX:
432       Cond[1].setImm(AArch64::TBZX);
433       break;
434     }
435   }
436 
437   return false;
438 }
439 
440 unsigned AArch64InstrInfo::removeBranch(MachineBasicBlock &MBB,
441                                         int *BytesRemoved) const {
442   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
443   if (I == MBB.end())
444     return 0;
445 
446   if (!isUncondBranchOpcode(I->getOpcode()) &&
447       !isCondBranchOpcode(I->getOpcode()))
448     return 0;
449 
450   // Remove the branch.
451   I->eraseFromParent();
452 
453   I = MBB.end();
454 
455   if (I == MBB.begin()) {
456     if (BytesRemoved)
457       *BytesRemoved = 4;
458     return 1;
459   }
460   --I;
461   if (!isCondBranchOpcode(I->getOpcode())) {
462     if (BytesRemoved)
463       *BytesRemoved = 4;
464     return 1;
465   }
466 
467   // Remove the branch.
468   I->eraseFromParent();
469   if (BytesRemoved)
470     *BytesRemoved = 8;
471 
472   return 2;
473 }
474 
475 void AArch64InstrInfo::instantiateCondBranch(
476     MachineBasicBlock &MBB, const DebugLoc &DL, MachineBasicBlock *TBB,
477     ArrayRef<MachineOperand> Cond) const {
478   if (Cond[0].getImm() != -1) {
479     // Regular Bcc
480     BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB);
481   } else {
482     // Folded compare-and-branch
483     // Note that we use addOperand instead of addReg to keep the flags.
484     const MachineInstrBuilder MIB =
485         BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]);
486     if (Cond.size() > 3)
487       MIB.addImm(Cond[3].getImm());
488     MIB.addMBB(TBB);
489   }
490 }
491 
492 unsigned AArch64InstrInfo::insertBranch(
493     MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
494     ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
495   // Shouldn't be a fall through.
496   assert(TBB && "insertBranch must not be told to insert a fallthrough");
497 
498   if (!FBB) {
499     if (Cond.empty()) // Unconditional branch?
500       BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB);
501     else
502       instantiateCondBranch(MBB, DL, TBB, Cond);
503 
504     if (BytesAdded)
505       *BytesAdded = 4;
506 
507     return 1;
508   }
509 
510   // Two-way conditional branch.
511   instantiateCondBranch(MBB, DL, TBB, Cond);
512   BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB);
513 
514   if (BytesAdded)
515     *BytesAdded = 8;
516 
517   return 2;
518 }
519 
520 // Find the original register that VReg is copied from.
521 static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) {
522   while (Register::isVirtualRegister(VReg)) {
523     const MachineInstr *DefMI = MRI.getVRegDef(VReg);
524     if (!DefMI->isFullCopy())
525       return VReg;
526     VReg = DefMI->getOperand(1).getReg();
527   }
528   return VReg;
529 }
530 
531 // Determine if VReg is defined by an instruction that can be folded into a
532 // csel instruction. If so, return the folded opcode, and the replacement
533 // register.
534 static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg,
535                                 unsigned *NewVReg = nullptr) {
536   VReg = removeCopies(MRI, VReg);
537   if (!Register::isVirtualRegister(VReg))
538     return 0;
539 
540   bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg));
541   const MachineInstr *DefMI = MRI.getVRegDef(VReg);
542   unsigned Opc = 0;
543   unsigned SrcOpNum = 0;
544   switch (DefMI->getOpcode()) {
545   case AArch64::ADDSXri:
546   case AArch64::ADDSWri:
547     // if NZCV is used, do not fold.
548     if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1)
549       return 0;
550     // fall-through to ADDXri and ADDWri.
551     LLVM_FALLTHROUGH;
552   case AArch64::ADDXri:
553   case AArch64::ADDWri:
554     // add x, 1 -> csinc.
555     if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 ||
556         DefMI->getOperand(3).getImm() != 0)
557       return 0;
558     SrcOpNum = 1;
559     Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
560     break;
561 
562   case AArch64::ORNXrr:
563   case AArch64::ORNWrr: {
564     // not x -> csinv, represented as orn dst, xzr, src.
565     unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
566     if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
567       return 0;
568     SrcOpNum = 2;
569     Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr;
570     break;
571   }
572 
573   case AArch64::SUBSXrr:
574   case AArch64::SUBSWrr:
575     // if NZCV is used, do not fold.
576     if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1)
577       return 0;
578     // fall-through to SUBXrr and SUBWrr.
579     LLVM_FALLTHROUGH;
580   case AArch64::SUBXrr:
581   case AArch64::SUBWrr: {
582     // neg x -> csneg, represented as sub dst, xzr, src.
583     unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
584     if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
585       return 0;
586     SrcOpNum = 2;
587     Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr;
588     break;
589   }
590   default:
591     return 0;
592   }
593   assert(Opc && SrcOpNum && "Missing parameters");
594 
595   if (NewVReg)
596     *NewVReg = DefMI->getOperand(SrcOpNum).getReg();
597   return Opc;
598 }
599 
600 bool AArch64InstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
601                                        ArrayRef<MachineOperand> Cond,
602                                        Register DstReg, Register TrueReg,
603                                        Register FalseReg, int &CondCycles,
604                                        int &TrueCycles,
605                                        int &FalseCycles) const {
606   // Check register classes.
607   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
608   const TargetRegisterClass *RC =
609       RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
610   if (!RC)
611     return false;
612 
613   // Also need to check the dest regclass, in case we're trying to optimize
614   // something like:
615   // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
616   if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
617     return false;
618 
619   // Expanding cbz/tbz requires an extra cycle of latency on the condition.
620   unsigned ExtraCondLat = Cond.size() != 1;
621 
622   // GPRs are handled by csel.
623   // FIXME: Fold in x+1, -x, and ~x when applicable.
624   if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
625       AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
626     // Single-cycle csel, csinc, csinv, and csneg.
627     CondCycles = 1 + ExtraCondLat;
628     TrueCycles = FalseCycles = 1;
629     if (canFoldIntoCSel(MRI, TrueReg))
630       TrueCycles = 0;
631     else if (canFoldIntoCSel(MRI, FalseReg))
632       FalseCycles = 0;
633     return true;
634   }
635 
636   // Scalar floating point is handled by fcsel.
637   // FIXME: Form fabs, fmin, and fmax when applicable.
638   if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
639       AArch64::FPR32RegClass.hasSubClassEq(RC)) {
640     CondCycles = 5 + ExtraCondLat;
641     TrueCycles = FalseCycles = 2;
642     return true;
643   }
644 
645   // Can't do vectors.
646   return false;
647 }
648 
649 void AArch64InstrInfo::insertSelect(MachineBasicBlock &MBB,
650                                     MachineBasicBlock::iterator I,
651                                     const DebugLoc &DL, Register DstReg,
652                                     ArrayRef<MachineOperand> Cond,
653                                     Register TrueReg, Register FalseReg) const {
654   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
655 
656   // Parse the condition code, see parseCondBranch() above.
657   AArch64CC::CondCode CC;
658   switch (Cond.size()) {
659   default:
660     llvm_unreachable("Unknown condition opcode in Cond");
661   case 1: // b.cc
662     CC = AArch64CC::CondCode(Cond[0].getImm());
663     break;
664   case 3: { // cbz/cbnz
665     // We must insert a compare against 0.
666     bool Is64Bit;
667     switch (Cond[1].getImm()) {
668     default:
669       llvm_unreachable("Unknown branch opcode in Cond");
670     case AArch64::CBZW:
671       Is64Bit = false;
672       CC = AArch64CC::EQ;
673       break;
674     case AArch64::CBZX:
675       Is64Bit = true;
676       CC = AArch64CC::EQ;
677       break;
678     case AArch64::CBNZW:
679       Is64Bit = false;
680       CC = AArch64CC::NE;
681       break;
682     case AArch64::CBNZX:
683       Is64Bit = true;
684       CC = AArch64CC::NE;
685       break;
686     }
687     Register SrcReg = Cond[2].getReg();
688     if (Is64Bit) {
689       // cmp reg, #0 is actually subs xzr, reg, #0.
690       MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass);
691       BuildMI(MBB, I, DL, get(AArch64::SUBSXri), AArch64::XZR)
692           .addReg(SrcReg)
693           .addImm(0)
694           .addImm(0);
695     } else {
696       MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass);
697       BuildMI(MBB, I, DL, get(AArch64::SUBSWri), AArch64::WZR)
698           .addReg(SrcReg)
699           .addImm(0)
700           .addImm(0);
701     }
702     break;
703   }
704   case 4: { // tbz/tbnz
705     // We must insert a tst instruction.
706     switch (Cond[1].getImm()) {
707     default:
708       llvm_unreachable("Unknown branch opcode in Cond");
709     case AArch64::TBZW:
710     case AArch64::TBZX:
711       CC = AArch64CC::EQ;
712       break;
713     case AArch64::TBNZW:
714     case AArch64::TBNZX:
715       CC = AArch64CC::NE;
716       break;
717     }
718     // cmp reg, #foo is actually ands xzr, reg, #1<<foo.
719     if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW)
720       BuildMI(MBB, I, DL, get(AArch64::ANDSWri), AArch64::WZR)
721           .addReg(Cond[2].getReg())
722           .addImm(
723               AArch64_AM::encodeLogicalImmediate(1ull << Cond[3].getImm(), 32));
724     else
725       BuildMI(MBB, I, DL, get(AArch64::ANDSXri), AArch64::XZR)
726           .addReg(Cond[2].getReg())
727           .addImm(
728               AArch64_AM::encodeLogicalImmediate(1ull << Cond[3].getImm(), 64));
729     break;
730   }
731   }
732 
733   unsigned Opc = 0;
734   const TargetRegisterClass *RC = nullptr;
735   bool TryFold = false;
736   if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
737     RC = &AArch64::GPR64RegClass;
738     Opc = AArch64::CSELXr;
739     TryFold = true;
740   } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
741     RC = &AArch64::GPR32RegClass;
742     Opc = AArch64::CSELWr;
743     TryFold = true;
744   } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
745     RC = &AArch64::FPR64RegClass;
746     Opc = AArch64::FCSELDrrr;
747   } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
748     RC = &AArch64::FPR32RegClass;
749     Opc = AArch64::FCSELSrrr;
750   }
751   assert(RC && "Unsupported regclass");
752 
753   // Try folding simple instructions into the csel.
754   if (TryFold) {
755     unsigned NewVReg = 0;
756     unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewVReg);
757     if (FoldedOpc) {
758       // The folded opcodes csinc, csinc and csneg apply the operation to
759       // FalseReg, so we need to invert the condition.
760       CC = AArch64CC::getInvertedCondCode(CC);
761       TrueReg = FalseReg;
762     } else
763       FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewVReg);
764 
765     // Fold the operation. Leave any dead instructions for DCE to clean up.
766     if (FoldedOpc) {
767       FalseReg = NewVReg;
768       Opc = FoldedOpc;
769       // The extends the live range of NewVReg.
770       MRI.clearKillFlags(NewVReg);
771     }
772   }
773 
774   // Pull all virtual register into the appropriate class.
775   MRI.constrainRegClass(TrueReg, RC);
776   MRI.constrainRegClass(FalseReg, RC);
777 
778   // Insert the csel.
779   BuildMI(MBB, I, DL, get(Opc), DstReg)
780       .addReg(TrueReg)
781       .addReg(FalseReg)
782       .addImm(CC);
783 }
784 
785 /// Returns true if a MOVi32imm or MOVi64imm can be expanded to an  ORRxx.
786 static bool canBeExpandedToORR(const MachineInstr &MI, unsigned BitSize) {
787   uint64_t Imm = MI.getOperand(1).getImm();
788   uint64_t UImm = Imm << (64 - BitSize) >> (64 - BitSize);
789   uint64_t Encoding;
790   return AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding);
791 }
792 
793 // FIXME: this implementation should be micro-architecture dependent, so a
794 // micro-architecture target hook should be introduced here in future.
795 bool AArch64InstrInfo::isAsCheapAsAMove(const MachineInstr &MI) const {
796   if (!Subtarget.hasCustomCheapAsMoveHandling())
797     return MI.isAsCheapAsAMove();
798 
799   const unsigned Opcode = MI.getOpcode();
800 
801   // Firstly, check cases gated by features.
802 
803   if (Subtarget.hasZeroCycleZeroingFP()) {
804     if (Opcode == AArch64::FMOVH0 ||
805         Opcode == AArch64::FMOVS0 ||
806         Opcode == AArch64::FMOVD0)
807       return true;
808   }
809 
810   if (Subtarget.hasZeroCycleZeroingGP()) {
811     if (Opcode == TargetOpcode::COPY &&
812         (MI.getOperand(1).getReg() == AArch64::WZR ||
813          MI.getOperand(1).getReg() == AArch64::XZR))
814       return true;
815   }
816 
817   // Secondly, check cases specific to sub-targets.
818 
819   if (Subtarget.hasExynosCheapAsMoveHandling()) {
820     if (isExynosCheapAsMove(MI))
821       return true;
822 
823     return MI.isAsCheapAsAMove();
824   }
825 
826   // Finally, check generic cases.
827 
828   switch (Opcode) {
829   default:
830     return false;
831 
832   // add/sub on register without shift
833   case AArch64::ADDWri:
834   case AArch64::ADDXri:
835   case AArch64::SUBWri:
836   case AArch64::SUBXri:
837     return (MI.getOperand(3).getImm() == 0);
838 
839   // logical ops on immediate
840   case AArch64::ANDWri:
841   case AArch64::ANDXri:
842   case AArch64::EORWri:
843   case AArch64::EORXri:
844   case AArch64::ORRWri:
845   case AArch64::ORRXri:
846     return true;
847 
848   // logical ops on register without shift
849   case AArch64::ANDWrr:
850   case AArch64::ANDXrr:
851   case AArch64::BICWrr:
852   case AArch64::BICXrr:
853   case AArch64::EONWrr:
854   case AArch64::EONXrr:
855   case AArch64::EORWrr:
856   case AArch64::EORXrr:
857   case AArch64::ORNWrr:
858   case AArch64::ORNXrr:
859   case AArch64::ORRWrr:
860   case AArch64::ORRXrr:
861     return true;
862 
863   // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
864   // ORRXri, it is as cheap as MOV
865   case AArch64::MOVi32imm:
866     return canBeExpandedToORR(MI, 32);
867   case AArch64::MOVi64imm:
868     return canBeExpandedToORR(MI, 64);
869   }
870 
871   llvm_unreachable("Unknown opcode to check as cheap as a move!");
872 }
873 
874 bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
875   switch (MI.getOpcode()) {
876   default:
877     return false;
878 
879   case AArch64::ADDWrs:
880   case AArch64::ADDXrs:
881   case AArch64::ADDSWrs:
882   case AArch64::ADDSXrs: {
883     unsigned Imm = MI.getOperand(3).getImm();
884     unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
885     if (ShiftVal == 0)
886       return true;
887     return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
888   }
889 
890   case AArch64::ADDWrx:
891   case AArch64::ADDXrx:
892   case AArch64::ADDXrx64:
893   case AArch64::ADDSWrx:
894   case AArch64::ADDSXrx:
895   case AArch64::ADDSXrx64: {
896     unsigned Imm = MI.getOperand(3).getImm();
897     switch (AArch64_AM::getArithExtendType(Imm)) {
898     default:
899       return false;
900     case AArch64_AM::UXTB:
901     case AArch64_AM::UXTH:
902     case AArch64_AM::UXTW:
903     case AArch64_AM::UXTX:
904       return AArch64_AM::getArithShiftValue(Imm) <= 4;
905     }
906   }
907 
908   case AArch64::SUBWrs:
909   case AArch64::SUBSWrs: {
910     unsigned Imm = MI.getOperand(3).getImm();
911     unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
912     return ShiftVal == 0 ||
913            (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
914   }
915 
916   case AArch64::SUBXrs:
917   case AArch64::SUBSXrs: {
918     unsigned Imm = MI.getOperand(3).getImm();
919     unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
920     return ShiftVal == 0 ||
921            (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
922   }
923 
924   case AArch64::SUBWrx:
925   case AArch64::SUBXrx:
926   case AArch64::SUBXrx64:
927   case AArch64::SUBSWrx:
928   case AArch64::SUBSXrx:
929   case AArch64::SUBSXrx64: {
930     unsigned Imm = MI.getOperand(3).getImm();
931     switch (AArch64_AM::getArithExtendType(Imm)) {
932     default:
933       return false;
934     case AArch64_AM::UXTB:
935     case AArch64_AM::UXTH:
936     case AArch64_AM::UXTW:
937     case AArch64_AM::UXTX:
938       return AArch64_AM::getArithShiftValue(Imm) == 0;
939     }
940   }
941 
942   case AArch64::LDRBBroW:
943   case AArch64::LDRBBroX:
944   case AArch64::LDRBroW:
945   case AArch64::LDRBroX:
946   case AArch64::LDRDroW:
947   case AArch64::LDRDroX:
948   case AArch64::LDRHHroW:
949   case AArch64::LDRHHroX:
950   case AArch64::LDRHroW:
951   case AArch64::LDRHroX:
952   case AArch64::LDRQroW:
953   case AArch64::LDRQroX:
954   case AArch64::LDRSBWroW:
955   case AArch64::LDRSBWroX:
956   case AArch64::LDRSBXroW:
957   case AArch64::LDRSBXroX:
958   case AArch64::LDRSHWroW:
959   case AArch64::LDRSHWroX:
960   case AArch64::LDRSHXroW:
961   case AArch64::LDRSHXroX:
962   case AArch64::LDRSWroW:
963   case AArch64::LDRSWroX:
964   case AArch64::LDRSroW:
965   case AArch64::LDRSroX:
966   case AArch64::LDRWroW:
967   case AArch64::LDRWroX:
968   case AArch64::LDRXroW:
969   case AArch64::LDRXroX:
970   case AArch64::PRFMroW:
971   case AArch64::PRFMroX:
972   case AArch64::STRBBroW:
973   case AArch64::STRBBroX:
974   case AArch64::STRBroW:
975   case AArch64::STRBroX:
976   case AArch64::STRDroW:
977   case AArch64::STRDroX:
978   case AArch64::STRHHroW:
979   case AArch64::STRHHroX:
980   case AArch64::STRHroW:
981   case AArch64::STRHroX:
982   case AArch64::STRQroW:
983   case AArch64::STRQroX:
984   case AArch64::STRSroW:
985   case AArch64::STRSroX:
986   case AArch64::STRWroW:
987   case AArch64::STRWroX:
988   case AArch64::STRXroW:
989   case AArch64::STRXroX: {
990     unsigned IsSigned = MI.getOperand(3).getImm();
991     return !IsSigned;
992   }
993   }
994 }
995 
996 bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
997   unsigned Opc = MI.getOpcode();
998   switch (Opc) {
999     default:
1000       return false;
1001     case AArch64::SEH_StackAlloc:
1002     case AArch64::SEH_SaveFPLR:
1003     case AArch64::SEH_SaveFPLR_X:
1004     case AArch64::SEH_SaveReg:
1005     case AArch64::SEH_SaveReg_X:
1006     case AArch64::SEH_SaveRegP:
1007     case AArch64::SEH_SaveRegP_X:
1008     case AArch64::SEH_SaveFReg:
1009     case AArch64::SEH_SaveFReg_X:
1010     case AArch64::SEH_SaveFRegP:
1011     case AArch64::SEH_SaveFRegP_X:
1012     case AArch64::SEH_SetFP:
1013     case AArch64::SEH_AddFP:
1014     case AArch64::SEH_Nop:
1015     case AArch64::SEH_PrologEnd:
1016     case AArch64::SEH_EpilogStart:
1017     case AArch64::SEH_EpilogEnd:
1018       return true;
1019   }
1020 }
1021 
1022 bool AArch64InstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
1023                                              Register &SrcReg, Register &DstReg,
1024                                              unsigned &SubIdx) const {
1025   switch (MI.getOpcode()) {
1026   default:
1027     return false;
1028   case AArch64::SBFMXri: // aka sxtw
1029   case AArch64::UBFMXri: // aka uxtw
1030     // Check for the 32 -> 64 bit extension case, these instructions can do
1031     // much more.
1032     if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
1033       return false;
1034     // This is a signed or unsigned 32 -> 64 bit extension.
1035     SrcReg = MI.getOperand(1).getReg();
1036     DstReg = MI.getOperand(0).getReg();
1037     SubIdx = AArch64::sub_32;
1038     return true;
1039   }
1040 }
1041 
1042 bool AArch64InstrInfo::areMemAccessesTriviallyDisjoint(
1043     const MachineInstr &MIa, const MachineInstr &MIb) const {
1044   const TargetRegisterInfo *TRI = &getRegisterInfo();
1045   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
1046   int64_t OffsetA = 0, OffsetB = 0;
1047   unsigned WidthA = 0, WidthB = 0;
1048   bool OffsetAIsScalable = false, OffsetBIsScalable = false;
1049 
1050   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
1051   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
1052 
1053   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
1054       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1055     return false;
1056 
1057   // Retrieve the base, offset from the base and width. Width
1058   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8).  If
1059   // base are identical, and the offset of a lower memory access +
1060   // the width doesn't overlap the offset of a higher memory access,
1061   // then the memory accesses are different.
1062   // If OffsetAIsScalable and OffsetBIsScalable are both true, they
1063   // are assumed to have the same scale (vscale).
1064   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
1065                                    WidthA, TRI) &&
1066       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
1067                                    WidthB, TRI)) {
1068     if (BaseOpA->isIdenticalTo(*BaseOpB) &&
1069         OffsetAIsScalable == OffsetBIsScalable) {
1070       int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1071       int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1072       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1073       if (LowOffset + LowWidth <= HighOffset)
1074         return true;
1075     }
1076   }
1077   return false;
1078 }
1079 
1080 bool AArch64InstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1081                                             const MachineBasicBlock *MBB,
1082                                             const MachineFunction &MF) const {
1083   if (TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF))
1084     return true;
1085   switch (MI.getOpcode()) {
1086   case AArch64::HINT:
1087     // CSDB hints are scheduling barriers.
1088     if (MI.getOperand(0).getImm() == 0x14)
1089       return true;
1090     break;
1091   case AArch64::DSB:
1092   case AArch64::ISB:
1093     // DSB and ISB also are scheduling barriers.
1094     return true;
1095   default:;
1096   }
1097   return isSEHInstruction(MI);
1098 }
1099 
1100 /// analyzeCompare - For a comparison instruction, return the source registers
1101 /// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
1102 /// Return true if the comparison instruction can be analyzed.
1103 bool AArch64InstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1104                                       Register &SrcReg2, int64_t &CmpMask,
1105                                       int64_t &CmpValue) const {
1106   // The first operand can be a frame index where we'd normally expect a
1107   // register.
1108   assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
1109   if (!MI.getOperand(1).isReg())
1110     return false;
1111 
1112   switch (MI.getOpcode()) {
1113   default:
1114     break;
1115   case AArch64::PTEST_PP:
1116     SrcReg = MI.getOperand(0).getReg();
1117     SrcReg2 = MI.getOperand(1).getReg();
1118     // Not sure about the mask and value for now...
1119     CmpMask = ~0;
1120     CmpValue = 0;
1121     return true;
1122   case AArch64::SUBSWrr:
1123   case AArch64::SUBSWrs:
1124   case AArch64::SUBSWrx:
1125   case AArch64::SUBSXrr:
1126   case AArch64::SUBSXrs:
1127   case AArch64::SUBSXrx:
1128   case AArch64::ADDSWrr:
1129   case AArch64::ADDSWrs:
1130   case AArch64::ADDSWrx:
1131   case AArch64::ADDSXrr:
1132   case AArch64::ADDSXrs:
1133   case AArch64::ADDSXrx:
1134     // Replace SUBSWrr with SUBWrr if NZCV is not used.
1135     SrcReg = MI.getOperand(1).getReg();
1136     SrcReg2 = MI.getOperand(2).getReg();
1137     CmpMask = ~0;
1138     CmpValue = 0;
1139     return true;
1140   case AArch64::SUBSWri:
1141   case AArch64::ADDSWri:
1142   case AArch64::SUBSXri:
1143   case AArch64::ADDSXri:
1144     SrcReg = MI.getOperand(1).getReg();
1145     SrcReg2 = 0;
1146     CmpMask = ~0;
1147     CmpValue = MI.getOperand(2).getImm();
1148     return true;
1149   case AArch64::ANDSWri:
1150   case AArch64::ANDSXri:
1151     // ANDS does not use the same encoding scheme as the others xxxS
1152     // instructions.
1153     SrcReg = MI.getOperand(1).getReg();
1154     SrcReg2 = 0;
1155     CmpMask = ~0;
1156     CmpValue = AArch64_AM::decodeLogicalImmediate(
1157                    MI.getOperand(2).getImm(),
1158                    MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
1159     return true;
1160   }
1161 
1162   return false;
1163 }
1164 
1165 static bool UpdateOperandRegClass(MachineInstr &Instr) {
1166   MachineBasicBlock *MBB = Instr.getParent();
1167   assert(MBB && "Can't get MachineBasicBlock here");
1168   MachineFunction *MF = MBB->getParent();
1169   assert(MF && "Can't get MachineFunction here");
1170   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1171   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1172   MachineRegisterInfo *MRI = &MF->getRegInfo();
1173 
1174   for (unsigned OpIdx = 0, EndIdx = Instr.getNumOperands(); OpIdx < EndIdx;
1175        ++OpIdx) {
1176     MachineOperand &MO = Instr.getOperand(OpIdx);
1177     const TargetRegisterClass *OpRegCstraints =
1178         Instr.getRegClassConstraint(OpIdx, TII, TRI);
1179 
1180     // If there's no constraint, there's nothing to do.
1181     if (!OpRegCstraints)
1182       continue;
1183     // If the operand is a frame index, there's nothing to do here.
1184     // A frame index operand will resolve correctly during PEI.
1185     if (MO.isFI())
1186       continue;
1187 
1188     assert(MO.isReg() &&
1189            "Operand has register constraints without being a register!");
1190 
1191     Register Reg = MO.getReg();
1192     if (Register::isPhysicalRegister(Reg)) {
1193       if (!OpRegCstraints->contains(Reg))
1194         return false;
1195     } else if (!OpRegCstraints->hasSubClassEq(MRI->getRegClass(Reg)) &&
1196                !MRI->constrainRegClass(Reg, OpRegCstraints))
1197       return false;
1198   }
1199 
1200   return true;
1201 }
1202 
1203 /// Return the opcode that does not set flags when possible - otherwise
1204 /// return the original opcode. The caller is responsible to do the actual
1205 /// substitution and legality checking.
1206 static unsigned convertToNonFlagSettingOpc(const MachineInstr &MI) {
1207   // Don't convert all compare instructions, because for some the zero register
1208   // encoding becomes the sp register.
1209   bool MIDefinesZeroReg = false;
1210   if (MI.definesRegister(AArch64::WZR) || MI.definesRegister(AArch64::XZR))
1211     MIDefinesZeroReg = true;
1212 
1213   switch (MI.getOpcode()) {
1214   default:
1215     return MI.getOpcode();
1216   case AArch64::ADDSWrr:
1217     return AArch64::ADDWrr;
1218   case AArch64::ADDSWri:
1219     return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
1220   case AArch64::ADDSWrs:
1221     return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
1222   case AArch64::ADDSWrx:
1223     return AArch64::ADDWrx;
1224   case AArch64::ADDSXrr:
1225     return AArch64::ADDXrr;
1226   case AArch64::ADDSXri:
1227     return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
1228   case AArch64::ADDSXrs:
1229     return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
1230   case AArch64::ADDSXrx:
1231     return AArch64::ADDXrx;
1232   case AArch64::SUBSWrr:
1233     return AArch64::SUBWrr;
1234   case AArch64::SUBSWri:
1235     return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
1236   case AArch64::SUBSWrs:
1237     return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
1238   case AArch64::SUBSWrx:
1239     return AArch64::SUBWrx;
1240   case AArch64::SUBSXrr:
1241     return AArch64::SUBXrr;
1242   case AArch64::SUBSXri:
1243     return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
1244   case AArch64::SUBSXrs:
1245     return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
1246   case AArch64::SUBSXrx:
1247     return AArch64::SUBXrx;
1248   }
1249 }
1250 
1251 enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
1252 
1253 /// True when condition flags are accessed (either by writing or reading)
1254 /// on the instruction trace starting at From and ending at To.
1255 ///
1256 /// Note: If From and To are from different blocks it's assumed CC are accessed
1257 ///       on the path.
1258 static bool areCFlagsAccessedBetweenInstrs(
1259     MachineBasicBlock::iterator From, MachineBasicBlock::iterator To,
1260     const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
1261   // Early exit if To is at the beginning of the BB.
1262   if (To == To->getParent()->begin())
1263     return true;
1264 
1265   // Check whether the instructions are in the same basic block
1266   // If not, assume the condition flags might get modified somewhere.
1267   if (To->getParent() != From->getParent())
1268     return true;
1269 
1270   // From must be above To.
1271   assert(std::any_of(
1272       ++To.getReverse(), To->getParent()->rend(),
1273       [From](MachineInstr &MI) { return MI.getIterator() == From; }));
1274 
1275   // We iterate backward starting at \p To until we hit \p From.
1276   for (const MachineInstr &Instr :
1277        instructionsWithoutDebug(++To.getReverse(), From.getReverse())) {
1278     if (((AccessToCheck & AK_Write) &&
1279          Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
1280         ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
1281       return true;
1282   }
1283   return false;
1284 }
1285 
1286 /// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
1287 /// operation which could set the flags in an identical manner
1288 bool AArch64InstrInfo::optimizePTestInstr(
1289     MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
1290     const MachineRegisterInfo *MRI) const {
1291   auto *Mask = MRI->getUniqueVRegDef(MaskReg);
1292   auto *Pred = MRI->getUniqueVRegDef(PredReg);
1293   auto NewOp = Pred->getOpcode();
1294   bool OpChanged = false;
1295 
1296   unsigned MaskOpcode = Mask->getOpcode();
1297   unsigned PredOpcode = Pred->getOpcode();
1298   bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
1299   bool PredIsWhileLike = isWhileOpcode(PredOpcode);
1300 
1301   if (isPTrueOpcode(MaskOpcode) && (PredIsPTestLike || PredIsWhileLike)) {
1302     // For PTEST(PTRUE, OTHER_INST), PTEST is redundant when PTRUE doesn't
1303     // deactivate any lanes OTHER_INST might set.
1304     uint64_t MaskElementSize = getElementSizeForOpcode(MaskOpcode);
1305     uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
1306 
1307     // Must be an all active predicate of matching element size.
1308     if ((PredElementSize != MaskElementSize) ||
1309         (Mask->getOperand(1).getImm() != 31))
1310       return false;
1311 
1312     // Fallthough to simply remove the PTEST.
1313   } else if ((Mask == Pred) && (PredIsPTestLike || PredIsWhileLike)) {
1314     // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
1315     // instruction that sets the flags as PTEST would.
1316 
1317     // Fallthough to simply remove the PTEST.
1318   } else if (PredIsPTestLike) {
1319     // For PTEST(PG_1, PTEST_LIKE(PG2, ...)), PTEST is redundant when both
1320     // instructions use the same predicate.
1321     auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1322     if (Mask != PTestLikeMask)
1323       return false;
1324 
1325     // Fallthough to simply remove the PTEST.
1326   } else {
1327     switch (Pred->getOpcode()) {
1328     case AArch64::BRKB_PPzP:
1329     case AArch64::BRKPB_PPzPP: {
1330       // Op 0 is chain, 1 is the mask, 2 the previous predicate to
1331       // propagate, 3 the new predicate.
1332 
1333       // Check to see if our mask is the same as the brkpb's. If
1334       // not the resulting flag bits may be different and we
1335       // can't remove the ptest.
1336       auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1337       if (Mask != PredMask)
1338         return false;
1339 
1340       // Switch to the new opcode
1341       NewOp = Pred->getOpcode() == AArch64::BRKB_PPzP ? AArch64::BRKBS_PPzP
1342                                                       : AArch64::BRKPBS_PPzPP;
1343       OpChanged = true;
1344       break;
1345     }
1346     case AArch64::BRKN_PPzP: {
1347       auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1348       if (Mask != PredMask)
1349         return false;
1350 
1351       NewOp = AArch64::BRKNS_PPzP;
1352       OpChanged = true;
1353       break;
1354     }
1355     case AArch64::RDFFR_PPz: {
1356       // rdffr   p1.b, PredMask=p0/z <--- Definition of Pred
1357       // ptest   Mask=p0, Pred=p1.b  <--- If equal masks, remove this and use
1358       //                                  `rdffrs p1.b, p0/z` above.
1359       auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1360       if (Mask != PredMask)
1361         return false;
1362 
1363       NewOp = AArch64::RDFFRS_PPz;
1364       OpChanged = true;
1365       break;
1366     }
1367     default:
1368       // Bail out if we don't recognize the input
1369       return false;
1370     }
1371   }
1372 
1373   const TargetRegisterInfo *TRI = &getRegisterInfo();
1374 
1375   // If another instruction between Pred and PTest accesses flags, don't remove
1376   // the ptest or update the earlier instruction to modify them.
1377   if (areCFlagsAccessedBetweenInstrs(Pred, PTest, TRI))
1378     return false;
1379 
1380   // If we pass all the checks, it's safe to remove the PTEST and use the flags
1381   // as they are prior to PTEST. Sometimes this requires the tested PTEST
1382   // operand to be replaced with an equivalent instruction that also sets the
1383   // flags.
1384   Pred->setDesc(get(NewOp));
1385   PTest->eraseFromParent();
1386   if (OpChanged) {
1387     bool succeeded = UpdateOperandRegClass(*Pred);
1388     (void)succeeded;
1389     assert(succeeded && "Operands have incompatible register classes!");
1390     Pred->addRegisterDefined(AArch64::NZCV, TRI);
1391   }
1392 
1393   // Ensure that the flags def is live.
1394   if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
1395     unsigned i = 0, e = Pred->getNumOperands();
1396     for (; i != e; ++i) {
1397       MachineOperand &MO = Pred->getOperand(i);
1398       if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
1399         MO.setIsDead(false);
1400         break;
1401       }
1402     }
1403   }
1404   return true;
1405 }
1406 
1407 /// Try to optimize a compare instruction. A compare instruction is an
1408 /// instruction which produces AArch64::NZCV. It can be truly compare
1409 /// instruction
1410 /// when there are no uses of its destination register.
1411 ///
1412 /// The following steps are tried in order:
1413 /// 1. Convert CmpInstr into an unconditional version.
1414 /// 2. Remove CmpInstr if above there is an instruction producing a needed
1415 ///    condition code or an instruction which can be converted into such an
1416 ///    instruction.
1417 ///    Only comparison with zero is supported.
1418 bool AArch64InstrInfo::optimizeCompareInstr(
1419     MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
1420     int64_t CmpValue, const MachineRegisterInfo *MRI) const {
1421   assert(CmpInstr.getParent());
1422   assert(MRI);
1423 
1424   // Replace SUBSWrr with SUBWrr if NZCV is not used.
1425   int DeadNZCVIdx = CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, true);
1426   if (DeadNZCVIdx != -1) {
1427     if (CmpInstr.definesRegister(AArch64::WZR) ||
1428         CmpInstr.definesRegister(AArch64::XZR)) {
1429       CmpInstr.eraseFromParent();
1430       return true;
1431     }
1432     unsigned Opc = CmpInstr.getOpcode();
1433     unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
1434     if (NewOpc == Opc)
1435       return false;
1436     const MCInstrDesc &MCID = get(NewOpc);
1437     CmpInstr.setDesc(MCID);
1438     CmpInstr.RemoveOperand(DeadNZCVIdx);
1439     bool succeeded = UpdateOperandRegClass(CmpInstr);
1440     (void)succeeded;
1441     assert(succeeded && "Some operands reg class are incompatible!");
1442     return true;
1443   }
1444 
1445   if (CmpInstr.getOpcode() == AArch64::PTEST_PP)
1446     return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
1447 
1448   if (SrcReg2 != 0)
1449     return false;
1450 
1451   // CmpInstr is a Compare instruction if destination register is not used.
1452   if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
1453     return false;
1454 
1455   if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
1456     return true;
1457   return (CmpValue == 0 || CmpValue == 1) &&
1458          removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
1459 }
1460 
1461 /// Get opcode of S version of Instr.
1462 /// If Instr is S version its opcode is returned.
1463 /// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
1464 /// or we are not interested in it.
1465 static unsigned sForm(MachineInstr &Instr) {
1466   switch (Instr.getOpcode()) {
1467   default:
1468     return AArch64::INSTRUCTION_LIST_END;
1469 
1470   case AArch64::ADDSWrr:
1471   case AArch64::ADDSWri:
1472   case AArch64::ADDSXrr:
1473   case AArch64::ADDSXri:
1474   case AArch64::SUBSWrr:
1475   case AArch64::SUBSWri:
1476   case AArch64::SUBSXrr:
1477   case AArch64::SUBSXri:
1478     return Instr.getOpcode();
1479 
1480   case AArch64::ADDWrr:
1481     return AArch64::ADDSWrr;
1482   case AArch64::ADDWri:
1483     return AArch64::ADDSWri;
1484   case AArch64::ADDXrr:
1485     return AArch64::ADDSXrr;
1486   case AArch64::ADDXri:
1487     return AArch64::ADDSXri;
1488   case AArch64::ADCWr:
1489     return AArch64::ADCSWr;
1490   case AArch64::ADCXr:
1491     return AArch64::ADCSXr;
1492   case AArch64::SUBWrr:
1493     return AArch64::SUBSWrr;
1494   case AArch64::SUBWri:
1495     return AArch64::SUBSWri;
1496   case AArch64::SUBXrr:
1497     return AArch64::SUBSXrr;
1498   case AArch64::SUBXri:
1499     return AArch64::SUBSXri;
1500   case AArch64::SBCWr:
1501     return AArch64::SBCSWr;
1502   case AArch64::SBCXr:
1503     return AArch64::SBCSXr;
1504   case AArch64::ANDWri:
1505     return AArch64::ANDSWri;
1506   case AArch64::ANDXri:
1507     return AArch64::ANDSXri;
1508   }
1509 }
1510 
1511 /// Check if AArch64::NZCV should be alive in successors of MBB.
1512 static bool areCFlagsAliveInSuccessors(const MachineBasicBlock *MBB) {
1513   for (auto *BB : MBB->successors())
1514     if (BB->isLiveIn(AArch64::NZCV))
1515       return true;
1516   return false;
1517 }
1518 
1519 /// \returns The condition code operand index for \p Instr if it is a branch
1520 /// or select and -1 otherwise.
1521 static int
1522 findCondCodeUseOperandIdxForBranchOrSelect(const MachineInstr &Instr) {
1523   switch (Instr.getOpcode()) {
1524   default:
1525     return -1;
1526 
1527   case AArch64::Bcc: {
1528     int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV);
1529     assert(Idx >= 2);
1530     return Idx - 2;
1531   }
1532 
1533   case AArch64::CSINVWr:
1534   case AArch64::CSINVXr:
1535   case AArch64::CSINCWr:
1536   case AArch64::CSINCXr:
1537   case AArch64::CSELWr:
1538   case AArch64::CSELXr:
1539   case AArch64::CSNEGWr:
1540   case AArch64::CSNEGXr:
1541   case AArch64::FCSELSrrr:
1542   case AArch64::FCSELDrrr: {
1543     int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV);
1544     assert(Idx >= 1);
1545     return Idx - 1;
1546   }
1547   }
1548 }
1549 
1550 namespace {
1551 
1552 struct UsedNZCV {
1553   bool N = false;
1554   bool Z = false;
1555   bool C = false;
1556   bool V = false;
1557 
1558   UsedNZCV() = default;
1559 
1560   UsedNZCV &operator|=(const UsedNZCV &UsedFlags) {
1561     this->N |= UsedFlags.N;
1562     this->Z |= UsedFlags.Z;
1563     this->C |= UsedFlags.C;
1564     this->V |= UsedFlags.V;
1565     return *this;
1566   }
1567 };
1568 
1569 } // end anonymous namespace
1570 
1571 /// Find a condition code used by the instruction.
1572 /// Returns AArch64CC::Invalid if either the instruction does not use condition
1573 /// codes or we don't optimize CmpInstr in the presence of such instructions.
1574 static AArch64CC::CondCode findCondCodeUsedByInstr(const MachineInstr &Instr) {
1575   int CCIdx = findCondCodeUseOperandIdxForBranchOrSelect(Instr);
1576   return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
1577                           Instr.getOperand(CCIdx).getImm())
1578                     : AArch64CC::Invalid;
1579 }
1580 
1581 static UsedNZCV getUsedNZCV(AArch64CC::CondCode CC) {
1582   assert(CC != AArch64CC::Invalid);
1583   UsedNZCV UsedFlags;
1584   switch (CC) {
1585   default:
1586     break;
1587 
1588   case AArch64CC::EQ: // Z set
1589   case AArch64CC::NE: // Z clear
1590     UsedFlags.Z = true;
1591     break;
1592 
1593   case AArch64CC::HI: // Z clear and C set
1594   case AArch64CC::LS: // Z set   or  C clear
1595     UsedFlags.Z = true;
1596     LLVM_FALLTHROUGH;
1597   case AArch64CC::HS: // C set
1598   case AArch64CC::LO: // C clear
1599     UsedFlags.C = true;
1600     break;
1601 
1602   case AArch64CC::MI: // N set
1603   case AArch64CC::PL: // N clear
1604     UsedFlags.N = true;
1605     break;
1606 
1607   case AArch64CC::VS: // V set
1608   case AArch64CC::VC: // V clear
1609     UsedFlags.V = true;
1610     break;
1611 
1612   case AArch64CC::GT: // Z clear, N and V the same
1613   case AArch64CC::LE: // Z set,   N and V differ
1614     UsedFlags.Z = true;
1615     LLVM_FALLTHROUGH;
1616   case AArch64CC::GE: // N and V the same
1617   case AArch64CC::LT: // N and V differ
1618     UsedFlags.N = true;
1619     UsedFlags.V = true;
1620     break;
1621   }
1622   return UsedFlags;
1623 }
1624 
1625 /// \returns Conditions flags used after \p CmpInstr in its MachineBB if they
1626 /// are not containing C or V flags and NZCV flags are not alive in successors
1627 /// of the same \p CmpInstr and \p MI parent. \returns None otherwise.
1628 ///
1629 /// Collect instructions using that flags in \p CCUseInstrs if provided.
1630 static Optional<UsedNZCV>
1631 examineCFlagsUse(MachineInstr &MI, MachineInstr &CmpInstr,
1632                  const TargetRegisterInfo &TRI,
1633                  SmallVectorImpl<MachineInstr *> *CCUseInstrs = nullptr) {
1634   MachineBasicBlock *CmpParent = CmpInstr.getParent();
1635   if (MI.getParent() != CmpParent)
1636     return None;
1637 
1638   if (areCFlagsAliveInSuccessors(CmpParent))
1639     return None;
1640 
1641   UsedNZCV NZCVUsedAfterCmp;
1642   for (MachineInstr &Instr : instructionsWithoutDebug(
1643            std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
1644     if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
1645       AArch64CC::CondCode CC = findCondCodeUsedByInstr(Instr);
1646       if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
1647         return None;
1648       NZCVUsedAfterCmp |= getUsedNZCV(CC);
1649       if (CCUseInstrs)
1650         CCUseInstrs->push_back(&Instr);
1651     }
1652     if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
1653       break;
1654   }
1655   if (NZCVUsedAfterCmp.C || NZCVUsedAfterCmp.V)
1656     return None;
1657   return NZCVUsedAfterCmp;
1658 }
1659 
1660 static bool isADDSRegImm(unsigned Opcode) {
1661   return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
1662 }
1663 
1664 static bool isSUBSRegImm(unsigned Opcode) {
1665   return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
1666 }
1667 
1668 /// Check if CmpInstr can be substituted by MI.
1669 ///
1670 /// CmpInstr can be substituted:
1671 /// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
1672 /// - and, MI and CmpInstr are from the same MachineBB
1673 /// - and, condition flags are not alive in successors of the CmpInstr parent
1674 /// - and, if MI opcode is the S form there must be no defs of flags between
1675 ///        MI and CmpInstr
1676 ///        or if MI opcode is not the S form there must be neither defs of flags
1677 ///        nor uses of flags between MI and CmpInstr.
1678 /// - and  C/V flags are not used after CmpInstr
1679 static bool canInstrSubstituteCmpInstr(MachineInstr &MI, MachineInstr &CmpInstr,
1680                                        const TargetRegisterInfo &TRI) {
1681   assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
1682 
1683   const unsigned CmpOpcode = CmpInstr.getOpcode();
1684   if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
1685     return false;
1686 
1687   if (!examineCFlagsUse(MI, CmpInstr, TRI))
1688     return false;
1689 
1690   AccessKind AccessToCheck = AK_Write;
1691   if (sForm(MI) != MI.getOpcode())
1692     AccessToCheck = AK_All;
1693   return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
1694 }
1695 
1696 /// Substitute an instruction comparing to zero with another instruction
1697 /// which produces needed condition flags.
1698 ///
1699 /// Return true on success.
1700 bool AArch64InstrInfo::substituteCmpToZero(
1701     MachineInstr &CmpInstr, unsigned SrcReg,
1702     const MachineRegisterInfo &MRI) const {
1703   // Get the unique definition of SrcReg.
1704   MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
1705   if (!MI)
1706     return false;
1707 
1708   const TargetRegisterInfo &TRI = getRegisterInfo();
1709 
1710   unsigned NewOpc = sForm(*MI);
1711   if (NewOpc == AArch64::INSTRUCTION_LIST_END)
1712     return false;
1713 
1714   if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
1715     return false;
1716 
1717   // Update the instruction to set NZCV.
1718   MI->setDesc(get(NewOpc));
1719   CmpInstr.eraseFromParent();
1720   bool succeeded = UpdateOperandRegClass(*MI);
1721   (void)succeeded;
1722   assert(succeeded && "Some operands reg class are incompatible!");
1723   MI->addRegisterDefined(AArch64::NZCV, &TRI);
1724   return true;
1725 }
1726 
1727 /// \returns True if \p CmpInstr can be removed.
1728 ///
1729 /// \p IsInvertCC is true if, after removing \p CmpInstr, condition
1730 /// codes used in \p CCUseInstrs must be inverted.
1731 static bool canCmpInstrBeRemoved(MachineInstr &MI, MachineInstr &CmpInstr,
1732                                  int CmpValue, const TargetRegisterInfo &TRI,
1733                                  SmallVectorImpl<MachineInstr *> &CCUseInstrs,
1734                                  bool &IsInvertCC) {
1735   assert((CmpValue == 0 || CmpValue == 1) &&
1736          "Only comparisons to 0 or 1 considered for removal!");
1737 
1738   // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
1739   unsigned MIOpc = MI.getOpcode();
1740   if (MIOpc == AArch64::CSINCWr) {
1741     if (MI.getOperand(1).getReg() != AArch64::WZR ||
1742         MI.getOperand(2).getReg() != AArch64::WZR)
1743       return false;
1744   } else if (MIOpc == AArch64::CSINCXr) {
1745     if (MI.getOperand(1).getReg() != AArch64::XZR ||
1746         MI.getOperand(2).getReg() != AArch64::XZR)
1747       return false;
1748   } else {
1749     return false;
1750   }
1751   AArch64CC::CondCode MICC = findCondCodeUsedByInstr(MI);
1752   if (MICC == AArch64CC::Invalid)
1753     return false;
1754 
1755   // NZCV needs to be defined
1756   if (MI.findRegisterDefOperandIdx(AArch64::NZCV, true) != -1)
1757     return false;
1758 
1759   // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
1760   const unsigned CmpOpcode = CmpInstr.getOpcode();
1761   bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
1762   if (CmpValue && !IsSubsRegImm)
1763     return false;
1764   if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
1765     return false;
1766 
1767   // MI conditions allowed: eq, ne, mi, pl
1768   UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
1769   if (MIUsedNZCV.C || MIUsedNZCV.V)
1770     return false;
1771 
1772   Optional<UsedNZCV> NZCVUsedAfterCmp =
1773       examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
1774   // Condition flags are not used in CmpInstr basic block successors and only
1775   // Z or N flags allowed to be used after CmpInstr within its basic block
1776   if (!NZCVUsedAfterCmp)
1777     return false;
1778   // Z or N flag used after CmpInstr must correspond to the flag used in MI
1779   if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
1780       (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
1781     return false;
1782   // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
1783   if (MIUsedNZCV.N && !CmpValue)
1784     return false;
1785 
1786   // There must be no defs of flags between MI and CmpInstr
1787   if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
1788     return false;
1789 
1790   // Condition code is inverted in the following cases:
1791   // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
1792   // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
1793   IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
1794                (!CmpValue && MICC == AArch64CC::NE);
1795   return true;
1796 }
1797 
1798 /// Remove comparision in csinc-cmp sequence
1799 ///
1800 /// Examples:
1801 /// 1. \code
1802 ///   csinc w9, wzr, wzr, ne
1803 ///   cmp   w9, #0
1804 ///   b.eq
1805 ///    \endcode
1806 /// to
1807 ///    \code
1808 ///   csinc w9, wzr, wzr, ne
1809 ///   b.ne
1810 ///    \endcode
1811 ///
1812 /// 2. \code
1813 ///   csinc x2, xzr, xzr, mi
1814 ///   cmp   x2, #1
1815 ///   b.pl
1816 ///    \endcode
1817 /// to
1818 ///    \code
1819 ///   csinc x2, xzr, xzr, mi
1820 ///   b.pl
1821 ///    \endcode
1822 ///
1823 /// \param  CmpInstr comparison instruction
1824 /// \return True when comparison removed
1825 bool AArch64InstrInfo::removeCmpToZeroOrOne(
1826     MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
1827     const MachineRegisterInfo &MRI) const {
1828   MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
1829   if (!MI)
1830     return false;
1831   const TargetRegisterInfo &TRI = getRegisterInfo();
1832   SmallVector<MachineInstr *, 4> CCUseInstrs;
1833   bool IsInvertCC = false;
1834   if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
1835                             IsInvertCC))
1836     return false;
1837   // Make transformation
1838   CmpInstr.eraseFromParent();
1839   if (IsInvertCC) {
1840     // Invert condition codes in CmpInstr CC users
1841     for (MachineInstr *CCUseInstr : CCUseInstrs) {
1842       int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
1843       assert(Idx >= 0 && "Unexpected instruction using CC.");
1844       MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
1845       AArch64CC::CondCode CCUse = AArch64CC::getInvertedCondCode(
1846           static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
1847       CCOperand.setImm(CCUse);
1848     }
1849   }
1850   return true;
1851 }
1852 
1853 bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1854   if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
1855       MI.getOpcode() != AArch64::CATCHRET)
1856     return false;
1857 
1858   MachineBasicBlock &MBB = *MI.getParent();
1859   auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
1860   auto TRI = Subtarget.getRegisterInfo();
1861   DebugLoc DL = MI.getDebugLoc();
1862 
1863   if (MI.getOpcode() == AArch64::CATCHRET) {
1864     // Skip to the first instruction before the epilog.
1865     const TargetInstrInfo *TII =
1866       MBB.getParent()->getSubtarget().getInstrInfo();
1867     MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
1868     auto MBBI = MachineBasicBlock::iterator(MI);
1869     MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
1870     while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
1871            FirstEpilogSEH != MBB.begin())
1872       FirstEpilogSEH = std::prev(FirstEpilogSEH);
1873     if (FirstEpilogSEH != MBB.begin())
1874       FirstEpilogSEH = std::next(FirstEpilogSEH);
1875     BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
1876         .addReg(AArch64::X0, RegState::Define)
1877         .addMBB(TargetMBB);
1878     BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
1879         .addReg(AArch64::X0, RegState::Define)
1880         .addReg(AArch64::X0)
1881         .addMBB(TargetMBB)
1882         .addImm(0);
1883     return true;
1884   }
1885 
1886   Register Reg = MI.getOperand(0).getReg();
1887   Module &M = *MBB.getParent()->getFunction().getParent();
1888   if (M.getStackProtectorGuard() == "sysreg") {
1889     const AArch64SysReg::SysReg *SrcReg =
1890         AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
1891     if (!SrcReg)
1892       report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
1893 
1894     // mrs xN, sysreg
1895     BuildMI(MBB, MI, DL, get(AArch64::MRS))
1896         .addDef(Reg, RegState::Renamable)
1897         .addImm(SrcReg->Encoding);
1898     int Offset = M.getStackProtectorGuardOffset();
1899     if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
1900       // ldr xN, [xN, #offset]
1901       BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
1902           .addDef(Reg)
1903           .addUse(Reg, RegState::Kill)
1904           .addImm(Offset / 8);
1905     } else if (Offset >= -256 && Offset <= 255) {
1906       // ldur xN, [xN, #offset]
1907       BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
1908           .addDef(Reg)
1909           .addUse(Reg, RegState::Kill)
1910           .addImm(Offset);
1911     } else if (Offset >= -4095 && Offset <= 4095) {
1912       if (Offset > 0) {
1913         // add xN, xN, #offset
1914         BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
1915             .addDef(Reg)
1916             .addUse(Reg, RegState::Kill)
1917             .addImm(Offset)
1918             .addImm(0);
1919       } else {
1920         // sub xN, xN, #offset
1921         BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
1922             .addDef(Reg)
1923             .addUse(Reg, RegState::Kill)
1924             .addImm(-Offset)
1925             .addImm(0);
1926       }
1927       // ldr xN, [xN]
1928       BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
1929           .addDef(Reg)
1930           .addUse(Reg, RegState::Kill)
1931           .addImm(0);
1932     } else {
1933       // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
1934       // than 23760.
1935       // It might be nice to use AArch64::MOVi32imm here, which would get
1936       // expanded in PreSched2 after PostRA, but our lone scratch Reg already
1937       // contains the MRS result. findScratchNonCalleeSaveRegister() in
1938       // AArch64FrameLowering might help us find such a scratch register
1939       // though. If we failed to find a scratch register, we could emit a
1940       // stream of add instructions to build up the immediate. Or, we could try
1941       // to insert a AArch64::MOVi32imm before register allocation so that we
1942       // didn't need to scavenge for a scratch register.
1943       report_fatal_error("Unable to encode Stack Protector Guard Offset");
1944     }
1945     MBB.erase(MI);
1946     return true;
1947   }
1948 
1949   const GlobalValue *GV =
1950       cast<GlobalValue>((*MI.memoperands_begin())->getValue());
1951   const TargetMachine &TM = MBB.getParent()->getTarget();
1952   unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
1953   const unsigned char MO_NC = AArch64II::MO_NC;
1954 
1955   if ((OpFlags & AArch64II::MO_GOT) != 0) {
1956     BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
1957         .addGlobalAddress(GV, 0, OpFlags);
1958     if (Subtarget.isTargetILP32()) {
1959       unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
1960       BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
1961           .addDef(Reg32, RegState::Dead)
1962           .addUse(Reg, RegState::Kill)
1963           .addImm(0)
1964           .addMemOperand(*MI.memoperands_begin())
1965           .addDef(Reg, RegState::Implicit);
1966     } else {
1967       BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
1968           .addReg(Reg, RegState::Kill)
1969           .addImm(0)
1970           .addMemOperand(*MI.memoperands_begin());
1971     }
1972   } else if (TM.getCodeModel() == CodeModel::Large) {
1973     assert(!Subtarget.isTargetILP32() && "how can large exist in ILP32?");
1974     BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
1975         .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
1976         .addImm(0);
1977     BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
1978         .addReg(Reg, RegState::Kill)
1979         .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
1980         .addImm(16);
1981     BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
1982         .addReg(Reg, RegState::Kill)
1983         .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
1984         .addImm(32);
1985     BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
1986         .addReg(Reg, RegState::Kill)
1987         .addGlobalAddress(GV, 0, AArch64II::MO_G3)
1988         .addImm(48);
1989     BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
1990         .addReg(Reg, RegState::Kill)
1991         .addImm(0)
1992         .addMemOperand(*MI.memoperands_begin());
1993   } else if (TM.getCodeModel() == CodeModel::Tiny) {
1994     BuildMI(MBB, MI, DL, get(AArch64::ADR), Reg)
1995         .addGlobalAddress(GV, 0, OpFlags);
1996   } else {
1997     BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
1998         .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
1999     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
2000     if (Subtarget.isTargetILP32()) {
2001       unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2002       BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2003           .addDef(Reg32, RegState::Dead)
2004           .addUse(Reg, RegState::Kill)
2005           .addGlobalAddress(GV, 0, LoFlags)
2006           .addMemOperand(*MI.memoperands_begin())
2007           .addDef(Reg, RegState::Implicit);
2008     } else {
2009       BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2010           .addReg(Reg, RegState::Kill)
2011           .addGlobalAddress(GV, 0, LoFlags)
2012           .addMemOperand(*MI.memoperands_begin());
2013     }
2014   }
2015 
2016   MBB.erase(MI);
2017 
2018   return true;
2019 }
2020 
2021 // Return true if this instruction simply sets its single destination register
2022 // to zero. This is equivalent to a register rename of the zero-register.
2023 bool AArch64InstrInfo::isGPRZero(const MachineInstr &MI) {
2024   switch (MI.getOpcode()) {
2025   default:
2026     break;
2027   case AArch64::MOVZWi:
2028   case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
2029     if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
2030       assert(MI.getDesc().getNumOperands() == 3 &&
2031              MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
2032       return true;
2033     }
2034     break;
2035   case AArch64::ANDWri: // and Rd, Rzr, #imm
2036     return MI.getOperand(1).getReg() == AArch64::WZR;
2037   case AArch64::ANDXri:
2038     return MI.getOperand(1).getReg() == AArch64::XZR;
2039   case TargetOpcode::COPY:
2040     return MI.getOperand(1).getReg() == AArch64::WZR;
2041   }
2042   return false;
2043 }
2044 
2045 // Return true if this instruction simply renames a general register without
2046 // modifying bits.
2047 bool AArch64InstrInfo::isGPRCopy(const MachineInstr &MI) {
2048   switch (MI.getOpcode()) {
2049   default:
2050     break;
2051   case TargetOpcode::COPY: {
2052     // GPR32 copies will by lowered to ORRXrs
2053     Register DstReg = MI.getOperand(0).getReg();
2054     return (AArch64::GPR32RegClass.contains(DstReg) ||
2055             AArch64::GPR64RegClass.contains(DstReg));
2056   }
2057   case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
2058     if (MI.getOperand(1).getReg() == AArch64::XZR) {
2059       assert(MI.getDesc().getNumOperands() == 4 &&
2060              MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
2061       return true;
2062     }
2063     break;
2064   case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
2065     if (MI.getOperand(2).getImm() == 0) {
2066       assert(MI.getDesc().getNumOperands() == 4 &&
2067              MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
2068       return true;
2069     }
2070     break;
2071   }
2072   return false;
2073 }
2074 
2075 // Return true if this instruction simply renames a general register without
2076 // modifying bits.
2077 bool AArch64InstrInfo::isFPRCopy(const MachineInstr &MI) {
2078   switch (MI.getOpcode()) {
2079   default:
2080     break;
2081   case TargetOpcode::COPY: {
2082     Register DstReg = MI.getOperand(0).getReg();
2083     return AArch64::FPR128RegClass.contains(DstReg);
2084   }
2085   case AArch64::ORRv16i8:
2086     if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
2087       assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
2088              "invalid ORRv16i8 operands");
2089       return true;
2090     }
2091     break;
2092   }
2093   return false;
2094 }
2095 
2096 unsigned AArch64InstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
2097                                                int &FrameIndex) const {
2098   switch (MI.getOpcode()) {
2099   default:
2100     break;
2101   case AArch64::LDRWui:
2102   case AArch64::LDRXui:
2103   case AArch64::LDRBui:
2104   case AArch64::LDRHui:
2105   case AArch64::LDRSui:
2106   case AArch64::LDRDui:
2107   case AArch64::LDRQui:
2108     if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2109         MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2110       FrameIndex = MI.getOperand(1).getIndex();
2111       return MI.getOperand(0).getReg();
2112     }
2113     break;
2114   }
2115 
2116   return 0;
2117 }
2118 
2119 unsigned AArch64InstrInfo::isStoreToStackSlot(const MachineInstr &MI,
2120                                               int &FrameIndex) const {
2121   switch (MI.getOpcode()) {
2122   default:
2123     break;
2124   case AArch64::STRWui:
2125   case AArch64::STRXui:
2126   case AArch64::STRBui:
2127   case AArch64::STRHui:
2128   case AArch64::STRSui:
2129   case AArch64::STRDui:
2130   case AArch64::STRQui:
2131   case AArch64::LDR_PXI:
2132   case AArch64::STR_PXI:
2133     if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2134         MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2135       FrameIndex = MI.getOperand(1).getIndex();
2136       return MI.getOperand(0).getReg();
2137     }
2138     break;
2139   }
2140   return 0;
2141 }
2142 
2143 /// Check all MachineMemOperands for a hint to suppress pairing.
2144 bool AArch64InstrInfo::isLdStPairSuppressed(const MachineInstr &MI) {
2145   return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2146     return MMO->getFlags() & MOSuppressPair;
2147   });
2148 }
2149 
2150 /// Set a flag on the first MachineMemOperand to suppress pairing.
2151 void AArch64InstrInfo::suppressLdStPair(MachineInstr &MI) {
2152   if (MI.memoperands_empty())
2153     return;
2154   (*MI.memoperands_begin())->setFlags(MOSuppressPair);
2155 }
2156 
2157 /// Check all MachineMemOperands for a hint that the load/store is strided.
2158 bool AArch64InstrInfo::isStridedAccess(const MachineInstr &MI) {
2159   return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2160     return MMO->getFlags() & MOStridedAccess;
2161   });
2162 }
2163 
2164 bool AArch64InstrInfo::hasUnscaledLdStOffset(unsigned Opc) {
2165   switch (Opc) {
2166   default:
2167     return false;
2168   case AArch64::STURSi:
2169   case AArch64::STRSpre:
2170   case AArch64::STURDi:
2171   case AArch64::STRDpre:
2172   case AArch64::STURQi:
2173   case AArch64::STRQpre:
2174   case AArch64::STURBBi:
2175   case AArch64::STURHHi:
2176   case AArch64::STURWi:
2177   case AArch64::STRWpre:
2178   case AArch64::STURXi:
2179   case AArch64::STRXpre:
2180   case AArch64::LDURSi:
2181   case AArch64::LDRSpre:
2182   case AArch64::LDURDi:
2183   case AArch64::LDRDpre:
2184   case AArch64::LDURQi:
2185   case AArch64::LDRQpre:
2186   case AArch64::LDURWi:
2187   case AArch64::LDRWpre:
2188   case AArch64::LDURXi:
2189   case AArch64::LDRXpre:
2190   case AArch64::LDURSWi:
2191   case AArch64::LDURHHi:
2192   case AArch64::LDURBBi:
2193   case AArch64::LDURSBWi:
2194   case AArch64::LDURSHWi:
2195     return true;
2196   }
2197 }
2198 
2199 Optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
2200   switch (Opc) {
2201   default: return {};
2202   case AArch64::PRFMui: return AArch64::PRFUMi;
2203   case AArch64::LDRXui: return AArch64::LDURXi;
2204   case AArch64::LDRWui: return AArch64::LDURWi;
2205   case AArch64::LDRBui: return AArch64::LDURBi;
2206   case AArch64::LDRHui: return AArch64::LDURHi;
2207   case AArch64::LDRSui: return AArch64::LDURSi;
2208   case AArch64::LDRDui: return AArch64::LDURDi;
2209   case AArch64::LDRQui: return AArch64::LDURQi;
2210   case AArch64::LDRBBui: return AArch64::LDURBBi;
2211   case AArch64::LDRHHui: return AArch64::LDURHHi;
2212   case AArch64::LDRSBXui: return AArch64::LDURSBXi;
2213   case AArch64::LDRSBWui: return AArch64::LDURSBWi;
2214   case AArch64::LDRSHXui: return AArch64::LDURSHXi;
2215   case AArch64::LDRSHWui: return AArch64::LDURSHWi;
2216   case AArch64::LDRSWui: return AArch64::LDURSWi;
2217   case AArch64::STRXui: return AArch64::STURXi;
2218   case AArch64::STRWui: return AArch64::STURWi;
2219   case AArch64::STRBui: return AArch64::STURBi;
2220   case AArch64::STRHui: return AArch64::STURHi;
2221   case AArch64::STRSui: return AArch64::STURSi;
2222   case AArch64::STRDui: return AArch64::STURDi;
2223   case AArch64::STRQui: return AArch64::STURQi;
2224   case AArch64::STRBBui: return AArch64::STURBBi;
2225   case AArch64::STRHHui: return AArch64::STURHHi;
2226   }
2227 }
2228 
2229 unsigned AArch64InstrInfo::getLoadStoreImmIdx(unsigned Opc) {
2230   switch (Opc) {
2231   default:
2232     return 2;
2233   case AArch64::LDPXi:
2234   case AArch64::LDPDi:
2235   case AArch64::STPXi:
2236   case AArch64::STPDi:
2237   case AArch64::LDNPXi:
2238   case AArch64::LDNPDi:
2239   case AArch64::STNPXi:
2240   case AArch64::STNPDi:
2241   case AArch64::LDPQi:
2242   case AArch64::STPQi:
2243   case AArch64::LDNPQi:
2244   case AArch64::STNPQi:
2245   case AArch64::LDPWi:
2246   case AArch64::LDPSi:
2247   case AArch64::STPWi:
2248   case AArch64::STPSi:
2249   case AArch64::LDNPWi:
2250   case AArch64::LDNPSi:
2251   case AArch64::STNPWi:
2252   case AArch64::STNPSi:
2253   case AArch64::LDG:
2254   case AArch64::STGPi:
2255 
2256   case AArch64::LD1B_IMM:
2257   case AArch64::LD1B_H_IMM:
2258   case AArch64::LD1B_S_IMM:
2259   case AArch64::LD1B_D_IMM:
2260   case AArch64::LD1SB_H_IMM:
2261   case AArch64::LD1SB_S_IMM:
2262   case AArch64::LD1SB_D_IMM:
2263   case AArch64::LD1H_IMM:
2264   case AArch64::LD1H_S_IMM:
2265   case AArch64::LD1H_D_IMM:
2266   case AArch64::LD1SH_S_IMM:
2267   case AArch64::LD1SH_D_IMM:
2268   case AArch64::LD1W_IMM:
2269   case AArch64::LD1W_D_IMM:
2270   case AArch64::LD1SW_D_IMM:
2271   case AArch64::LD1D_IMM:
2272 
2273   case AArch64::LD2B_IMM:
2274   case AArch64::LD2H_IMM:
2275   case AArch64::LD2W_IMM:
2276   case AArch64::LD2D_IMM:
2277   case AArch64::LD3B_IMM:
2278   case AArch64::LD3H_IMM:
2279   case AArch64::LD3W_IMM:
2280   case AArch64::LD3D_IMM:
2281   case AArch64::LD4B_IMM:
2282   case AArch64::LD4H_IMM:
2283   case AArch64::LD4W_IMM:
2284   case AArch64::LD4D_IMM:
2285 
2286   case AArch64::ST1B_IMM:
2287   case AArch64::ST1B_H_IMM:
2288   case AArch64::ST1B_S_IMM:
2289   case AArch64::ST1B_D_IMM:
2290   case AArch64::ST1H_IMM:
2291   case AArch64::ST1H_S_IMM:
2292   case AArch64::ST1H_D_IMM:
2293   case AArch64::ST1W_IMM:
2294   case AArch64::ST1W_D_IMM:
2295   case AArch64::ST1D_IMM:
2296 
2297   case AArch64::ST2B_IMM:
2298   case AArch64::ST2H_IMM:
2299   case AArch64::ST2W_IMM:
2300   case AArch64::ST2D_IMM:
2301   case AArch64::ST3B_IMM:
2302   case AArch64::ST3H_IMM:
2303   case AArch64::ST3W_IMM:
2304   case AArch64::ST3D_IMM:
2305   case AArch64::ST4B_IMM:
2306   case AArch64::ST4H_IMM:
2307   case AArch64::ST4W_IMM:
2308   case AArch64::ST4D_IMM:
2309 
2310   case AArch64::LD1RB_IMM:
2311   case AArch64::LD1RB_H_IMM:
2312   case AArch64::LD1RB_S_IMM:
2313   case AArch64::LD1RB_D_IMM:
2314   case AArch64::LD1RSB_H_IMM:
2315   case AArch64::LD1RSB_S_IMM:
2316   case AArch64::LD1RSB_D_IMM:
2317   case AArch64::LD1RH_IMM:
2318   case AArch64::LD1RH_S_IMM:
2319   case AArch64::LD1RH_D_IMM:
2320   case AArch64::LD1RSH_S_IMM:
2321   case AArch64::LD1RSH_D_IMM:
2322   case AArch64::LD1RW_IMM:
2323   case AArch64::LD1RW_D_IMM:
2324   case AArch64::LD1RSW_IMM:
2325   case AArch64::LD1RD_IMM:
2326 
2327   case AArch64::LDNT1B_ZRI:
2328   case AArch64::LDNT1H_ZRI:
2329   case AArch64::LDNT1W_ZRI:
2330   case AArch64::LDNT1D_ZRI:
2331   case AArch64::STNT1B_ZRI:
2332   case AArch64::STNT1H_ZRI:
2333   case AArch64::STNT1W_ZRI:
2334   case AArch64::STNT1D_ZRI:
2335 
2336   case AArch64::LDNF1B_IMM:
2337   case AArch64::LDNF1B_H_IMM:
2338   case AArch64::LDNF1B_S_IMM:
2339   case AArch64::LDNF1B_D_IMM:
2340   case AArch64::LDNF1SB_H_IMM:
2341   case AArch64::LDNF1SB_S_IMM:
2342   case AArch64::LDNF1SB_D_IMM:
2343   case AArch64::LDNF1H_IMM:
2344   case AArch64::LDNF1H_S_IMM:
2345   case AArch64::LDNF1H_D_IMM:
2346   case AArch64::LDNF1SH_S_IMM:
2347   case AArch64::LDNF1SH_D_IMM:
2348   case AArch64::LDNF1W_IMM:
2349   case AArch64::LDNF1W_D_IMM:
2350   case AArch64::LDNF1SW_D_IMM:
2351   case AArch64::LDNF1D_IMM:
2352     return 3;
2353   case AArch64::ADDG:
2354   case AArch64::STGOffset:
2355   case AArch64::LDR_PXI:
2356   case AArch64::STR_PXI:
2357     return 2;
2358   }
2359 }
2360 
2361 bool AArch64InstrInfo::isPairableLdStInst(const MachineInstr &MI) {
2362   switch (MI.getOpcode()) {
2363   default:
2364     return false;
2365   // Scaled instructions.
2366   case AArch64::STRSui:
2367   case AArch64::STRDui:
2368   case AArch64::STRQui:
2369   case AArch64::STRXui:
2370   case AArch64::STRWui:
2371   case AArch64::LDRSui:
2372   case AArch64::LDRDui:
2373   case AArch64::LDRQui:
2374   case AArch64::LDRXui:
2375   case AArch64::LDRWui:
2376   case AArch64::LDRSWui:
2377   // Unscaled instructions.
2378   case AArch64::STURSi:
2379   case AArch64::STRSpre:
2380   case AArch64::STURDi:
2381   case AArch64::STRDpre:
2382   case AArch64::STURQi:
2383   case AArch64::STRQpre:
2384   case AArch64::STURWi:
2385   case AArch64::STRWpre:
2386   case AArch64::STURXi:
2387   case AArch64::STRXpre:
2388   case AArch64::LDURSi:
2389   case AArch64::LDRSpre:
2390   case AArch64::LDURDi:
2391   case AArch64::LDRDpre:
2392   case AArch64::LDURQi:
2393   case AArch64::LDRQpre:
2394   case AArch64::LDURWi:
2395   case AArch64::LDRWpre:
2396   case AArch64::LDURXi:
2397   case AArch64::LDRXpre:
2398   case AArch64::LDURSWi:
2399     return true;
2400   }
2401 }
2402 
2403 unsigned AArch64InstrInfo::convertToFlagSettingOpc(unsigned Opc,
2404                                                    bool &Is64Bit) {
2405   switch (Opc) {
2406   default:
2407     llvm_unreachable("Opcode has no flag setting equivalent!");
2408   // 32-bit cases:
2409   case AArch64::ADDWri:
2410     Is64Bit = false;
2411     return AArch64::ADDSWri;
2412   case AArch64::ADDWrr:
2413     Is64Bit = false;
2414     return AArch64::ADDSWrr;
2415   case AArch64::ADDWrs:
2416     Is64Bit = false;
2417     return AArch64::ADDSWrs;
2418   case AArch64::ADDWrx:
2419     Is64Bit = false;
2420     return AArch64::ADDSWrx;
2421   case AArch64::ANDWri:
2422     Is64Bit = false;
2423     return AArch64::ANDSWri;
2424   case AArch64::ANDWrr:
2425     Is64Bit = false;
2426     return AArch64::ANDSWrr;
2427   case AArch64::ANDWrs:
2428     Is64Bit = false;
2429     return AArch64::ANDSWrs;
2430   case AArch64::BICWrr:
2431     Is64Bit = false;
2432     return AArch64::BICSWrr;
2433   case AArch64::BICWrs:
2434     Is64Bit = false;
2435     return AArch64::BICSWrs;
2436   case AArch64::SUBWri:
2437     Is64Bit = false;
2438     return AArch64::SUBSWri;
2439   case AArch64::SUBWrr:
2440     Is64Bit = false;
2441     return AArch64::SUBSWrr;
2442   case AArch64::SUBWrs:
2443     Is64Bit = false;
2444     return AArch64::SUBSWrs;
2445   case AArch64::SUBWrx:
2446     Is64Bit = false;
2447     return AArch64::SUBSWrx;
2448   // 64-bit cases:
2449   case AArch64::ADDXri:
2450     Is64Bit = true;
2451     return AArch64::ADDSXri;
2452   case AArch64::ADDXrr:
2453     Is64Bit = true;
2454     return AArch64::ADDSXrr;
2455   case AArch64::ADDXrs:
2456     Is64Bit = true;
2457     return AArch64::ADDSXrs;
2458   case AArch64::ADDXrx:
2459     Is64Bit = true;
2460     return AArch64::ADDSXrx;
2461   case AArch64::ANDXri:
2462     Is64Bit = true;
2463     return AArch64::ANDSXri;
2464   case AArch64::ANDXrr:
2465     Is64Bit = true;
2466     return AArch64::ANDSXrr;
2467   case AArch64::ANDXrs:
2468     Is64Bit = true;
2469     return AArch64::ANDSXrs;
2470   case AArch64::BICXrr:
2471     Is64Bit = true;
2472     return AArch64::BICSXrr;
2473   case AArch64::BICXrs:
2474     Is64Bit = true;
2475     return AArch64::BICSXrs;
2476   case AArch64::SUBXri:
2477     Is64Bit = true;
2478     return AArch64::SUBSXri;
2479   case AArch64::SUBXrr:
2480     Is64Bit = true;
2481     return AArch64::SUBSXrr;
2482   case AArch64::SUBXrs:
2483     Is64Bit = true;
2484     return AArch64::SUBSXrs;
2485   case AArch64::SUBXrx:
2486     Is64Bit = true;
2487     return AArch64::SUBSXrx;
2488   }
2489 }
2490 
2491 // Is this a candidate for ld/st merging or pairing?  For example, we don't
2492 // touch volatiles or load/stores that have a hint to avoid pair formation.
2493 bool AArch64InstrInfo::isCandidateToMergeOrPair(const MachineInstr &MI) const {
2494 
2495   bool IsPreLdSt = isPreLdSt(MI);
2496 
2497   // If this is a volatile load/store, don't mess with it.
2498   if (MI.hasOrderedMemoryRef())
2499     return false;
2500 
2501   // Make sure this is a reg/fi+imm (as opposed to an address reloc).
2502   // For Pre-inc LD/ST, the operand is shifted by one.
2503   assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
2504           MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
2505          "Expected a reg or frame index operand.");
2506 
2507   // For Pre-indexed addressing quadword instructions, the third operand is the
2508   // immediate value.
2509   bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
2510 
2511   if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
2512     return false;
2513 
2514   // Can't merge/pair if the instruction modifies the base register.
2515   // e.g., ldr x0, [x0]
2516   // This case will never occur with an FI base.
2517   // However, if the instruction is an LDR/STR<S,D,Q,W,X>pre, it can be merged.
2518   // For example:
2519   //   ldr q0, [x11, #32]!
2520   //   ldr q1, [x11, #16]
2521   //   to
2522   //   ldp q0, q1, [x11, #32]!
2523   if (MI.getOperand(1).isReg() && !IsPreLdSt) {
2524     Register BaseReg = MI.getOperand(1).getReg();
2525     const TargetRegisterInfo *TRI = &getRegisterInfo();
2526     if (MI.modifiesRegister(BaseReg, TRI))
2527       return false;
2528   }
2529 
2530   // Check if this load/store has a hint to avoid pair formation.
2531   // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
2532   if (isLdStPairSuppressed(MI))
2533     return false;
2534 
2535   // Do not pair any callee-save store/reload instructions in the
2536   // prologue/epilogue if the CFI information encoded the operations as separate
2537   // instructions, as that will cause the size of the actual prologue to mismatch
2538   // with the prologue size recorded in the Windows CFI.
2539   const MCAsmInfo *MAI = MI.getMF()->getTarget().getMCAsmInfo();
2540   bool NeedsWinCFI = MAI->usesWindowsCFI() &&
2541                      MI.getMF()->getFunction().needsUnwindTableEntry();
2542   if (NeedsWinCFI && (MI.getFlag(MachineInstr::FrameSetup) ||
2543                       MI.getFlag(MachineInstr::FrameDestroy)))
2544     return false;
2545 
2546   // On some CPUs quad load/store pairs are slower than two single load/stores.
2547   if (Subtarget.isPaired128Slow()) {
2548     switch (MI.getOpcode()) {
2549     default:
2550       break;
2551     case AArch64::LDURQi:
2552     case AArch64::STURQi:
2553     case AArch64::LDRQui:
2554     case AArch64::STRQui:
2555       return false;
2556     }
2557   }
2558 
2559   return true;
2560 }
2561 
2562 bool AArch64InstrInfo::getMemOperandsWithOffsetWidth(
2563     const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
2564     int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
2565     const TargetRegisterInfo *TRI) const {
2566   if (!LdSt.mayLoadOrStore())
2567     return false;
2568 
2569   const MachineOperand *BaseOp;
2570   if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
2571                                     Width, TRI))
2572     return false;
2573   BaseOps.push_back(BaseOp);
2574   return true;
2575 }
2576 
2577 Optional<ExtAddrMode>
2578 AArch64InstrInfo::getAddrModeFromMemoryOp(const MachineInstr &MemI,
2579                                           const TargetRegisterInfo *TRI) const {
2580   const MachineOperand *Base; // Filled with the base operand of MI.
2581   int64_t Offset;             // Filled with the offset of MI.
2582   bool OffsetIsScalable;
2583   if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable, TRI))
2584     return None;
2585 
2586   if (!Base->isReg())
2587     return None;
2588   ExtAddrMode AM;
2589   AM.BaseReg = Base->getReg();
2590   AM.Displacement = Offset;
2591   AM.ScaledReg = 0;
2592   AM.Scale = 0;
2593   return AM;
2594 }
2595 
2596 bool AArch64InstrInfo::getMemOperandWithOffsetWidth(
2597     const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
2598     bool &OffsetIsScalable, unsigned &Width,
2599     const TargetRegisterInfo *TRI) const {
2600   assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
2601   // Handle only loads/stores with base register followed by immediate offset.
2602   if (LdSt.getNumExplicitOperands() == 3) {
2603     // Non-paired instruction (e.g., ldr x1, [x0, #8]).
2604     if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
2605         !LdSt.getOperand(2).isImm())
2606       return false;
2607   } else if (LdSt.getNumExplicitOperands() == 4) {
2608     // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
2609     if (!LdSt.getOperand(1).isReg() ||
2610         (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
2611         !LdSt.getOperand(3).isImm())
2612       return false;
2613   } else
2614     return false;
2615 
2616   // Get the scaling factor for the instruction and set the width for the
2617   // instruction.
2618   TypeSize Scale(0U, false);
2619   int64_t Dummy1, Dummy2;
2620 
2621   // If this returns false, then it's an instruction we don't want to handle.
2622   if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
2623     return false;
2624 
2625   // Compute the offset. Offset is calculated as the immediate operand
2626   // multiplied by the scaling factor. Unscaled instructions have scaling factor
2627   // set to 1.
2628   if (LdSt.getNumExplicitOperands() == 3) {
2629     BaseOp = &LdSt.getOperand(1);
2630     Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinSize();
2631   } else {
2632     assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
2633     BaseOp = &LdSt.getOperand(2);
2634     Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinSize();
2635   }
2636   OffsetIsScalable = Scale.isScalable();
2637 
2638   if (!BaseOp->isReg() && !BaseOp->isFI())
2639     return false;
2640 
2641   return true;
2642 }
2643 
2644 MachineOperand &
2645 AArch64InstrInfo::getMemOpBaseRegImmOfsOffsetOperand(MachineInstr &LdSt) const {
2646   assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
2647   MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
2648   assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
2649   return OfsOp;
2650 }
2651 
2652 bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
2653                                     unsigned &Width, int64_t &MinOffset,
2654                                     int64_t &MaxOffset) {
2655   const unsigned SVEMaxBytesPerVector = AArch64::SVEMaxBitsPerVector / 8;
2656   switch (Opcode) {
2657   // Not a memory operation or something we want to handle.
2658   default:
2659     Scale = TypeSize::Fixed(0);
2660     Width = 0;
2661     MinOffset = MaxOffset = 0;
2662     return false;
2663   case AArch64::STRWpost:
2664   case AArch64::LDRWpost:
2665     Width = 32;
2666     Scale = TypeSize::Fixed(4);
2667     MinOffset = -256;
2668     MaxOffset = 255;
2669     break;
2670   case AArch64::LDURQi:
2671   case AArch64::STURQi:
2672     Width = 16;
2673     Scale = TypeSize::Fixed(1);
2674     MinOffset = -256;
2675     MaxOffset = 255;
2676     break;
2677   case AArch64::PRFUMi:
2678   case AArch64::LDURXi:
2679   case AArch64::LDURDi:
2680   case AArch64::STURXi:
2681   case AArch64::STURDi:
2682     Width = 8;
2683     Scale = TypeSize::Fixed(1);
2684     MinOffset = -256;
2685     MaxOffset = 255;
2686     break;
2687   case AArch64::LDURWi:
2688   case AArch64::LDURSi:
2689   case AArch64::LDURSWi:
2690   case AArch64::STURWi:
2691   case AArch64::STURSi:
2692     Width = 4;
2693     Scale = TypeSize::Fixed(1);
2694     MinOffset = -256;
2695     MaxOffset = 255;
2696     break;
2697   case AArch64::LDURHi:
2698   case AArch64::LDURHHi:
2699   case AArch64::LDURSHXi:
2700   case AArch64::LDURSHWi:
2701   case AArch64::STURHi:
2702   case AArch64::STURHHi:
2703     Width = 2;
2704     Scale = TypeSize::Fixed(1);
2705     MinOffset = -256;
2706     MaxOffset = 255;
2707     break;
2708   case AArch64::LDURBi:
2709   case AArch64::LDURBBi:
2710   case AArch64::LDURSBXi:
2711   case AArch64::LDURSBWi:
2712   case AArch64::STURBi:
2713   case AArch64::STURBBi:
2714     Width = 1;
2715     Scale = TypeSize::Fixed(1);
2716     MinOffset = -256;
2717     MaxOffset = 255;
2718     break;
2719   case AArch64::LDPQi:
2720   case AArch64::LDNPQi:
2721   case AArch64::STPQi:
2722   case AArch64::STNPQi:
2723     Scale = TypeSize::Fixed(16);
2724     Width = 32;
2725     MinOffset = -64;
2726     MaxOffset = 63;
2727     break;
2728   case AArch64::LDRQui:
2729   case AArch64::STRQui:
2730     Scale = TypeSize::Fixed(16);
2731     Width = 16;
2732     MinOffset = 0;
2733     MaxOffset = 4095;
2734     break;
2735   case AArch64::LDPXi:
2736   case AArch64::LDPDi:
2737   case AArch64::LDNPXi:
2738   case AArch64::LDNPDi:
2739   case AArch64::STPXi:
2740   case AArch64::STPDi:
2741   case AArch64::STNPXi:
2742   case AArch64::STNPDi:
2743     Scale = TypeSize::Fixed(8);
2744     Width = 16;
2745     MinOffset = -64;
2746     MaxOffset = 63;
2747     break;
2748   case AArch64::PRFMui:
2749   case AArch64::LDRXui:
2750   case AArch64::LDRDui:
2751   case AArch64::STRXui:
2752   case AArch64::STRDui:
2753     Scale = TypeSize::Fixed(8);
2754     Width = 8;
2755     MinOffset = 0;
2756     MaxOffset = 4095;
2757     break;
2758   case AArch64::StoreSwiftAsyncContext:
2759     // Store is an STRXui, but there might be an ADDXri in the expansion too.
2760     Scale = TypeSize::Fixed(1);
2761     Width = 8;
2762     MinOffset = 0;
2763     MaxOffset = 4095;
2764     break;
2765   case AArch64::LDPWi:
2766   case AArch64::LDPSi:
2767   case AArch64::LDNPWi:
2768   case AArch64::LDNPSi:
2769   case AArch64::STPWi:
2770   case AArch64::STPSi:
2771   case AArch64::STNPWi:
2772   case AArch64::STNPSi:
2773     Scale = TypeSize::Fixed(4);
2774     Width = 8;
2775     MinOffset = -64;
2776     MaxOffset = 63;
2777     break;
2778   case AArch64::LDRWui:
2779   case AArch64::LDRSui:
2780   case AArch64::LDRSWui:
2781   case AArch64::STRWui:
2782   case AArch64::STRSui:
2783     Scale = TypeSize::Fixed(4);
2784     Width = 4;
2785     MinOffset = 0;
2786     MaxOffset = 4095;
2787     break;
2788   case AArch64::LDRHui:
2789   case AArch64::LDRHHui:
2790   case AArch64::LDRSHWui:
2791   case AArch64::LDRSHXui:
2792   case AArch64::STRHui:
2793   case AArch64::STRHHui:
2794     Scale = TypeSize::Fixed(2);
2795     Width = 2;
2796     MinOffset = 0;
2797     MaxOffset = 4095;
2798     break;
2799   case AArch64::LDRBui:
2800   case AArch64::LDRBBui:
2801   case AArch64::LDRSBWui:
2802   case AArch64::LDRSBXui:
2803   case AArch64::STRBui:
2804   case AArch64::STRBBui:
2805     Scale = TypeSize::Fixed(1);
2806     Width = 1;
2807     MinOffset = 0;
2808     MaxOffset = 4095;
2809     break;
2810   case AArch64::STPXpre:
2811   case AArch64::LDPXpost:
2812   case AArch64::STPDpre:
2813   case AArch64::LDPDpost:
2814     Scale = TypeSize::Fixed(8);
2815     Width = 8;
2816     MinOffset = -512;
2817     MaxOffset = 504;
2818     break;
2819   case AArch64::STPQpre:
2820   case AArch64::LDPQpost:
2821     Scale = TypeSize::Fixed(16);
2822     Width = 16;
2823     MinOffset = -1024;
2824     MaxOffset = 1008;
2825     break;
2826   case AArch64::STRXpre:
2827   case AArch64::STRDpre:
2828   case AArch64::LDRXpost:
2829   case AArch64::LDRDpost:
2830     Scale = TypeSize::Fixed(1);
2831     Width = 8;
2832     MinOffset = -256;
2833     MaxOffset = 255;
2834     break;
2835   case AArch64::STRQpre:
2836   case AArch64::LDRQpost:
2837     Scale = TypeSize::Fixed(1);
2838     Width = 16;
2839     MinOffset = -256;
2840     MaxOffset = 255;
2841     break;
2842   case AArch64::ADDG:
2843     Scale = TypeSize::Fixed(16);
2844     Width = 0;
2845     MinOffset = 0;
2846     MaxOffset = 63;
2847     break;
2848   case AArch64::TAGPstack:
2849     Scale = TypeSize::Fixed(16);
2850     Width = 0;
2851     // TAGP with a negative offset turns into SUBP, which has a maximum offset
2852     // of 63 (not 64!).
2853     MinOffset = -63;
2854     MaxOffset = 63;
2855     break;
2856   case AArch64::LDG:
2857   case AArch64::STGOffset:
2858   case AArch64::STZGOffset:
2859     Scale = TypeSize::Fixed(16);
2860     Width = 16;
2861     MinOffset = -256;
2862     MaxOffset = 255;
2863     break;
2864   case AArch64::STR_ZZZZXI:
2865   case AArch64::LDR_ZZZZXI:
2866     Scale = TypeSize::Scalable(16);
2867     Width = SVEMaxBytesPerVector * 4;
2868     MinOffset = -256;
2869     MaxOffset = 252;
2870     break;
2871   case AArch64::STR_ZZZXI:
2872   case AArch64::LDR_ZZZXI:
2873     Scale = TypeSize::Scalable(16);
2874     Width = SVEMaxBytesPerVector * 3;
2875     MinOffset = -256;
2876     MaxOffset = 253;
2877     break;
2878   case AArch64::STR_ZZXI:
2879   case AArch64::LDR_ZZXI:
2880     Scale = TypeSize::Scalable(16);
2881     Width = SVEMaxBytesPerVector * 2;
2882     MinOffset = -256;
2883     MaxOffset = 254;
2884     break;
2885   case AArch64::LDR_PXI:
2886   case AArch64::STR_PXI:
2887     Scale = TypeSize::Scalable(2);
2888     Width = SVEMaxBytesPerVector / 8;
2889     MinOffset = -256;
2890     MaxOffset = 255;
2891     break;
2892   case AArch64::LDR_ZXI:
2893   case AArch64::STR_ZXI:
2894     Scale = TypeSize::Scalable(16);
2895     Width = SVEMaxBytesPerVector;
2896     MinOffset = -256;
2897     MaxOffset = 255;
2898     break;
2899   case AArch64::LD1B_IMM:
2900   case AArch64::LD1H_IMM:
2901   case AArch64::LD1W_IMM:
2902   case AArch64::LD1D_IMM:
2903   case AArch64::LDNT1B_ZRI:
2904   case AArch64::LDNT1H_ZRI:
2905   case AArch64::LDNT1W_ZRI:
2906   case AArch64::LDNT1D_ZRI:
2907   case AArch64::ST1B_IMM:
2908   case AArch64::ST1H_IMM:
2909   case AArch64::ST1W_IMM:
2910   case AArch64::ST1D_IMM:
2911   case AArch64::STNT1B_ZRI:
2912   case AArch64::STNT1H_ZRI:
2913   case AArch64::STNT1W_ZRI:
2914   case AArch64::STNT1D_ZRI:
2915   case AArch64::LDNF1B_IMM:
2916   case AArch64::LDNF1H_IMM:
2917   case AArch64::LDNF1W_IMM:
2918   case AArch64::LDNF1D_IMM:
2919     // A full vectors worth of data
2920     // Width = mbytes * elements
2921     Scale = TypeSize::Scalable(16);
2922     Width = SVEMaxBytesPerVector;
2923     MinOffset = -8;
2924     MaxOffset = 7;
2925     break;
2926   case AArch64::LD2B_IMM:
2927   case AArch64::LD2H_IMM:
2928   case AArch64::LD2W_IMM:
2929   case AArch64::LD2D_IMM:
2930   case AArch64::ST2B_IMM:
2931   case AArch64::ST2H_IMM:
2932   case AArch64::ST2W_IMM:
2933   case AArch64::ST2D_IMM:
2934     Scale = TypeSize::Scalable(32);
2935     Width = SVEMaxBytesPerVector * 2;
2936     MinOffset = -8;
2937     MaxOffset = 7;
2938     break;
2939   case AArch64::LD3B_IMM:
2940   case AArch64::LD3H_IMM:
2941   case AArch64::LD3W_IMM:
2942   case AArch64::LD3D_IMM:
2943   case AArch64::ST3B_IMM:
2944   case AArch64::ST3H_IMM:
2945   case AArch64::ST3W_IMM:
2946   case AArch64::ST3D_IMM:
2947     Scale = TypeSize::Scalable(48);
2948     Width = SVEMaxBytesPerVector * 3;
2949     MinOffset = -8;
2950     MaxOffset = 7;
2951     break;
2952   case AArch64::LD4B_IMM:
2953   case AArch64::LD4H_IMM:
2954   case AArch64::LD4W_IMM:
2955   case AArch64::LD4D_IMM:
2956   case AArch64::ST4B_IMM:
2957   case AArch64::ST4H_IMM:
2958   case AArch64::ST4W_IMM:
2959   case AArch64::ST4D_IMM:
2960     Scale = TypeSize::Scalable(64);
2961     Width = SVEMaxBytesPerVector * 4;
2962     MinOffset = -8;
2963     MaxOffset = 7;
2964     break;
2965   case AArch64::LD1B_H_IMM:
2966   case AArch64::LD1SB_H_IMM:
2967   case AArch64::LD1H_S_IMM:
2968   case AArch64::LD1SH_S_IMM:
2969   case AArch64::LD1W_D_IMM:
2970   case AArch64::LD1SW_D_IMM:
2971   case AArch64::ST1B_H_IMM:
2972   case AArch64::ST1H_S_IMM:
2973   case AArch64::ST1W_D_IMM:
2974   case AArch64::LDNF1B_H_IMM:
2975   case AArch64::LDNF1SB_H_IMM:
2976   case AArch64::LDNF1H_S_IMM:
2977   case AArch64::LDNF1SH_S_IMM:
2978   case AArch64::LDNF1W_D_IMM:
2979   case AArch64::LDNF1SW_D_IMM:
2980     // A half vector worth of data
2981     // Width = mbytes * elements
2982     Scale = TypeSize::Scalable(8);
2983     Width = SVEMaxBytesPerVector / 2;
2984     MinOffset = -8;
2985     MaxOffset = 7;
2986     break;
2987   case AArch64::LD1B_S_IMM:
2988   case AArch64::LD1SB_S_IMM:
2989   case AArch64::LD1H_D_IMM:
2990   case AArch64::LD1SH_D_IMM:
2991   case AArch64::ST1B_S_IMM:
2992   case AArch64::ST1H_D_IMM:
2993   case AArch64::LDNF1B_S_IMM:
2994   case AArch64::LDNF1SB_S_IMM:
2995   case AArch64::LDNF1H_D_IMM:
2996   case AArch64::LDNF1SH_D_IMM:
2997     // A quarter vector worth of data
2998     // Width = mbytes * elements
2999     Scale = TypeSize::Scalable(4);
3000     Width = SVEMaxBytesPerVector / 4;
3001     MinOffset = -8;
3002     MaxOffset = 7;
3003     break;
3004   case AArch64::LD1B_D_IMM:
3005   case AArch64::LD1SB_D_IMM:
3006   case AArch64::ST1B_D_IMM:
3007   case AArch64::LDNF1B_D_IMM:
3008   case AArch64::LDNF1SB_D_IMM:
3009     // A eighth vector worth of data
3010     // Width = mbytes * elements
3011     Scale = TypeSize::Scalable(2);
3012     Width = SVEMaxBytesPerVector / 8;
3013     MinOffset = -8;
3014     MaxOffset = 7;
3015     break;
3016   case AArch64::ST2GOffset:
3017   case AArch64::STZ2GOffset:
3018     Scale = TypeSize::Fixed(16);
3019     Width = 32;
3020     MinOffset = -256;
3021     MaxOffset = 255;
3022     break;
3023   case AArch64::STGPi:
3024     Scale = TypeSize::Fixed(16);
3025     Width = 16;
3026     MinOffset = -64;
3027     MaxOffset = 63;
3028     break;
3029   case AArch64::LD1RB_IMM:
3030   case AArch64::LD1RB_H_IMM:
3031   case AArch64::LD1RB_S_IMM:
3032   case AArch64::LD1RB_D_IMM:
3033   case AArch64::LD1RSB_H_IMM:
3034   case AArch64::LD1RSB_S_IMM:
3035   case AArch64::LD1RSB_D_IMM:
3036     Scale = TypeSize::Fixed(1);
3037     Width = 1;
3038     MinOffset = 0;
3039     MaxOffset = 63;
3040     break;
3041   case AArch64::LD1RH_IMM:
3042   case AArch64::LD1RH_S_IMM:
3043   case AArch64::LD1RH_D_IMM:
3044   case AArch64::LD1RSH_S_IMM:
3045   case AArch64::LD1RSH_D_IMM:
3046     Scale = TypeSize::Fixed(2);
3047     Width = 2;
3048     MinOffset = 0;
3049     MaxOffset = 63;
3050     break;
3051   case AArch64::LD1RW_IMM:
3052   case AArch64::LD1RW_D_IMM:
3053   case AArch64::LD1RSW_IMM:
3054     Scale = TypeSize::Fixed(4);
3055     Width = 4;
3056     MinOffset = 0;
3057     MaxOffset = 63;
3058     break;
3059   case AArch64::LD1RD_IMM:
3060     Scale = TypeSize::Fixed(8);
3061     Width = 8;
3062     MinOffset = 0;
3063     MaxOffset = 63;
3064     break;
3065   }
3066 
3067   return true;
3068 }
3069 
3070 // Scaling factor for unscaled load or store.
3071 int AArch64InstrInfo::getMemScale(unsigned Opc) {
3072   switch (Opc) {
3073   default:
3074     llvm_unreachable("Opcode has unknown scale!");
3075   case AArch64::LDRBBui:
3076   case AArch64::LDURBBi:
3077   case AArch64::LDRSBWui:
3078   case AArch64::LDURSBWi:
3079   case AArch64::STRBBui:
3080   case AArch64::STURBBi:
3081     return 1;
3082   case AArch64::LDRHHui:
3083   case AArch64::LDURHHi:
3084   case AArch64::LDRSHWui:
3085   case AArch64::LDURSHWi:
3086   case AArch64::STRHHui:
3087   case AArch64::STURHHi:
3088     return 2;
3089   case AArch64::LDRSui:
3090   case AArch64::LDURSi:
3091   case AArch64::LDRSpre:
3092   case AArch64::LDRSWui:
3093   case AArch64::LDURSWi:
3094   case AArch64::LDRWpre:
3095   case AArch64::LDRWui:
3096   case AArch64::LDURWi:
3097   case AArch64::STRSui:
3098   case AArch64::STURSi:
3099   case AArch64::STRSpre:
3100   case AArch64::STRWui:
3101   case AArch64::STURWi:
3102   case AArch64::STRWpre:
3103   case AArch64::LDPSi:
3104   case AArch64::LDPSWi:
3105   case AArch64::LDPWi:
3106   case AArch64::STPSi:
3107   case AArch64::STPWi:
3108     return 4;
3109   case AArch64::LDRDui:
3110   case AArch64::LDURDi:
3111   case AArch64::LDRDpre:
3112   case AArch64::LDRXui:
3113   case AArch64::LDURXi:
3114   case AArch64::LDRXpre:
3115   case AArch64::STRDui:
3116   case AArch64::STURDi:
3117   case AArch64::STRDpre:
3118   case AArch64::STRXui:
3119   case AArch64::STURXi:
3120   case AArch64::STRXpre:
3121   case AArch64::LDPDi:
3122   case AArch64::LDPXi:
3123   case AArch64::STPDi:
3124   case AArch64::STPXi:
3125     return 8;
3126   case AArch64::LDRQui:
3127   case AArch64::LDURQi:
3128   case AArch64::STRQui:
3129   case AArch64::STURQi:
3130   case AArch64::STRQpre:
3131   case AArch64::LDPQi:
3132   case AArch64::LDRQpre:
3133   case AArch64::STPQi:
3134   case AArch64::STGOffset:
3135   case AArch64::STZGOffset:
3136   case AArch64::ST2GOffset:
3137   case AArch64::STZ2GOffset:
3138   case AArch64::STGPi:
3139     return 16;
3140   }
3141 }
3142 
3143 bool AArch64InstrInfo::isPreLd(const MachineInstr &MI) {
3144   switch (MI.getOpcode()) {
3145   default:
3146     return false;
3147   case AArch64::LDRWpre:
3148   case AArch64::LDRXpre:
3149   case AArch64::LDRSpre:
3150   case AArch64::LDRDpre:
3151   case AArch64::LDRQpre:
3152     return true;
3153   }
3154 }
3155 
3156 bool AArch64InstrInfo::isPreSt(const MachineInstr &MI) {
3157   switch (MI.getOpcode()) {
3158   default:
3159     return false;
3160   case AArch64::STRWpre:
3161   case AArch64::STRXpre:
3162   case AArch64::STRSpre:
3163   case AArch64::STRDpre:
3164   case AArch64::STRQpre:
3165     return true;
3166   }
3167 }
3168 
3169 bool AArch64InstrInfo::isPreLdSt(const MachineInstr &MI) {
3170   return isPreLd(MI) || isPreSt(MI);
3171 }
3172 
3173 static const TargetRegisterClass *getRegClass(const MachineInstr &MI,
3174                                               Register Reg) {
3175   if (MI.getParent() == nullptr)
3176     return nullptr;
3177   const MachineFunction *MF = MI.getParent()->getParent();
3178   return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
3179 }
3180 
3181 bool AArch64InstrInfo::isQForm(const MachineInstr &MI) {
3182   auto IsQFPR = [&](const MachineOperand &Op) {
3183     if (!Op.isReg())
3184       return false;
3185     auto Reg = Op.getReg();
3186     if (Reg.isPhysical())
3187       return AArch64::FPR128RegClass.contains(Reg);
3188     const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
3189     return TRC == &AArch64::FPR128RegClass ||
3190            TRC == &AArch64::FPR128_loRegClass;
3191   };
3192   return llvm::any_of(MI.operands(), IsQFPR);
3193 }
3194 
3195 bool AArch64InstrInfo::isFpOrNEON(const MachineInstr &MI) {
3196   auto IsFPR = [&](const MachineOperand &Op) {
3197     if (!Op.isReg())
3198       return false;
3199     auto Reg = Op.getReg();
3200     if (Reg.isPhysical())
3201       return AArch64::FPR128RegClass.contains(Reg) ||
3202              AArch64::FPR64RegClass.contains(Reg) ||
3203              AArch64::FPR32RegClass.contains(Reg) ||
3204              AArch64::FPR16RegClass.contains(Reg) ||
3205              AArch64::FPR8RegClass.contains(Reg);
3206 
3207     const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
3208     return TRC == &AArch64::FPR128RegClass ||
3209            TRC == &AArch64::FPR128_loRegClass ||
3210            TRC == &AArch64::FPR64RegClass ||
3211            TRC == &AArch64::FPR64_loRegClass ||
3212            TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
3213            TRC == &AArch64::FPR8RegClass;
3214   };
3215   return llvm::any_of(MI.operands(), IsFPR);
3216 }
3217 
3218 // Scale the unscaled offsets.  Returns false if the unscaled offset can't be
3219 // scaled.
3220 static bool scaleOffset(unsigned Opc, int64_t &Offset) {
3221   int Scale = AArch64InstrInfo::getMemScale(Opc);
3222 
3223   // If the byte-offset isn't a multiple of the stride, we can't scale this
3224   // offset.
3225   if (Offset % Scale != 0)
3226     return false;
3227 
3228   // Convert the byte-offset used by unscaled into an "element" offset used
3229   // by the scaled pair load/store instructions.
3230   Offset /= Scale;
3231   return true;
3232 }
3233 
3234 static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
3235   if (FirstOpc == SecondOpc)
3236     return true;
3237   // We can also pair sign-ext and zero-ext instructions.
3238   switch (FirstOpc) {
3239   default:
3240     return false;
3241   case AArch64::LDRWui:
3242   case AArch64::LDURWi:
3243     return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
3244   case AArch64::LDRSWui:
3245   case AArch64::LDURSWi:
3246     return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
3247   }
3248   // These instructions can't be paired based on their opcodes.
3249   return false;
3250 }
3251 
3252 static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
3253                             int64_t Offset1, unsigned Opcode1, int FI2,
3254                             int64_t Offset2, unsigned Opcode2) {
3255   // Accesses through fixed stack object frame indices may access a different
3256   // fixed stack slot. Check that the object offsets + offsets match.
3257   if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
3258     int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
3259     int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
3260     assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
3261     // Convert to scaled object offsets.
3262     int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
3263     if (ObjectOffset1 % Scale1 != 0)
3264       return false;
3265     ObjectOffset1 /= Scale1;
3266     int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
3267     if (ObjectOffset2 % Scale2 != 0)
3268       return false;
3269     ObjectOffset2 /= Scale2;
3270     ObjectOffset1 += Offset1;
3271     ObjectOffset2 += Offset2;
3272     return ObjectOffset1 + 1 == ObjectOffset2;
3273   }
3274 
3275   return FI1 == FI2;
3276 }
3277 
3278 /// Detect opportunities for ldp/stp formation.
3279 ///
3280 /// Only called for LdSt for which getMemOperandWithOffset returns true.
3281 bool AArch64InstrInfo::shouldClusterMemOps(
3282     ArrayRef<const MachineOperand *> BaseOps1,
3283     ArrayRef<const MachineOperand *> BaseOps2, unsigned NumLoads,
3284     unsigned NumBytes) const {
3285   assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
3286   const MachineOperand &BaseOp1 = *BaseOps1.front();
3287   const MachineOperand &BaseOp2 = *BaseOps2.front();
3288   const MachineInstr &FirstLdSt = *BaseOp1.getParent();
3289   const MachineInstr &SecondLdSt = *BaseOp2.getParent();
3290   if (BaseOp1.getType() != BaseOp2.getType())
3291     return false;
3292 
3293   assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
3294          "Only base registers and frame indices are supported.");
3295 
3296   // Check for both base regs and base FI.
3297   if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
3298     return false;
3299 
3300   // Only cluster up to a single pair.
3301   if (NumLoads > 2)
3302     return false;
3303 
3304   if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
3305     return false;
3306 
3307   // Can we pair these instructions based on their opcodes?
3308   unsigned FirstOpc = FirstLdSt.getOpcode();
3309   unsigned SecondOpc = SecondLdSt.getOpcode();
3310   if (!canPairLdStOpc(FirstOpc, SecondOpc))
3311     return false;
3312 
3313   // Can't merge volatiles or load/stores that have a hint to avoid pair
3314   // formation, for example.
3315   if (!isCandidateToMergeOrPair(FirstLdSt) ||
3316       !isCandidateToMergeOrPair(SecondLdSt))
3317     return false;
3318 
3319   // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
3320   int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
3321   if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
3322     return false;
3323 
3324   int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
3325   if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
3326     return false;
3327 
3328   // Pairwise instructions have a 7-bit signed offset field.
3329   if (Offset1 > 63 || Offset1 < -64)
3330     return false;
3331 
3332   // The caller should already have ordered First/SecondLdSt by offset.
3333   // Note: except for non-equal frame index bases
3334   if (BaseOp1.isFI()) {
3335     assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
3336            "Caller should have ordered offsets.");
3337 
3338     const MachineFrameInfo &MFI =
3339         FirstLdSt.getParent()->getParent()->getFrameInfo();
3340     return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
3341                            BaseOp2.getIndex(), Offset2, SecondOpc);
3342   }
3343 
3344   assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
3345 
3346   return Offset1 + 1 == Offset2;
3347 }
3348 
3349 static const MachineInstrBuilder &AddSubReg(const MachineInstrBuilder &MIB,
3350                                             unsigned Reg, unsigned SubIdx,
3351                                             unsigned State,
3352                                             const TargetRegisterInfo *TRI) {
3353   if (!SubIdx)
3354     return MIB.addReg(Reg, State);
3355 
3356   if (Register::isPhysicalRegister(Reg))
3357     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
3358   return MIB.addReg(Reg, State, SubIdx);
3359 }
3360 
3361 static bool forwardCopyWillClobberTuple(unsigned DestReg, unsigned SrcReg,
3362                                         unsigned NumRegs) {
3363   // We really want the positive remainder mod 32 here, that happens to be
3364   // easily obtainable with a mask.
3365   return ((DestReg - SrcReg) & 0x1f) < NumRegs;
3366 }
3367 
3368 void AArch64InstrInfo::copyPhysRegTuple(MachineBasicBlock &MBB,
3369                                         MachineBasicBlock::iterator I,
3370                                         const DebugLoc &DL, MCRegister DestReg,
3371                                         MCRegister SrcReg, bool KillSrc,
3372                                         unsigned Opcode,
3373                                         ArrayRef<unsigned> Indices) const {
3374   assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
3375   const TargetRegisterInfo *TRI = &getRegisterInfo();
3376   uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
3377   uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
3378   unsigned NumRegs = Indices.size();
3379 
3380   int SubReg = 0, End = NumRegs, Incr = 1;
3381   if (forwardCopyWillClobberTuple(DestEncoding, SrcEncoding, NumRegs)) {
3382     SubReg = NumRegs - 1;
3383     End = -1;
3384     Incr = -1;
3385   }
3386 
3387   for (; SubReg != End; SubReg += Incr) {
3388     const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
3389     AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
3390     AddSubReg(MIB, SrcReg, Indices[SubReg], 0, TRI);
3391     AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
3392   }
3393 }
3394 
3395 void AArch64InstrInfo::copyGPRRegTuple(MachineBasicBlock &MBB,
3396                                        MachineBasicBlock::iterator I,
3397                                        DebugLoc DL, unsigned DestReg,
3398                                        unsigned SrcReg, bool KillSrc,
3399                                        unsigned Opcode, unsigned ZeroReg,
3400                                        llvm::ArrayRef<unsigned> Indices) const {
3401   const TargetRegisterInfo *TRI = &getRegisterInfo();
3402   unsigned NumRegs = Indices.size();
3403 
3404 #ifndef NDEBUG
3405   uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
3406   uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
3407   assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
3408          "GPR reg sequences should not be able to overlap");
3409 #endif
3410 
3411   for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
3412     const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
3413     AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
3414     MIB.addReg(ZeroReg);
3415     AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
3416     MIB.addImm(0);
3417   }
3418 }
3419 
3420 void AArch64InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
3421                                    MachineBasicBlock::iterator I,
3422                                    const DebugLoc &DL, MCRegister DestReg,
3423                                    MCRegister SrcReg, bool KillSrc) const {
3424   if (AArch64::GPR32spRegClass.contains(DestReg) &&
3425       (AArch64::GPR32spRegClass.contains(SrcReg) || SrcReg == AArch64::WZR)) {
3426     const TargetRegisterInfo *TRI = &getRegisterInfo();
3427 
3428     if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
3429       // If either operand is WSP, expand to ADD #0.
3430       if (Subtarget.hasZeroCycleRegMove()) {
3431         // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
3432         MCRegister DestRegX = TRI->getMatchingSuperReg(
3433             DestReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
3434         MCRegister SrcRegX = TRI->getMatchingSuperReg(
3435             SrcReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
3436         // This instruction is reading and writing X registers.  This may upset
3437         // the register scavenger and machine verifier, so we need to indicate
3438         // that we are reading an undefined value from SrcRegX, but a proper
3439         // value from SrcReg.
3440         BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
3441             .addReg(SrcRegX, RegState::Undef)
3442             .addImm(0)
3443             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
3444             .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
3445       } else {
3446         BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
3447             .addReg(SrcReg, getKillRegState(KillSrc))
3448             .addImm(0)
3449             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
3450       }
3451     } else if (SrcReg == AArch64::WZR && Subtarget.hasZeroCycleZeroingGP()) {
3452       BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
3453           .addImm(0)
3454           .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
3455     } else {
3456       if (Subtarget.hasZeroCycleRegMove()) {
3457         // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
3458         MCRegister DestRegX = TRI->getMatchingSuperReg(
3459             DestReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
3460         MCRegister SrcRegX = TRI->getMatchingSuperReg(
3461             SrcReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
3462         // This instruction is reading and writing X registers.  This may upset
3463         // the register scavenger and machine verifier, so we need to indicate
3464         // that we are reading an undefined value from SrcRegX, but a proper
3465         // value from SrcReg.
3466         BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
3467             .addReg(AArch64::XZR)
3468             .addReg(SrcRegX, RegState::Undef)
3469             .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
3470       } else {
3471         // Otherwise, expand to ORR WZR.
3472         BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
3473             .addReg(AArch64::WZR)
3474             .addReg(SrcReg, getKillRegState(KillSrc));
3475       }
3476     }
3477     return;
3478   }
3479 
3480   // Copy a Predicate register by ORRing with itself.
3481   if (AArch64::PPRRegClass.contains(DestReg) &&
3482       AArch64::PPRRegClass.contains(SrcReg)) {
3483     assert(Subtarget.hasSVE() && "Unexpected SVE register.");
3484     BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
3485       .addReg(SrcReg) // Pg
3486       .addReg(SrcReg)
3487       .addReg(SrcReg, getKillRegState(KillSrc));
3488     return;
3489   }
3490 
3491   // Copy a Z register by ORRing with itself.
3492   if (AArch64::ZPRRegClass.contains(DestReg) &&
3493       AArch64::ZPRRegClass.contains(SrcReg)) {
3494     assert(Subtarget.hasSVE() && "Unexpected SVE register.");
3495     BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
3496       .addReg(SrcReg)
3497       .addReg(SrcReg, getKillRegState(KillSrc));
3498     return;
3499   }
3500 
3501   // Copy a Z register pair by copying the individual sub-registers.
3502   if (AArch64::ZPR2RegClass.contains(DestReg) &&
3503       AArch64::ZPR2RegClass.contains(SrcReg)) {
3504     static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
3505     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
3506                      Indices);
3507     return;
3508   }
3509 
3510   // Copy a Z register triple by copying the individual sub-registers.
3511   if (AArch64::ZPR3RegClass.contains(DestReg) &&
3512       AArch64::ZPR3RegClass.contains(SrcReg)) {
3513     static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
3514                                        AArch64::zsub2};
3515     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
3516                      Indices);
3517     return;
3518   }
3519 
3520   // Copy a Z register quad by copying the individual sub-registers.
3521   if (AArch64::ZPR4RegClass.contains(DestReg) &&
3522       AArch64::ZPR4RegClass.contains(SrcReg)) {
3523     static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
3524                                        AArch64::zsub2, AArch64::zsub3};
3525     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
3526                      Indices);
3527     return;
3528   }
3529 
3530   if (AArch64::GPR64spRegClass.contains(DestReg) &&
3531       (AArch64::GPR64spRegClass.contains(SrcReg) || SrcReg == AArch64::XZR)) {
3532     if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
3533       // If either operand is SP, expand to ADD #0.
3534       BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
3535           .addReg(SrcReg, getKillRegState(KillSrc))
3536           .addImm(0)
3537           .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
3538     } else if (SrcReg == AArch64::XZR && Subtarget.hasZeroCycleZeroingGP()) {
3539       BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
3540           .addImm(0)
3541           .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
3542     } else {
3543       // Otherwise, expand to ORR XZR.
3544       BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
3545           .addReg(AArch64::XZR)
3546           .addReg(SrcReg, getKillRegState(KillSrc));
3547     }
3548     return;
3549   }
3550 
3551   // Copy a DDDD register quad by copying the individual sub-registers.
3552   if (AArch64::DDDDRegClass.contains(DestReg) &&
3553       AArch64::DDDDRegClass.contains(SrcReg)) {
3554     static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
3555                                        AArch64::dsub2, AArch64::dsub3};
3556     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
3557                      Indices);
3558     return;
3559   }
3560 
3561   // Copy a DDD register triple by copying the individual sub-registers.
3562   if (AArch64::DDDRegClass.contains(DestReg) &&
3563       AArch64::DDDRegClass.contains(SrcReg)) {
3564     static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
3565                                        AArch64::dsub2};
3566     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
3567                      Indices);
3568     return;
3569   }
3570 
3571   // Copy a DD register pair by copying the individual sub-registers.
3572   if (AArch64::DDRegClass.contains(DestReg) &&
3573       AArch64::DDRegClass.contains(SrcReg)) {
3574     static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
3575     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
3576                      Indices);
3577     return;
3578   }
3579 
3580   // Copy a QQQQ register quad by copying the individual sub-registers.
3581   if (AArch64::QQQQRegClass.contains(DestReg) &&
3582       AArch64::QQQQRegClass.contains(SrcReg)) {
3583     static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
3584                                        AArch64::qsub2, AArch64::qsub3};
3585     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
3586                      Indices);
3587     return;
3588   }
3589 
3590   // Copy a QQQ register triple by copying the individual sub-registers.
3591   if (AArch64::QQQRegClass.contains(DestReg) &&
3592       AArch64::QQQRegClass.contains(SrcReg)) {
3593     static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
3594                                        AArch64::qsub2};
3595     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
3596                      Indices);
3597     return;
3598   }
3599 
3600   // Copy a QQ register pair by copying the individual sub-registers.
3601   if (AArch64::QQRegClass.contains(DestReg) &&
3602       AArch64::QQRegClass.contains(SrcReg)) {
3603     static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
3604     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
3605                      Indices);
3606     return;
3607   }
3608 
3609   if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
3610       AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
3611     static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
3612     copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
3613                     AArch64::XZR, Indices);
3614     return;
3615   }
3616 
3617   if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
3618       AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
3619     static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
3620     copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
3621                     AArch64::WZR, Indices);
3622     return;
3623   }
3624 
3625   if (AArch64::FPR128RegClass.contains(DestReg) &&
3626       AArch64::FPR128RegClass.contains(SrcReg)) {
3627     if (Subtarget.hasNEON()) {
3628       BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
3629           .addReg(SrcReg)
3630           .addReg(SrcReg, getKillRegState(KillSrc));
3631     } else {
3632       BuildMI(MBB, I, DL, get(AArch64::STRQpre))
3633           .addReg(AArch64::SP, RegState::Define)
3634           .addReg(SrcReg, getKillRegState(KillSrc))
3635           .addReg(AArch64::SP)
3636           .addImm(-16);
3637       BuildMI(MBB, I, DL, get(AArch64::LDRQpre))
3638           .addReg(AArch64::SP, RegState::Define)
3639           .addReg(DestReg, RegState::Define)
3640           .addReg(AArch64::SP)
3641           .addImm(16);
3642     }
3643     return;
3644   }
3645 
3646   if (AArch64::FPR64RegClass.contains(DestReg) &&
3647       AArch64::FPR64RegClass.contains(SrcReg)) {
3648     BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
3649         .addReg(SrcReg, getKillRegState(KillSrc));
3650     return;
3651   }
3652 
3653   if (AArch64::FPR32RegClass.contains(DestReg) &&
3654       AArch64::FPR32RegClass.contains(SrcReg)) {
3655     BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
3656         .addReg(SrcReg, getKillRegState(KillSrc));
3657     return;
3658   }
3659 
3660   if (AArch64::FPR16RegClass.contains(DestReg) &&
3661       AArch64::FPR16RegClass.contains(SrcReg)) {
3662     DestReg =
3663         RI.getMatchingSuperReg(DestReg, AArch64::hsub, &AArch64::FPR32RegClass);
3664     SrcReg =
3665         RI.getMatchingSuperReg(SrcReg, AArch64::hsub, &AArch64::FPR32RegClass);
3666     BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
3667         .addReg(SrcReg, getKillRegState(KillSrc));
3668     return;
3669   }
3670 
3671   if (AArch64::FPR8RegClass.contains(DestReg) &&
3672       AArch64::FPR8RegClass.contains(SrcReg)) {
3673     DestReg =
3674         RI.getMatchingSuperReg(DestReg, AArch64::bsub, &AArch64::FPR32RegClass);
3675     SrcReg =
3676         RI.getMatchingSuperReg(SrcReg, AArch64::bsub, &AArch64::FPR32RegClass);
3677     BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
3678         .addReg(SrcReg, getKillRegState(KillSrc));
3679     return;
3680   }
3681 
3682   // Copies between GPR64 and FPR64.
3683   if (AArch64::FPR64RegClass.contains(DestReg) &&
3684       AArch64::GPR64RegClass.contains(SrcReg)) {
3685     BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
3686         .addReg(SrcReg, getKillRegState(KillSrc));
3687     return;
3688   }
3689   if (AArch64::GPR64RegClass.contains(DestReg) &&
3690       AArch64::FPR64RegClass.contains(SrcReg)) {
3691     BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
3692         .addReg(SrcReg, getKillRegState(KillSrc));
3693     return;
3694   }
3695   // Copies between GPR32 and FPR32.
3696   if (AArch64::FPR32RegClass.contains(DestReg) &&
3697       AArch64::GPR32RegClass.contains(SrcReg)) {
3698     BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
3699         .addReg(SrcReg, getKillRegState(KillSrc));
3700     return;
3701   }
3702   if (AArch64::GPR32RegClass.contains(DestReg) &&
3703       AArch64::FPR32RegClass.contains(SrcReg)) {
3704     BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
3705         .addReg(SrcReg, getKillRegState(KillSrc));
3706     return;
3707   }
3708 
3709   if (DestReg == AArch64::NZCV) {
3710     assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
3711     BuildMI(MBB, I, DL, get(AArch64::MSR))
3712         .addImm(AArch64SysReg::NZCV)
3713         .addReg(SrcReg, getKillRegState(KillSrc))
3714         .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
3715     return;
3716   }
3717 
3718   if (SrcReg == AArch64::NZCV) {
3719     assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
3720     BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
3721         .addImm(AArch64SysReg::NZCV)
3722         .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
3723     return;
3724   }
3725 
3726 #ifndef NDEBUG
3727   const TargetRegisterInfo &TRI = getRegisterInfo();
3728   errs() << TRI.getRegAsmName(DestReg) << " = COPY "
3729          << TRI.getRegAsmName(SrcReg) << "\n";
3730 #endif
3731   llvm_unreachable("unimplemented reg-to-reg copy");
3732 }
3733 
3734 static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI,
3735                                     MachineBasicBlock &MBB,
3736                                     MachineBasicBlock::iterator InsertBefore,
3737                                     const MCInstrDesc &MCID,
3738                                     Register SrcReg, bool IsKill,
3739                                     unsigned SubIdx0, unsigned SubIdx1, int FI,
3740                                     MachineMemOperand *MMO) {
3741   Register SrcReg0 = SrcReg;
3742   Register SrcReg1 = SrcReg;
3743   if (Register::isPhysicalRegister(SrcReg)) {
3744     SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
3745     SubIdx0 = 0;
3746     SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
3747     SubIdx1 = 0;
3748   }
3749   BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
3750       .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
3751       .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
3752       .addFrameIndex(FI)
3753       .addImm(0)
3754       .addMemOperand(MMO);
3755 }
3756 
3757 void AArch64InstrInfo::storeRegToStackSlot(
3758     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
3759     bool isKill, int FI, const TargetRegisterClass *RC,
3760     const TargetRegisterInfo *TRI) const {
3761   MachineFunction &MF = *MBB.getParent();
3762   MachineFrameInfo &MFI = MF.getFrameInfo();
3763 
3764   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
3765   MachineMemOperand *MMO =
3766       MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
3767                               MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
3768   unsigned Opc = 0;
3769   bool Offset = true;
3770   unsigned StackID = TargetStackID::Default;
3771   switch (TRI->getSpillSize(*RC)) {
3772   case 1:
3773     if (AArch64::FPR8RegClass.hasSubClassEq(RC))
3774       Opc = AArch64::STRBui;
3775     break;
3776   case 2:
3777     if (AArch64::FPR16RegClass.hasSubClassEq(RC))
3778       Opc = AArch64::STRHui;
3779     else if (AArch64::PPRRegClass.hasSubClassEq(RC)) {
3780       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3781       Opc = AArch64::STR_PXI;
3782       StackID = TargetStackID::ScalableVector;
3783     }
3784     break;
3785   case 4:
3786     if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
3787       Opc = AArch64::STRWui;
3788       if (Register::isVirtualRegister(SrcReg))
3789         MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
3790       else
3791         assert(SrcReg != AArch64::WSP);
3792     } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
3793       Opc = AArch64::STRSui;
3794     break;
3795   case 8:
3796     if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
3797       Opc = AArch64::STRXui;
3798       if (Register::isVirtualRegister(SrcReg))
3799         MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
3800       else
3801         assert(SrcReg != AArch64::SP);
3802     } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
3803       Opc = AArch64::STRDui;
3804     } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
3805       storeRegPairToStackSlot(getRegisterInfo(), MBB, MBBI,
3806                               get(AArch64::STPWi), SrcReg, isKill,
3807                               AArch64::sube32, AArch64::subo32, FI, MMO);
3808       return;
3809     }
3810     break;
3811   case 16:
3812     if (AArch64::FPR128RegClass.hasSubClassEq(RC))
3813       Opc = AArch64::STRQui;
3814     else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
3815       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3816       Opc = AArch64::ST1Twov1d;
3817       Offset = false;
3818     } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
3819       storeRegPairToStackSlot(getRegisterInfo(), MBB, MBBI,
3820                               get(AArch64::STPXi), SrcReg, isKill,
3821                               AArch64::sube64, AArch64::subo64, FI, MMO);
3822       return;
3823     } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
3824       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3825       Opc = AArch64::STR_ZXI;
3826       StackID = TargetStackID::ScalableVector;
3827     }
3828     break;
3829   case 24:
3830     if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
3831       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3832       Opc = AArch64::ST1Threev1d;
3833       Offset = false;
3834     }
3835     break;
3836   case 32:
3837     if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
3838       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3839       Opc = AArch64::ST1Fourv1d;
3840       Offset = false;
3841     } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
3842       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3843       Opc = AArch64::ST1Twov2d;
3844       Offset = false;
3845     } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
3846       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3847       Opc = AArch64::STR_ZZXI;
3848       StackID = TargetStackID::ScalableVector;
3849     }
3850     break;
3851   case 48:
3852     if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
3853       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3854       Opc = AArch64::ST1Threev2d;
3855       Offset = false;
3856     } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
3857       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3858       Opc = AArch64::STR_ZZZXI;
3859       StackID = TargetStackID::ScalableVector;
3860     }
3861     break;
3862   case 64:
3863     if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
3864       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3865       Opc = AArch64::ST1Fourv2d;
3866       Offset = false;
3867     } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
3868       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3869       Opc = AArch64::STR_ZZZZXI;
3870       StackID = TargetStackID::ScalableVector;
3871     }
3872     break;
3873   }
3874   assert(Opc && "Unknown register class");
3875   MFI.setStackID(FI, StackID);
3876 
3877   const MachineInstrBuilder MI = BuildMI(MBB, MBBI, DebugLoc(), get(Opc))
3878                                      .addReg(SrcReg, getKillRegState(isKill))
3879                                      .addFrameIndex(FI);
3880 
3881   if (Offset)
3882     MI.addImm(0);
3883   MI.addMemOperand(MMO);
3884 }
3885 
3886 static void loadRegPairFromStackSlot(const TargetRegisterInfo &TRI,
3887                                      MachineBasicBlock &MBB,
3888                                      MachineBasicBlock::iterator InsertBefore,
3889                                      const MCInstrDesc &MCID,
3890                                      Register DestReg, unsigned SubIdx0,
3891                                      unsigned SubIdx1, int FI,
3892                                      MachineMemOperand *MMO) {
3893   Register DestReg0 = DestReg;
3894   Register DestReg1 = DestReg;
3895   bool IsUndef = true;
3896   if (Register::isPhysicalRegister(DestReg)) {
3897     DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
3898     SubIdx0 = 0;
3899     DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
3900     SubIdx1 = 0;
3901     IsUndef = false;
3902   }
3903   BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
3904       .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
3905       .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
3906       .addFrameIndex(FI)
3907       .addImm(0)
3908       .addMemOperand(MMO);
3909 }
3910 
3911 void AArch64InstrInfo::loadRegFromStackSlot(
3912     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg,
3913     int FI, const TargetRegisterClass *RC,
3914     const TargetRegisterInfo *TRI) const {
3915   MachineFunction &MF = *MBB.getParent();
3916   MachineFrameInfo &MFI = MF.getFrameInfo();
3917   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
3918   MachineMemOperand *MMO =
3919       MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
3920                               MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
3921 
3922   unsigned Opc = 0;
3923   bool Offset = true;
3924   unsigned StackID = TargetStackID::Default;
3925   switch (TRI->getSpillSize(*RC)) {
3926   case 1:
3927     if (AArch64::FPR8RegClass.hasSubClassEq(RC))
3928       Opc = AArch64::LDRBui;
3929     break;
3930   case 2:
3931     if (AArch64::FPR16RegClass.hasSubClassEq(RC))
3932       Opc = AArch64::LDRHui;
3933     else if (AArch64::PPRRegClass.hasSubClassEq(RC)) {
3934       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
3935       Opc = AArch64::LDR_PXI;
3936       StackID = TargetStackID::ScalableVector;
3937     }
3938     break;
3939   case 4:
3940     if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
3941       Opc = AArch64::LDRWui;
3942       if (Register::isVirtualRegister(DestReg))
3943         MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
3944       else
3945         assert(DestReg != AArch64::WSP);
3946     } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
3947       Opc = AArch64::LDRSui;
3948     break;
3949   case 8:
3950     if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
3951       Opc = AArch64::LDRXui;
3952       if (Register::isVirtualRegister(DestReg))
3953         MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
3954       else
3955         assert(DestReg != AArch64::SP);
3956     } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
3957       Opc = AArch64::LDRDui;
3958     } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
3959       loadRegPairFromStackSlot(getRegisterInfo(), MBB, MBBI,
3960                                get(AArch64::LDPWi), DestReg, AArch64::sube32,
3961                                AArch64::subo32, FI, MMO);
3962       return;
3963     }
3964     break;
3965   case 16:
3966     if (AArch64::FPR128RegClass.hasSubClassEq(RC))
3967       Opc = AArch64::LDRQui;
3968     else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
3969       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3970       Opc = AArch64::LD1Twov1d;
3971       Offset = false;
3972     } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
3973       loadRegPairFromStackSlot(getRegisterInfo(), MBB, MBBI,
3974                                get(AArch64::LDPXi), DestReg, AArch64::sube64,
3975                                AArch64::subo64, FI, MMO);
3976       return;
3977     } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
3978       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
3979       Opc = AArch64::LDR_ZXI;
3980       StackID = TargetStackID::ScalableVector;
3981     }
3982     break;
3983   case 24:
3984     if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
3985       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3986       Opc = AArch64::LD1Threev1d;
3987       Offset = false;
3988     }
3989     break;
3990   case 32:
3991     if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
3992       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3993       Opc = AArch64::LD1Fourv1d;
3994       Offset = false;
3995     } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
3996       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3997       Opc = AArch64::LD1Twov2d;
3998       Offset = false;
3999     } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
4000       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
4001       Opc = AArch64::LDR_ZZXI;
4002       StackID = TargetStackID::ScalableVector;
4003     }
4004     break;
4005   case 48:
4006     if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
4007       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
4008       Opc = AArch64::LD1Threev2d;
4009       Offset = false;
4010     } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
4011       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
4012       Opc = AArch64::LDR_ZZZXI;
4013       StackID = TargetStackID::ScalableVector;
4014     }
4015     break;
4016   case 64:
4017     if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
4018       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
4019       Opc = AArch64::LD1Fourv2d;
4020       Offset = false;
4021     } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
4022       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
4023       Opc = AArch64::LDR_ZZZZXI;
4024       StackID = TargetStackID::ScalableVector;
4025     }
4026     break;
4027   }
4028 
4029   assert(Opc && "Unknown register class");
4030   MFI.setStackID(FI, StackID);
4031 
4032   const MachineInstrBuilder MI = BuildMI(MBB, MBBI, DebugLoc(), get(Opc))
4033                                      .addReg(DestReg, getDefRegState(true))
4034                                      .addFrameIndex(FI);
4035   if (Offset)
4036     MI.addImm(0);
4037   MI.addMemOperand(MMO);
4038 }
4039 
4040 bool llvm::isNZCVTouchedInInstructionRange(const MachineInstr &DefMI,
4041                                            const MachineInstr &UseMI,
4042                                            const TargetRegisterInfo *TRI) {
4043   return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
4044                                          UseMI.getIterator()),
4045                 [TRI](const MachineInstr &I) {
4046                   return I.modifiesRegister(AArch64::NZCV, TRI) ||
4047                          I.readsRegister(AArch64::NZCV, TRI);
4048                 });
4049 }
4050 
4051 void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
4052     const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
4053   // The smallest scalable element supported by scaled SVE addressing
4054   // modes are predicates, which are 2 scalable bytes in size. So the scalable
4055   // byte offset must always be a multiple of 2.
4056   assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
4057 
4058   // VGSized offsets are divided by '2', because the VG register is the
4059   // the number of 64bit granules as opposed to 128bit vector chunks,
4060   // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
4061   // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
4062   // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
4063   ByteSized = Offset.getFixed();
4064   VGSized = Offset.getScalable() / 2;
4065 }
4066 
4067 /// Returns the offset in parts to which this frame offset can be
4068 /// decomposed for the purpose of describing a frame offset.
4069 /// For non-scalable offsets this is simply its byte size.
4070 void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
4071     const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
4072     int64_t &NumDataVectors) {
4073   // The smallest scalable element supported by scaled SVE addressing
4074   // modes are predicates, which are 2 scalable bytes in size. So the scalable
4075   // byte offset must always be a multiple of 2.
4076   assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
4077 
4078   NumBytes = Offset.getFixed();
4079   NumDataVectors = 0;
4080   NumPredicateVectors = Offset.getScalable() / 2;
4081   // This method is used to get the offsets to adjust the frame offset.
4082   // If the function requires ADDPL to be used and needs more than two ADDPL
4083   // instructions, part of the offset is folded into NumDataVectors so that it
4084   // uses ADDVL for part of it, reducing the number of ADDPL instructions.
4085   if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
4086       NumPredicateVectors > 62) {
4087     NumDataVectors = NumPredicateVectors / 8;
4088     NumPredicateVectors -= NumDataVectors * 8;
4089   }
4090 }
4091 
4092 // Helper function to emit a frame offset adjustment from a given
4093 // pointer (SrcReg), stored into DestReg. This function is explicit
4094 // in that it requires the opcode.
4095 static void emitFrameOffsetAdj(MachineBasicBlock &MBB,
4096                                MachineBasicBlock::iterator MBBI,
4097                                const DebugLoc &DL, unsigned DestReg,
4098                                unsigned SrcReg, int64_t Offset, unsigned Opc,
4099                                const TargetInstrInfo *TII,
4100                                MachineInstr::MIFlag Flag, bool NeedsWinCFI,
4101                                bool *HasWinCFI) {
4102   int Sign = 1;
4103   unsigned MaxEncoding, ShiftSize;
4104   switch (Opc) {
4105   case AArch64::ADDXri:
4106   case AArch64::ADDSXri:
4107   case AArch64::SUBXri:
4108   case AArch64::SUBSXri:
4109     MaxEncoding = 0xfff;
4110     ShiftSize = 12;
4111     break;
4112   case AArch64::ADDVL_XXI:
4113   case AArch64::ADDPL_XXI:
4114     MaxEncoding = 31;
4115     ShiftSize = 0;
4116     if (Offset < 0) {
4117       MaxEncoding = 32;
4118       Sign = -1;
4119       Offset = -Offset;
4120     }
4121     break;
4122   default:
4123     llvm_unreachable("Unsupported opcode");
4124   }
4125 
4126   // FIXME: If the offset won't fit in 24-bits, compute the offset into a
4127   // scratch register.  If DestReg is a virtual register, use it as the
4128   // scratch register; otherwise, create a new virtual register (to be
4129   // replaced by the scavenger at the end of PEI).  That case can be optimized
4130   // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
4131   // register can be loaded with offset%8 and the add/sub can use an extending
4132   // instruction with LSL#3.
4133   // Currently the function handles any offsets but generates a poor sequence
4134   // of code.
4135   //  assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
4136 
4137   const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
4138   Register TmpReg = DestReg;
4139   if (TmpReg == AArch64::XZR)
4140     TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
4141         &AArch64::GPR64RegClass);
4142   do {
4143     uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
4144     unsigned LocalShiftSize = 0;
4145     if (ThisVal > MaxEncoding) {
4146       ThisVal = ThisVal >> ShiftSize;
4147       LocalShiftSize = ShiftSize;
4148     }
4149     assert((ThisVal >> ShiftSize) <= MaxEncoding &&
4150            "Encoding cannot handle value that big");
4151 
4152     Offset -= ThisVal << LocalShiftSize;
4153     if (Offset == 0)
4154       TmpReg = DestReg;
4155     auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
4156                    .addReg(SrcReg)
4157                    .addImm(Sign * (int)ThisVal);
4158     if (ShiftSize)
4159       MBI = MBI.addImm(
4160           AArch64_AM::getShifterImm(AArch64_AM::LSL, LocalShiftSize));
4161     MBI = MBI.setMIFlag(Flag);
4162 
4163     if (NeedsWinCFI) {
4164       assert(Sign == 1 && "SEH directives should always have a positive sign");
4165       int Imm = (int)(ThisVal << LocalShiftSize);
4166       if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
4167           (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
4168         if (HasWinCFI)
4169           *HasWinCFI = true;
4170         if (Imm == 0)
4171           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
4172         else
4173           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
4174               .addImm(Imm)
4175               .setMIFlag(Flag);
4176         assert(Offset == 0 && "Expected remaining offset to be zero to "
4177                               "emit a single SEH directive");
4178       } else if (DestReg == AArch64::SP) {
4179         if (HasWinCFI)
4180           *HasWinCFI = true;
4181         assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
4182         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
4183             .addImm(Imm)
4184             .setMIFlag(Flag);
4185       }
4186       if (HasWinCFI)
4187         *HasWinCFI = true;
4188     }
4189 
4190     SrcReg = TmpReg;
4191   } while (Offset);
4192 }
4193 
4194 void llvm::emitFrameOffset(MachineBasicBlock &MBB,
4195                            MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
4196                            unsigned DestReg, unsigned SrcReg,
4197                            StackOffset Offset, const TargetInstrInfo *TII,
4198                            MachineInstr::MIFlag Flag, bool SetNZCV,
4199                            bool NeedsWinCFI, bool *HasWinCFI) {
4200   int64_t Bytes, NumPredicateVectors, NumDataVectors;
4201   AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
4202       Offset, Bytes, NumPredicateVectors, NumDataVectors);
4203 
4204   // First emit non-scalable frame offsets, or a simple 'mov'.
4205   if (Bytes || (!Offset && SrcReg != DestReg)) {
4206     assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
4207            "SP increment/decrement not 8-byte aligned");
4208     unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
4209     if (Bytes < 0) {
4210       Bytes = -Bytes;
4211       Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
4212     }
4213     emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
4214                        NeedsWinCFI, HasWinCFI);
4215     SrcReg = DestReg;
4216   }
4217 
4218   assert(!(SetNZCV && (NumPredicateVectors || NumDataVectors)) &&
4219          "SetNZCV not supported with SVE vectors");
4220   assert(!(NeedsWinCFI && (NumPredicateVectors || NumDataVectors)) &&
4221          "WinCFI not supported with SVE vectors");
4222 
4223   if (NumDataVectors) {
4224     emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
4225                        AArch64::ADDVL_XXI, TII, Flag, NeedsWinCFI, nullptr);
4226     SrcReg = DestReg;
4227   }
4228 
4229   if (NumPredicateVectors) {
4230     assert(DestReg != AArch64::SP && "Unaligned access to SP");
4231     emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
4232                        AArch64::ADDPL_XXI, TII, Flag, NeedsWinCFI, nullptr);
4233   }
4234 }
4235 
4236 MachineInstr *AArch64InstrInfo::foldMemoryOperandImpl(
4237     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
4238     MachineBasicBlock::iterator InsertPt, int FrameIndex,
4239     LiveIntervals *LIS, VirtRegMap *VRM) const {
4240   // This is a bit of a hack. Consider this instruction:
4241   //
4242   //   %0 = COPY %sp; GPR64all:%0
4243   //
4244   // We explicitly chose GPR64all for the virtual register so such a copy might
4245   // be eliminated by RegisterCoalescer. However, that may not be possible, and
4246   // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
4247   // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
4248   //
4249   // To prevent that, we are going to constrain the %0 register class here.
4250   //
4251   // <rdar://problem/11522048>
4252   //
4253   if (MI.isFullCopy()) {
4254     Register DstReg = MI.getOperand(0).getReg();
4255     Register SrcReg = MI.getOperand(1).getReg();
4256     if (SrcReg == AArch64::SP && Register::isVirtualRegister(DstReg)) {
4257       MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
4258       return nullptr;
4259     }
4260     if (DstReg == AArch64::SP && Register::isVirtualRegister(SrcReg)) {
4261       MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
4262       return nullptr;
4263     }
4264   }
4265 
4266   // Handle the case where a copy is being spilled or filled but the source
4267   // and destination register class don't match.  For example:
4268   //
4269   //   %0 = COPY %xzr; GPR64common:%0
4270   //
4271   // In this case we can still safely fold away the COPY and generate the
4272   // following spill code:
4273   //
4274   //   STRXui %xzr, %stack.0
4275   //
4276   // This also eliminates spilled cross register class COPYs (e.g. between x and
4277   // d regs) of the same size.  For example:
4278   //
4279   //   %0 = COPY %1; GPR64:%0, FPR64:%1
4280   //
4281   // will be filled as
4282   //
4283   //   LDRDui %0, fi<#0>
4284   //
4285   // instead of
4286   //
4287   //   LDRXui %Temp, fi<#0>
4288   //   %0 = FMOV %Temp
4289   //
4290   if (MI.isCopy() && Ops.size() == 1 &&
4291       // Make sure we're only folding the explicit COPY defs/uses.
4292       (Ops[0] == 0 || Ops[0] == 1)) {
4293     bool IsSpill = Ops[0] == 0;
4294     bool IsFill = !IsSpill;
4295     const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
4296     const MachineRegisterInfo &MRI = MF.getRegInfo();
4297     MachineBasicBlock &MBB = *MI.getParent();
4298     const MachineOperand &DstMO = MI.getOperand(0);
4299     const MachineOperand &SrcMO = MI.getOperand(1);
4300     Register DstReg = DstMO.getReg();
4301     Register SrcReg = SrcMO.getReg();
4302     // This is slightly expensive to compute for physical regs since
4303     // getMinimalPhysRegClass is slow.
4304     auto getRegClass = [&](unsigned Reg) {
4305       return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
4306                                               : TRI.getMinimalPhysRegClass(Reg);
4307     };
4308 
4309     if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
4310       assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
4311                  TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
4312              "Mismatched register size in non subreg COPY");
4313       if (IsSpill)
4314         storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
4315                             getRegClass(SrcReg), &TRI);
4316       else
4317         loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
4318                              getRegClass(DstReg), &TRI);
4319       return &*--InsertPt;
4320     }
4321 
4322     // Handle cases like spilling def of:
4323     //
4324     //   %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
4325     //
4326     // where the physical register source can be widened and stored to the full
4327     // virtual reg destination stack slot, in this case producing:
4328     //
4329     //   STRXui %xzr, %stack.0
4330     //
4331     if (IsSpill && DstMO.isUndef() && Register::isPhysicalRegister(SrcReg)) {
4332       assert(SrcMO.getSubReg() == 0 &&
4333              "Unexpected subreg on physical register");
4334       const TargetRegisterClass *SpillRC;
4335       unsigned SpillSubreg;
4336       switch (DstMO.getSubReg()) {
4337       default:
4338         SpillRC = nullptr;
4339         break;
4340       case AArch64::sub_32:
4341       case AArch64::ssub:
4342         if (AArch64::GPR32RegClass.contains(SrcReg)) {
4343           SpillRC = &AArch64::GPR64RegClass;
4344           SpillSubreg = AArch64::sub_32;
4345         } else if (AArch64::FPR32RegClass.contains(SrcReg)) {
4346           SpillRC = &AArch64::FPR64RegClass;
4347           SpillSubreg = AArch64::ssub;
4348         } else
4349           SpillRC = nullptr;
4350         break;
4351       case AArch64::dsub:
4352         if (AArch64::FPR64RegClass.contains(SrcReg)) {
4353           SpillRC = &AArch64::FPR128RegClass;
4354           SpillSubreg = AArch64::dsub;
4355         } else
4356           SpillRC = nullptr;
4357         break;
4358       }
4359 
4360       if (SpillRC)
4361         if (unsigned WidenedSrcReg =
4362                 TRI.getMatchingSuperReg(SrcReg, SpillSubreg, SpillRC)) {
4363           storeRegToStackSlot(MBB, InsertPt, WidenedSrcReg, SrcMO.isKill(),
4364                               FrameIndex, SpillRC, &TRI);
4365           return &*--InsertPt;
4366         }
4367     }
4368 
4369     // Handle cases like filling use of:
4370     //
4371     //   %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
4372     //
4373     // where we can load the full virtual reg source stack slot, into the subreg
4374     // destination, in this case producing:
4375     //
4376     //   LDRWui %0:sub_32<def,read-undef>, %stack.0
4377     //
4378     if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
4379       const TargetRegisterClass *FillRC;
4380       switch (DstMO.getSubReg()) {
4381       default:
4382         FillRC = nullptr;
4383         break;
4384       case AArch64::sub_32:
4385         FillRC = &AArch64::GPR32RegClass;
4386         break;
4387       case AArch64::ssub:
4388         FillRC = &AArch64::FPR32RegClass;
4389         break;
4390       case AArch64::dsub:
4391         FillRC = &AArch64::FPR64RegClass;
4392         break;
4393       }
4394 
4395       if (FillRC) {
4396         assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
4397                    TRI.getRegSizeInBits(*FillRC) &&
4398                "Mismatched regclass size on folded subreg COPY");
4399         loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC, &TRI);
4400         MachineInstr &LoadMI = *--InsertPt;
4401         MachineOperand &LoadDst = LoadMI.getOperand(0);
4402         assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
4403         LoadDst.setSubReg(DstMO.getSubReg());
4404         LoadDst.setIsUndef();
4405         return &LoadMI;
4406       }
4407     }
4408   }
4409 
4410   // Cannot fold.
4411   return nullptr;
4412 }
4413 
4414 int llvm::isAArch64FrameOffsetLegal(const MachineInstr &MI,
4415                                     StackOffset &SOffset,
4416                                     bool *OutUseUnscaledOp,
4417                                     unsigned *OutUnscaledOp,
4418                                     int64_t *EmittableOffset) {
4419   // Set output values in case of early exit.
4420   if (EmittableOffset)
4421     *EmittableOffset = 0;
4422   if (OutUseUnscaledOp)
4423     *OutUseUnscaledOp = false;
4424   if (OutUnscaledOp)
4425     *OutUnscaledOp = 0;
4426 
4427   // Exit early for structured vector spills/fills as they can't take an
4428   // immediate offset.
4429   switch (MI.getOpcode()) {
4430   default:
4431     break;
4432   case AArch64::LD1Twov2d:
4433   case AArch64::LD1Threev2d:
4434   case AArch64::LD1Fourv2d:
4435   case AArch64::LD1Twov1d:
4436   case AArch64::LD1Threev1d:
4437   case AArch64::LD1Fourv1d:
4438   case AArch64::ST1Twov2d:
4439   case AArch64::ST1Threev2d:
4440   case AArch64::ST1Fourv2d:
4441   case AArch64::ST1Twov1d:
4442   case AArch64::ST1Threev1d:
4443   case AArch64::ST1Fourv1d:
4444   case AArch64::ST1i8:
4445   case AArch64::ST1i16:
4446   case AArch64::ST1i32:
4447   case AArch64::ST1i64:
4448   case AArch64::IRG:
4449   case AArch64::IRGstack:
4450   case AArch64::STGloop:
4451   case AArch64::STZGloop:
4452     return AArch64FrameOffsetCannotUpdate;
4453   }
4454 
4455   // Get the min/max offset and the scale.
4456   TypeSize ScaleValue(0U, false);
4457   unsigned Width;
4458   int64_t MinOff, MaxOff;
4459   if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
4460                                       MaxOff))
4461     llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
4462 
4463   // Construct the complete offset.
4464   bool IsMulVL = ScaleValue.isScalable();
4465   unsigned Scale = ScaleValue.getKnownMinSize();
4466   int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
4467 
4468   const MachineOperand &ImmOpnd =
4469       MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
4470   Offset += ImmOpnd.getImm() * Scale;
4471 
4472   // If the offset doesn't match the scale, we rewrite the instruction to
4473   // use the unscaled instruction instead. Likewise, if we have a negative
4474   // offset and there is an unscaled op to use.
4475   Optional<unsigned> UnscaledOp =
4476       AArch64InstrInfo::getUnscaledLdSt(MI.getOpcode());
4477   bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
4478   if (useUnscaledOp &&
4479       !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
4480                                       MaxOff))
4481     llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
4482 
4483   Scale = ScaleValue.getKnownMinSize();
4484   assert(IsMulVL == ScaleValue.isScalable() &&
4485          "Unscaled opcode has different value for scalable");
4486 
4487   int64_t Remainder = Offset % Scale;
4488   assert(!(Remainder && useUnscaledOp) &&
4489          "Cannot have remainder when using unscaled op");
4490 
4491   assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
4492   int64_t NewOffset = Offset / Scale;
4493   if (MinOff <= NewOffset && NewOffset <= MaxOff)
4494     Offset = Remainder;
4495   else {
4496     NewOffset = NewOffset < 0 ? MinOff : MaxOff;
4497     Offset = Offset - NewOffset * Scale + Remainder;
4498   }
4499 
4500   if (EmittableOffset)
4501     *EmittableOffset = NewOffset;
4502   if (OutUseUnscaledOp)
4503     *OutUseUnscaledOp = useUnscaledOp;
4504   if (OutUnscaledOp && UnscaledOp)
4505     *OutUnscaledOp = *UnscaledOp;
4506 
4507   if (IsMulVL)
4508     SOffset = StackOffset::get(SOffset.getFixed(), Offset);
4509   else
4510     SOffset = StackOffset::get(Offset, SOffset.getScalable());
4511   return AArch64FrameOffsetCanUpdate |
4512          (SOffset ? 0 : AArch64FrameOffsetIsLegal);
4513 }
4514 
4515 bool llvm::rewriteAArch64FrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
4516                                     unsigned FrameReg, StackOffset &Offset,
4517                                     const AArch64InstrInfo *TII) {
4518   unsigned Opcode = MI.getOpcode();
4519   unsigned ImmIdx = FrameRegIdx + 1;
4520 
4521   if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
4522     Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
4523     emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
4524                     MI.getOperand(0).getReg(), FrameReg, Offset, TII,
4525                     MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
4526     MI.eraseFromParent();
4527     Offset = StackOffset();
4528     return true;
4529   }
4530 
4531   int64_t NewOffset;
4532   unsigned UnscaledOp;
4533   bool UseUnscaledOp;
4534   int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
4535                                          &UnscaledOp, &NewOffset);
4536   if (Status & AArch64FrameOffsetCanUpdate) {
4537     if (Status & AArch64FrameOffsetIsLegal)
4538       // Replace the FrameIndex with FrameReg.
4539       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
4540     if (UseUnscaledOp)
4541       MI.setDesc(TII->get(UnscaledOp));
4542 
4543     MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
4544     return !Offset;
4545   }
4546 
4547   return false;
4548 }
4549 
4550 MCInst AArch64InstrInfo::getNop() const {
4551   return MCInstBuilder(AArch64::HINT).addImm(0);
4552 }
4553 
4554 // AArch64 supports MachineCombiner.
4555 bool AArch64InstrInfo::useMachineCombiner() const { return true; }
4556 
4557 // True when Opc sets flag
4558 static bool isCombineInstrSettingFlag(unsigned Opc) {
4559   switch (Opc) {
4560   case AArch64::ADDSWrr:
4561   case AArch64::ADDSWri:
4562   case AArch64::ADDSXrr:
4563   case AArch64::ADDSXri:
4564   case AArch64::SUBSWrr:
4565   case AArch64::SUBSXrr:
4566   // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
4567   case AArch64::SUBSWri:
4568   case AArch64::SUBSXri:
4569     return true;
4570   default:
4571     break;
4572   }
4573   return false;
4574 }
4575 
4576 // 32b Opcodes that can be combined with a MUL
4577 static bool isCombineInstrCandidate32(unsigned Opc) {
4578   switch (Opc) {
4579   case AArch64::ADDWrr:
4580   case AArch64::ADDWri:
4581   case AArch64::SUBWrr:
4582   case AArch64::ADDSWrr:
4583   case AArch64::ADDSWri:
4584   case AArch64::SUBSWrr:
4585   // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
4586   case AArch64::SUBWri:
4587   case AArch64::SUBSWri:
4588     return true;
4589   default:
4590     break;
4591   }
4592   return false;
4593 }
4594 
4595 // 64b Opcodes that can be combined with a MUL
4596 static bool isCombineInstrCandidate64(unsigned Opc) {
4597   switch (Opc) {
4598   case AArch64::ADDXrr:
4599   case AArch64::ADDXri:
4600   case AArch64::SUBXrr:
4601   case AArch64::ADDSXrr:
4602   case AArch64::ADDSXri:
4603   case AArch64::SUBSXrr:
4604   // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
4605   case AArch64::SUBXri:
4606   case AArch64::SUBSXri:
4607   case AArch64::ADDv8i8:
4608   case AArch64::ADDv16i8:
4609   case AArch64::ADDv4i16:
4610   case AArch64::ADDv8i16:
4611   case AArch64::ADDv2i32:
4612   case AArch64::ADDv4i32:
4613   case AArch64::SUBv8i8:
4614   case AArch64::SUBv16i8:
4615   case AArch64::SUBv4i16:
4616   case AArch64::SUBv8i16:
4617   case AArch64::SUBv2i32:
4618   case AArch64::SUBv4i32:
4619     return true;
4620   default:
4621     break;
4622   }
4623   return false;
4624 }
4625 
4626 // FP Opcodes that can be combined with a FMUL.
4627 static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
4628   switch (Inst.getOpcode()) {
4629   default:
4630     break;
4631   case AArch64::FADDHrr:
4632   case AArch64::FADDSrr:
4633   case AArch64::FADDDrr:
4634   case AArch64::FADDv4f16:
4635   case AArch64::FADDv8f16:
4636   case AArch64::FADDv2f32:
4637   case AArch64::FADDv2f64:
4638   case AArch64::FADDv4f32:
4639   case AArch64::FSUBHrr:
4640   case AArch64::FSUBSrr:
4641   case AArch64::FSUBDrr:
4642   case AArch64::FSUBv4f16:
4643   case AArch64::FSUBv8f16:
4644   case AArch64::FSUBv2f32:
4645   case AArch64::FSUBv2f64:
4646   case AArch64::FSUBv4f32:
4647     TargetOptions Options = Inst.getParent()->getParent()->getTarget().Options;
4648     // We can fuse FADD/FSUB with FMUL, if fusion is either allowed globally by
4649     // the target options or if FADD/FSUB has the contract fast-math flag.
4650     return Options.UnsafeFPMath ||
4651            Options.AllowFPOpFusion == FPOpFusion::Fast ||
4652            Inst.getFlag(MachineInstr::FmContract);
4653     return true;
4654   }
4655   return false;
4656 }
4657 
4658 // Opcodes that can be combined with a MUL
4659 static bool isCombineInstrCandidate(unsigned Opc) {
4660   return (isCombineInstrCandidate32(Opc) || isCombineInstrCandidate64(Opc));
4661 }
4662 
4663 //
4664 // Utility routine that checks if \param MO is defined by an
4665 // \param CombineOpc instruction in the basic block \param MBB
4666 static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO,
4667                        unsigned CombineOpc, unsigned ZeroReg = 0,
4668                        bool CheckZeroReg = false) {
4669   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4670   MachineInstr *MI = nullptr;
4671 
4672   if (MO.isReg() && Register::isVirtualRegister(MO.getReg()))
4673     MI = MRI.getUniqueVRegDef(MO.getReg());
4674   // And it needs to be in the trace (otherwise, it won't have a depth).
4675   if (!MI || MI->getParent() != &MBB || (unsigned)MI->getOpcode() != CombineOpc)
4676     return false;
4677   // Must only used by the user we combine with.
4678   if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
4679     return false;
4680 
4681   if (CheckZeroReg) {
4682     assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
4683            MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
4684            MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
4685     // The third input reg must be zero.
4686     if (MI->getOperand(3).getReg() != ZeroReg)
4687       return false;
4688   }
4689 
4690   return true;
4691 }
4692 
4693 //
4694 // Is \param MO defined by an integer multiply and can be combined?
4695 static bool canCombineWithMUL(MachineBasicBlock &MBB, MachineOperand &MO,
4696                               unsigned MulOpc, unsigned ZeroReg) {
4697   return canCombine(MBB, MO, MulOpc, ZeroReg, true);
4698 }
4699 
4700 //
4701 // Is \param MO defined by a floating-point multiply and can be combined?
4702 static bool canCombineWithFMUL(MachineBasicBlock &MBB, MachineOperand &MO,
4703                                unsigned MulOpc) {
4704   return canCombine(MBB, MO, MulOpc);
4705 }
4706 
4707 // TODO: There are many more machine instruction opcodes to match:
4708 //       1. Other data types (integer, vectors)
4709 //       2. Other math / logic operations (xor, or)
4710 //       3. Other forms of the same operation (intrinsics and other variants)
4711 bool AArch64InstrInfo::isAssociativeAndCommutative(
4712     const MachineInstr &Inst) const {
4713   switch (Inst.getOpcode()) {
4714   case AArch64::FADDDrr:
4715   case AArch64::FADDSrr:
4716   case AArch64::FADDv2f32:
4717   case AArch64::FADDv2f64:
4718   case AArch64::FADDv4f32:
4719   case AArch64::FMULDrr:
4720   case AArch64::FMULSrr:
4721   case AArch64::FMULX32:
4722   case AArch64::FMULX64:
4723   case AArch64::FMULXv2f32:
4724   case AArch64::FMULXv2f64:
4725   case AArch64::FMULXv4f32:
4726   case AArch64::FMULv2f32:
4727   case AArch64::FMULv2f64:
4728   case AArch64::FMULv4f32:
4729     return Inst.getParent()->getParent()->getTarget().Options.UnsafeFPMath;
4730   default:
4731     return false;
4732   }
4733 }
4734 
4735 /// Find instructions that can be turned into madd.
4736 static bool getMaddPatterns(MachineInstr &Root,
4737                             SmallVectorImpl<MachineCombinerPattern> &Patterns) {
4738   unsigned Opc = Root.getOpcode();
4739   MachineBasicBlock &MBB = *Root.getParent();
4740   bool Found = false;
4741 
4742   if (!isCombineInstrCandidate(Opc))
4743     return false;
4744   if (isCombineInstrSettingFlag(Opc)) {
4745     int Cmp_NZCV = Root.findRegisterDefOperandIdx(AArch64::NZCV, true);
4746     // When NZCV is live bail out.
4747     if (Cmp_NZCV == -1)
4748       return false;
4749     unsigned NewOpc = convertToNonFlagSettingOpc(Root);
4750     // When opcode can't change bail out.
4751     // CHECKME: do we miss any cases for opcode conversion?
4752     if (NewOpc == Opc)
4753       return false;
4754     Opc = NewOpc;
4755   }
4756 
4757   auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
4758                       MachineCombinerPattern Pattern) {
4759     if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
4760       Patterns.push_back(Pattern);
4761       Found = true;
4762     }
4763   };
4764 
4765   auto setVFound = [&](int Opcode, int Operand, MachineCombinerPattern Pattern) {
4766     if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
4767       Patterns.push_back(Pattern);
4768       Found = true;
4769     }
4770   };
4771 
4772   typedef MachineCombinerPattern MCP;
4773 
4774   switch (Opc) {
4775   default:
4776     break;
4777   case AArch64::ADDWrr:
4778     assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
4779            "ADDWrr does not have register operands");
4780     setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
4781     setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
4782     break;
4783   case AArch64::ADDXrr:
4784     setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
4785     setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
4786     break;
4787   case AArch64::SUBWrr:
4788     setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
4789     setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
4790     break;
4791   case AArch64::SUBXrr:
4792     setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
4793     setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
4794     break;
4795   case AArch64::ADDWri:
4796     setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
4797     break;
4798   case AArch64::ADDXri:
4799     setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
4800     break;
4801   case AArch64::SUBWri:
4802     setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
4803     break;
4804   case AArch64::SUBXri:
4805     setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
4806     break;
4807   case AArch64::ADDv8i8:
4808     setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
4809     setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
4810     break;
4811   case AArch64::ADDv16i8:
4812     setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
4813     setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
4814     break;
4815   case AArch64::ADDv4i16:
4816     setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
4817     setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
4818     setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
4819     setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
4820     break;
4821   case AArch64::ADDv8i16:
4822     setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
4823     setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
4824     setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
4825     setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
4826     break;
4827   case AArch64::ADDv2i32:
4828     setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
4829     setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
4830     setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
4831     setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
4832     break;
4833   case AArch64::ADDv4i32:
4834     setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
4835     setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
4836     setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
4837     setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
4838     break;
4839   case AArch64::SUBv8i8:
4840     setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
4841     setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
4842     break;
4843   case AArch64::SUBv16i8:
4844     setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
4845     setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
4846     break;
4847   case AArch64::SUBv4i16:
4848     setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
4849     setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
4850     setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
4851     setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
4852     break;
4853   case AArch64::SUBv8i16:
4854     setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
4855     setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
4856     setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
4857     setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
4858     break;
4859   case AArch64::SUBv2i32:
4860     setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
4861     setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
4862     setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
4863     setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
4864     break;
4865   case AArch64::SUBv4i32:
4866     setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
4867     setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
4868     setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
4869     setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
4870     break;
4871   }
4872   return Found;
4873 }
4874 /// Floating-Point Support
4875 
4876 /// Find instructions that can be turned into madd.
4877 static bool getFMAPatterns(MachineInstr &Root,
4878                            SmallVectorImpl<MachineCombinerPattern> &Patterns) {
4879 
4880   if (!isCombineInstrCandidateFP(Root))
4881     return false;
4882 
4883   MachineBasicBlock &MBB = *Root.getParent();
4884   bool Found = false;
4885 
4886   auto Match = [&](int Opcode, int Operand,
4887                    MachineCombinerPattern Pattern) -> bool {
4888     if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
4889       Patterns.push_back(Pattern);
4890       return true;
4891     }
4892     return false;
4893   };
4894 
4895   typedef MachineCombinerPattern MCP;
4896 
4897   switch (Root.getOpcode()) {
4898   default:
4899     assert(false && "Unsupported FP instruction in combiner\n");
4900     break;
4901   case AArch64::FADDHrr:
4902     assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
4903            "FADDHrr does not have register operands");
4904 
4905     Found  = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
4906     Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
4907     break;
4908   case AArch64::FADDSrr:
4909     assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
4910            "FADDSrr does not have register operands");
4911 
4912     Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
4913              Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
4914 
4915     Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
4916              Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
4917     break;
4918   case AArch64::FADDDrr:
4919     Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
4920              Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
4921 
4922     Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
4923              Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
4924     break;
4925   case AArch64::FADDv4f16:
4926     Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
4927              Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
4928 
4929     Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
4930              Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
4931     break;
4932   case AArch64::FADDv8f16:
4933     Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
4934              Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
4935 
4936     Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
4937              Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
4938     break;
4939   case AArch64::FADDv2f32:
4940     Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
4941              Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
4942 
4943     Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
4944              Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
4945     break;
4946   case AArch64::FADDv2f64:
4947     Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
4948              Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
4949 
4950     Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
4951              Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
4952     break;
4953   case AArch64::FADDv4f32:
4954     Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
4955              Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
4956 
4957     Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
4958              Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
4959     break;
4960   case AArch64::FSUBHrr:
4961     Found  = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
4962     Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
4963     Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
4964     break;
4965   case AArch64::FSUBSrr:
4966     Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
4967 
4968     Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
4969              Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
4970 
4971     Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
4972     break;
4973   case AArch64::FSUBDrr:
4974     Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
4975 
4976     Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
4977              Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
4978 
4979     Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
4980     break;
4981   case AArch64::FSUBv4f16:
4982     Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
4983              Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
4984 
4985     Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
4986              Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
4987     break;
4988   case AArch64::FSUBv8f16:
4989     Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
4990              Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
4991 
4992     Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
4993              Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
4994     break;
4995   case AArch64::FSUBv2f32:
4996     Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
4997              Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
4998 
4999     Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
5000              Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
5001     break;
5002   case AArch64::FSUBv2f64:
5003     Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
5004              Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
5005 
5006     Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
5007              Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
5008     break;
5009   case AArch64::FSUBv4f32:
5010     Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
5011              Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
5012 
5013     Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
5014              Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
5015     break;
5016   }
5017   return Found;
5018 }
5019 
5020 static bool getFMULPatterns(MachineInstr &Root,
5021                             SmallVectorImpl<MachineCombinerPattern> &Patterns) {
5022   MachineBasicBlock &MBB = *Root.getParent();
5023   bool Found = false;
5024 
5025   auto Match = [&](unsigned Opcode, int Operand,
5026                    MachineCombinerPattern Pattern) -> bool {
5027     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5028     MachineOperand &MO = Root.getOperand(Operand);
5029     MachineInstr *MI = nullptr;
5030     if (MO.isReg() && Register::isVirtualRegister(MO.getReg()))
5031       MI = MRI.getUniqueVRegDef(MO.getReg());
5032     if (MI && MI->getOpcode() == Opcode) {
5033       Patterns.push_back(Pattern);
5034       return true;
5035     }
5036     return false;
5037   };
5038 
5039   typedef MachineCombinerPattern MCP;
5040 
5041   switch (Root.getOpcode()) {
5042   default:
5043     return false;
5044   case AArch64::FMULv2f32:
5045     Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
5046     Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
5047     break;
5048   case AArch64::FMULv2f64:
5049     Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
5050     Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
5051     break;
5052   case AArch64::FMULv4f16:
5053     Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
5054     Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
5055     break;
5056   case AArch64::FMULv4f32:
5057     Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
5058     Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
5059     break;
5060   case AArch64::FMULv8f16:
5061     Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
5062     Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
5063     break;
5064   }
5065 
5066   return Found;
5067 }
5068 
5069 /// Return true when a code sequence can improve throughput. It
5070 /// should be called only for instructions in loops.
5071 /// \param Pattern - combiner pattern
5072 bool AArch64InstrInfo::isThroughputPattern(
5073     MachineCombinerPattern Pattern) const {
5074   switch (Pattern) {
5075   default:
5076     break;
5077   case MachineCombinerPattern::FMULADDH_OP1:
5078   case MachineCombinerPattern::FMULADDH_OP2:
5079   case MachineCombinerPattern::FMULSUBH_OP1:
5080   case MachineCombinerPattern::FMULSUBH_OP2:
5081   case MachineCombinerPattern::FMULADDS_OP1:
5082   case MachineCombinerPattern::FMULADDS_OP2:
5083   case MachineCombinerPattern::FMULSUBS_OP1:
5084   case MachineCombinerPattern::FMULSUBS_OP2:
5085   case MachineCombinerPattern::FMULADDD_OP1:
5086   case MachineCombinerPattern::FMULADDD_OP2:
5087   case MachineCombinerPattern::FMULSUBD_OP1:
5088   case MachineCombinerPattern::FMULSUBD_OP2:
5089   case MachineCombinerPattern::FNMULSUBH_OP1:
5090   case MachineCombinerPattern::FNMULSUBS_OP1:
5091   case MachineCombinerPattern::FNMULSUBD_OP1:
5092   case MachineCombinerPattern::FMLAv4i16_indexed_OP1:
5093   case MachineCombinerPattern::FMLAv4i16_indexed_OP2:
5094   case MachineCombinerPattern::FMLAv8i16_indexed_OP1:
5095   case MachineCombinerPattern::FMLAv8i16_indexed_OP2:
5096   case MachineCombinerPattern::FMLAv1i32_indexed_OP1:
5097   case MachineCombinerPattern::FMLAv1i32_indexed_OP2:
5098   case MachineCombinerPattern::FMLAv1i64_indexed_OP1:
5099   case MachineCombinerPattern::FMLAv1i64_indexed_OP2:
5100   case MachineCombinerPattern::FMLAv4f16_OP2:
5101   case MachineCombinerPattern::FMLAv4f16_OP1:
5102   case MachineCombinerPattern::FMLAv8f16_OP1:
5103   case MachineCombinerPattern::FMLAv8f16_OP2:
5104   case MachineCombinerPattern::FMLAv2f32_OP2:
5105   case MachineCombinerPattern::FMLAv2f32_OP1:
5106   case MachineCombinerPattern::FMLAv2f64_OP1:
5107   case MachineCombinerPattern::FMLAv2f64_OP2:
5108   case MachineCombinerPattern::FMLAv2i32_indexed_OP1:
5109   case MachineCombinerPattern::FMLAv2i32_indexed_OP2:
5110   case MachineCombinerPattern::FMLAv2i64_indexed_OP1:
5111   case MachineCombinerPattern::FMLAv2i64_indexed_OP2:
5112   case MachineCombinerPattern::FMLAv4f32_OP1:
5113   case MachineCombinerPattern::FMLAv4f32_OP2:
5114   case MachineCombinerPattern::FMLAv4i32_indexed_OP1:
5115   case MachineCombinerPattern::FMLAv4i32_indexed_OP2:
5116   case MachineCombinerPattern::FMLSv4i16_indexed_OP1:
5117   case MachineCombinerPattern::FMLSv4i16_indexed_OP2:
5118   case MachineCombinerPattern::FMLSv8i16_indexed_OP1:
5119   case MachineCombinerPattern::FMLSv8i16_indexed_OP2:
5120   case MachineCombinerPattern::FMLSv1i32_indexed_OP2:
5121   case MachineCombinerPattern::FMLSv1i64_indexed_OP2:
5122   case MachineCombinerPattern::FMLSv2i32_indexed_OP2:
5123   case MachineCombinerPattern::FMLSv2i64_indexed_OP2:
5124   case MachineCombinerPattern::FMLSv4f16_OP1:
5125   case MachineCombinerPattern::FMLSv4f16_OP2:
5126   case MachineCombinerPattern::FMLSv8f16_OP1:
5127   case MachineCombinerPattern::FMLSv8f16_OP2:
5128   case MachineCombinerPattern::FMLSv2f32_OP2:
5129   case MachineCombinerPattern::FMLSv2f64_OP2:
5130   case MachineCombinerPattern::FMLSv4i32_indexed_OP2:
5131   case MachineCombinerPattern::FMLSv4f32_OP2:
5132   case MachineCombinerPattern::FMULv2i32_indexed_OP1:
5133   case MachineCombinerPattern::FMULv2i32_indexed_OP2:
5134   case MachineCombinerPattern::FMULv2i64_indexed_OP1:
5135   case MachineCombinerPattern::FMULv2i64_indexed_OP2:
5136   case MachineCombinerPattern::FMULv4i16_indexed_OP1:
5137   case MachineCombinerPattern::FMULv4i16_indexed_OP2:
5138   case MachineCombinerPattern::FMULv4i32_indexed_OP1:
5139   case MachineCombinerPattern::FMULv4i32_indexed_OP2:
5140   case MachineCombinerPattern::FMULv8i16_indexed_OP1:
5141   case MachineCombinerPattern::FMULv8i16_indexed_OP2:
5142   case MachineCombinerPattern::MULADDv8i8_OP1:
5143   case MachineCombinerPattern::MULADDv8i8_OP2:
5144   case MachineCombinerPattern::MULADDv16i8_OP1:
5145   case MachineCombinerPattern::MULADDv16i8_OP2:
5146   case MachineCombinerPattern::MULADDv4i16_OP1:
5147   case MachineCombinerPattern::MULADDv4i16_OP2:
5148   case MachineCombinerPattern::MULADDv8i16_OP1:
5149   case MachineCombinerPattern::MULADDv8i16_OP2:
5150   case MachineCombinerPattern::MULADDv2i32_OP1:
5151   case MachineCombinerPattern::MULADDv2i32_OP2:
5152   case MachineCombinerPattern::MULADDv4i32_OP1:
5153   case MachineCombinerPattern::MULADDv4i32_OP2:
5154   case MachineCombinerPattern::MULSUBv8i8_OP1:
5155   case MachineCombinerPattern::MULSUBv8i8_OP2:
5156   case MachineCombinerPattern::MULSUBv16i8_OP1:
5157   case MachineCombinerPattern::MULSUBv16i8_OP2:
5158   case MachineCombinerPattern::MULSUBv4i16_OP1:
5159   case MachineCombinerPattern::MULSUBv4i16_OP2:
5160   case MachineCombinerPattern::MULSUBv8i16_OP1:
5161   case MachineCombinerPattern::MULSUBv8i16_OP2:
5162   case MachineCombinerPattern::MULSUBv2i32_OP1:
5163   case MachineCombinerPattern::MULSUBv2i32_OP2:
5164   case MachineCombinerPattern::MULSUBv4i32_OP1:
5165   case MachineCombinerPattern::MULSUBv4i32_OP2:
5166   case MachineCombinerPattern::MULADDv4i16_indexed_OP1:
5167   case MachineCombinerPattern::MULADDv4i16_indexed_OP2:
5168   case MachineCombinerPattern::MULADDv8i16_indexed_OP1:
5169   case MachineCombinerPattern::MULADDv8i16_indexed_OP2:
5170   case MachineCombinerPattern::MULADDv2i32_indexed_OP1:
5171   case MachineCombinerPattern::MULADDv2i32_indexed_OP2:
5172   case MachineCombinerPattern::MULADDv4i32_indexed_OP1:
5173   case MachineCombinerPattern::MULADDv4i32_indexed_OP2:
5174   case MachineCombinerPattern::MULSUBv4i16_indexed_OP1:
5175   case MachineCombinerPattern::MULSUBv4i16_indexed_OP2:
5176   case MachineCombinerPattern::MULSUBv8i16_indexed_OP1:
5177   case MachineCombinerPattern::MULSUBv8i16_indexed_OP2:
5178   case MachineCombinerPattern::MULSUBv2i32_indexed_OP1:
5179   case MachineCombinerPattern::MULSUBv2i32_indexed_OP2:
5180   case MachineCombinerPattern::MULSUBv4i32_indexed_OP1:
5181   case MachineCombinerPattern::MULSUBv4i32_indexed_OP2:
5182     return true;
5183   } // end switch (Pattern)
5184   return false;
5185 }
5186 /// Return true when there is potentially a faster code sequence for an
5187 /// instruction chain ending in \p Root. All potential patterns are listed in
5188 /// the \p Pattern vector. Pattern should be sorted in priority order since the
5189 /// pattern evaluator stops checking as soon as it finds a faster sequence.
5190 
5191 bool AArch64InstrInfo::getMachineCombinerPatterns(
5192     MachineInstr &Root, SmallVectorImpl<MachineCombinerPattern> &Patterns,
5193     bool DoRegPressureReduce) const {
5194   // Integer patterns
5195   if (getMaddPatterns(Root, Patterns))
5196     return true;
5197   // Floating point patterns
5198   if (getFMULPatterns(Root, Patterns))
5199     return true;
5200   if (getFMAPatterns(Root, Patterns))
5201     return true;
5202 
5203   return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
5204                                                      DoRegPressureReduce);
5205 }
5206 
5207 enum class FMAInstKind { Default, Indexed, Accumulator };
5208 /// genFusedMultiply - Generate fused multiply instructions.
5209 /// This function supports both integer and floating point instructions.
5210 /// A typical example:
5211 ///  F|MUL I=A,B,0
5212 ///  F|ADD R,I,C
5213 ///  ==> F|MADD R,A,B,C
5214 /// \param MF Containing MachineFunction
5215 /// \param MRI Register information
5216 /// \param TII Target information
5217 /// \param Root is the F|ADD instruction
5218 /// \param [out] InsInstrs is a vector of machine instructions and will
5219 /// contain the generated madd instruction
5220 /// \param IdxMulOpd is index of operand in Root that is the result of
5221 /// the F|MUL. In the example above IdxMulOpd is 1.
5222 /// \param MaddOpc the opcode fo the f|madd instruction
5223 /// \param RC Register class of operands
5224 /// \param kind of fma instruction (addressing mode) to be generated
5225 /// \param ReplacedAddend is the result register from the instruction
5226 /// replacing the non-combined operand, if any.
5227 static MachineInstr *
5228 genFusedMultiply(MachineFunction &MF, MachineRegisterInfo &MRI,
5229                  const TargetInstrInfo *TII, MachineInstr &Root,
5230                  SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
5231                  unsigned MaddOpc, const TargetRegisterClass *RC,
5232                  FMAInstKind kind = FMAInstKind::Default,
5233                  const Register *ReplacedAddend = nullptr) {
5234   assert(IdxMulOpd == 1 || IdxMulOpd == 2);
5235 
5236   unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
5237   MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
5238   Register ResultReg = Root.getOperand(0).getReg();
5239   Register SrcReg0 = MUL->getOperand(1).getReg();
5240   bool Src0IsKill = MUL->getOperand(1).isKill();
5241   Register SrcReg1 = MUL->getOperand(2).getReg();
5242   bool Src1IsKill = MUL->getOperand(2).isKill();
5243 
5244   unsigned SrcReg2;
5245   bool Src2IsKill;
5246   if (ReplacedAddend) {
5247     // If we just generated a new addend, we must be it's only use.
5248     SrcReg2 = *ReplacedAddend;
5249     Src2IsKill = true;
5250   } else {
5251     SrcReg2 = Root.getOperand(IdxOtherOpd).getReg();
5252     Src2IsKill = Root.getOperand(IdxOtherOpd).isKill();
5253   }
5254 
5255   if (Register::isVirtualRegister(ResultReg))
5256     MRI.constrainRegClass(ResultReg, RC);
5257   if (Register::isVirtualRegister(SrcReg0))
5258     MRI.constrainRegClass(SrcReg0, RC);
5259   if (Register::isVirtualRegister(SrcReg1))
5260     MRI.constrainRegClass(SrcReg1, RC);
5261   if (Register::isVirtualRegister(SrcReg2))
5262     MRI.constrainRegClass(SrcReg2, RC);
5263 
5264   MachineInstrBuilder MIB;
5265   if (kind == FMAInstKind::Default)
5266     MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg)
5267               .addReg(SrcReg0, getKillRegState(Src0IsKill))
5268               .addReg(SrcReg1, getKillRegState(Src1IsKill))
5269               .addReg(SrcReg2, getKillRegState(Src2IsKill));
5270   else if (kind == FMAInstKind::Indexed)
5271     MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg)
5272               .addReg(SrcReg2, getKillRegState(Src2IsKill))
5273               .addReg(SrcReg0, getKillRegState(Src0IsKill))
5274               .addReg(SrcReg1, getKillRegState(Src1IsKill))
5275               .addImm(MUL->getOperand(3).getImm());
5276   else if (kind == FMAInstKind::Accumulator)
5277     MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg)
5278               .addReg(SrcReg2, getKillRegState(Src2IsKill))
5279               .addReg(SrcReg0, getKillRegState(Src0IsKill))
5280               .addReg(SrcReg1, getKillRegState(Src1IsKill));
5281   else
5282     assert(false && "Invalid FMA instruction kind \n");
5283   // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
5284   InsInstrs.push_back(MIB);
5285   return MUL;
5286 }
5287 
5288 /// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
5289 static MachineInstr *
5290 genIndexedMultiply(MachineInstr &Root,
5291                    SmallVectorImpl<MachineInstr *> &InsInstrs,
5292                    unsigned IdxDupOp, unsigned MulOpc,
5293                    const TargetRegisterClass *RC, MachineRegisterInfo &MRI) {
5294   assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
5295          "Invalid index of FMUL operand");
5296 
5297   MachineFunction &MF = *Root.getMF();
5298   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
5299 
5300   MachineInstr *Dup =
5301       MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
5302 
5303   Register DupSrcReg = Dup->getOperand(1).getReg();
5304   MRI.clearKillFlags(DupSrcReg);
5305   MRI.constrainRegClass(DupSrcReg, RC);
5306 
5307   unsigned DupSrcLane = Dup->getOperand(2).getImm();
5308 
5309   unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
5310   MachineOperand &MulOp = Root.getOperand(IdxMulOp);
5311 
5312   Register ResultReg = Root.getOperand(0).getReg();
5313 
5314   MachineInstrBuilder MIB;
5315   MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MulOpc), ResultReg)
5316             .add(MulOp)
5317             .addReg(DupSrcReg)
5318             .addImm(DupSrcLane);
5319 
5320   InsInstrs.push_back(MIB);
5321   return &Root;
5322 }
5323 
5324 /// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
5325 /// instructions.
5326 ///
5327 /// \see genFusedMultiply
5328 static MachineInstr *genFusedMultiplyAcc(
5329     MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
5330     MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
5331     unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
5332   return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
5333                           FMAInstKind::Accumulator);
5334 }
5335 
5336 /// genNeg - Helper to generate an intermediate negation of the second operand
5337 /// of Root
5338 static Register genNeg(MachineFunction &MF, MachineRegisterInfo &MRI,
5339                        const TargetInstrInfo *TII, MachineInstr &Root,
5340                        SmallVectorImpl<MachineInstr *> &InsInstrs,
5341                        DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
5342                        unsigned MnegOpc, const TargetRegisterClass *RC) {
5343   Register NewVR = MRI.createVirtualRegister(RC);
5344   MachineInstrBuilder MIB =
5345       BuildMI(MF, Root.getDebugLoc(), TII->get(MnegOpc), NewVR)
5346           .add(Root.getOperand(2));
5347   InsInstrs.push_back(MIB);
5348 
5349   assert(InstrIdxForVirtReg.empty());
5350   InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
5351 
5352   return NewVR;
5353 }
5354 
5355 /// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
5356 /// instructions with an additional negation of the accumulator
5357 static MachineInstr *genFusedMultiplyAccNeg(
5358     MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
5359     MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
5360     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
5361     unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
5362   assert(IdxMulOpd == 1);
5363 
5364   Register NewVR =
5365       genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
5366   return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
5367                           FMAInstKind::Accumulator, &NewVR);
5368 }
5369 
5370 /// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
5371 /// instructions.
5372 ///
5373 /// \see genFusedMultiply
5374 static MachineInstr *genFusedMultiplyIdx(
5375     MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
5376     MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
5377     unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
5378   return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
5379                           FMAInstKind::Indexed);
5380 }
5381 
5382 /// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
5383 /// instructions with an additional negation of the accumulator
5384 static MachineInstr *genFusedMultiplyIdxNeg(
5385     MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
5386     MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
5387     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
5388     unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
5389   assert(IdxMulOpd == 1);
5390 
5391   Register NewVR =
5392       genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
5393 
5394   return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
5395                           FMAInstKind::Indexed, &NewVR);
5396 }
5397 
5398 /// genMaddR - Generate madd instruction and combine mul and add using
5399 /// an extra virtual register
5400 /// Example - an ADD intermediate needs to be stored in a register:
5401 ///   MUL I=A,B,0
5402 ///   ADD R,I,Imm
5403 ///   ==> ORR  V, ZR, Imm
5404 ///   ==> MADD R,A,B,V
5405 /// \param MF Containing MachineFunction
5406 /// \param MRI Register information
5407 /// \param TII Target information
5408 /// \param Root is the ADD instruction
5409 /// \param [out] InsInstrs is a vector of machine instructions and will
5410 /// contain the generated madd instruction
5411 /// \param IdxMulOpd is index of operand in Root that is the result of
5412 /// the MUL. In the example above IdxMulOpd is 1.
5413 /// \param MaddOpc the opcode fo the madd instruction
5414 /// \param VR is a virtual register that holds the value of an ADD operand
5415 /// (V in the example above).
5416 /// \param RC Register class of operands
5417 static MachineInstr *genMaddR(MachineFunction &MF, MachineRegisterInfo &MRI,
5418                               const TargetInstrInfo *TII, MachineInstr &Root,
5419                               SmallVectorImpl<MachineInstr *> &InsInstrs,
5420                               unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
5421                               const TargetRegisterClass *RC) {
5422   assert(IdxMulOpd == 1 || IdxMulOpd == 2);
5423 
5424   MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
5425   Register ResultReg = Root.getOperand(0).getReg();
5426   Register SrcReg0 = MUL->getOperand(1).getReg();
5427   bool Src0IsKill = MUL->getOperand(1).isKill();
5428   Register SrcReg1 = MUL->getOperand(2).getReg();
5429   bool Src1IsKill = MUL->getOperand(2).isKill();
5430 
5431   if (Register::isVirtualRegister(ResultReg))
5432     MRI.constrainRegClass(ResultReg, RC);
5433   if (Register::isVirtualRegister(SrcReg0))
5434     MRI.constrainRegClass(SrcReg0, RC);
5435   if (Register::isVirtualRegister(SrcReg1))
5436     MRI.constrainRegClass(SrcReg1, RC);
5437   if (Register::isVirtualRegister(VR))
5438     MRI.constrainRegClass(VR, RC);
5439 
5440   MachineInstrBuilder MIB =
5441       BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg)
5442           .addReg(SrcReg0, getKillRegState(Src0IsKill))
5443           .addReg(SrcReg1, getKillRegState(Src1IsKill))
5444           .addReg(VR);
5445   // Insert the MADD
5446   InsInstrs.push_back(MIB);
5447   return MUL;
5448 }
5449 
5450 /// When getMachineCombinerPatterns() finds potential patterns,
5451 /// this function generates the instructions that could replace the
5452 /// original code sequence
5453 void AArch64InstrInfo::genAlternativeCodeSequence(
5454     MachineInstr &Root, MachineCombinerPattern Pattern,
5455     SmallVectorImpl<MachineInstr *> &InsInstrs,
5456     SmallVectorImpl<MachineInstr *> &DelInstrs,
5457     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
5458   MachineBasicBlock &MBB = *Root.getParent();
5459   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5460   MachineFunction &MF = *MBB.getParent();
5461   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
5462 
5463   MachineInstr *MUL = nullptr;
5464   const TargetRegisterClass *RC;
5465   unsigned Opc;
5466   switch (Pattern) {
5467   default:
5468     // Reassociate instructions.
5469     TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
5470                                                 DelInstrs, InstrIdxForVirtReg);
5471     return;
5472   case MachineCombinerPattern::MULADDW_OP1:
5473   case MachineCombinerPattern::MULADDX_OP1:
5474     // MUL I=A,B,0
5475     // ADD R,I,C
5476     // ==> MADD R,A,B,C
5477     // --- Create(MADD);
5478     if (Pattern == MachineCombinerPattern::MULADDW_OP1) {
5479       Opc = AArch64::MADDWrrr;
5480       RC = &AArch64::GPR32RegClass;
5481     } else {
5482       Opc = AArch64::MADDXrrr;
5483       RC = &AArch64::GPR64RegClass;
5484     }
5485     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5486     break;
5487   case MachineCombinerPattern::MULADDW_OP2:
5488   case MachineCombinerPattern::MULADDX_OP2:
5489     // MUL I=A,B,0
5490     // ADD R,C,I
5491     // ==> MADD R,A,B,C
5492     // --- Create(MADD);
5493     if (Pattern == MachineCombinerPattern::MULADDW_OP2) {
5494       Opc = AArch64::MADDWrrr;
5495       RC = &AArch64::GPR32RegClass;
5496     } else {
5497       Opc = AArch64::MADDXrrr;
5498       RC = &AArch64::GPR64RegClass;
5499     }
5500     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5501     break;
5502   case MachineCombinerPattern::MULADDWI_OP1:
5503   case MachineCombinerPattern::MULADDXI_OP1: {
5504     // MUL I=A,B,0
5505     // ADD R,I,Imm
5506     // ==> ORR  V, ZR, Imm
5507     // ==> MADD R,A,B,V
5508     // --- Create(MADD);
5509     const TargetRegisterClass *OrrRC;
5510     unsigned BitSize, OrrOpc, ZeroReg;
5511     if (Pattern == MachineCombinerPattern::MULADDWI_OP1) {
5512       OrrOpc = AArch64::ORRWri;
5513       OrrRC = &AArch64::GPR32spRegClass;
5514       BitSize = 32;
5515       ZeroReg = AArch64::WZR;
5516       Opc = AArch64::MADDWrrr;
5517       RC = &AArch64::GPR32RegClass;
5518     } else {
5519       OrrOpc = AArch64::ORRXri;
5520       OrrRC = &AArch64::GPR64spRegClass;
5521       BitSize = 64;
5522       ZeroReg = AArch64::XZR;
5523       Opc = AArch64::MADDXrrr;
5524       RC = &AArch64::GPR64RegClass;
5525     }
5526     Register NewVR = MRI.createVirtualRegister(OrrRC);
5527     uint64_t Imm = Root.getOperand(2).getImm();
5528 
5529     if (Root.getOperand(3).isImm()) {
5530       unsigned Val = Root.getOperand(3).getImm();
5531       Imm = Imm << Val;
5532     }
5533     uint64_t UImm = SignExtend64(Imm, BitSize);
5534     uint64_t Encoding;
5535     if (!AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding))
5536       return;
5537     MachineInstrBuilder MIB1 =
5538         BuildMI(MF, Root.getDebugLoc(), TII->get(OrrOpc), NewVR)
5539             .addReg(ZeroReg)
5540             .addImm(Encoding);
5541     InsInstrs.push_back(MIB1);
5542     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
5543     MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
5544     break;
5545   }
5546   case MachineCombinerPattern::MULSUBW_OP1:
5547   case MachineCombinerPattern::MULSUBX_OP1: {
5548     // MUL I=A,B,0
5549     // SUB R,I, C
5550     // ==> SUB  V, 0, C
5551     // ==> MADD R,A,B,V // = -C + A*B
5552     // --- Create(MADD);
5553     const TargetRegisterClass *SubRC;
5554     unsigned SubOpc, ZeroReg;
5555     if (Pattern == MachineCombinerPattern::MULSUBW_OP1) {
5556       SubOpc = AArch64::SUBWrr;
5557       SubRC = &AArch64::GPR32spRegClass;
5558       ZeroReg = AArch64::WZR;
5559       Opc = AArch64::MADDWrrr;
5560       RC = &AArch64::GPR32RegClass;
5561     } else {
5562       SubOpc = AArch64::SUBXrr;
5563       SubRC = &AArch64::GPR64spRegClass;
5564       ZeroReg = AArch64::XZR;
5565       Opc = AArch64::MADDXrrr;
5566       RC = &AArch64::GPR64RegClass;
5567     }
5568     Register NewVR = MRI.createVirtualRegister(SubRC);
5569     // SUB NewVR, 0, C
5570     MachineInstrBuilder MIB1 =
5571         BuildMI(MF, Root.getDebugLoc(), TII->get(SubOpc), NewVR)
5572             .addReg(ZeroReg)
5573             .add(Root.getOperand(2));
5574     InsInstrs.push_back(MIB1);
5575     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
5576     MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
5577     break;
5578   }
5579   case MachineCombinerPattern::MULSUBW_OP2:
5580   case MachineCombinerPattern::MULSUBX_OP2:
5581     // MUL I=A,B,0
5582     // SUB R,C,I
5583     // ==> MSUB R,A,B,C (computes C - A*B)
5584     // --- Create(MSUB);
5585     if (Pattern == MachineCombinerPattern::MULSUBW_OP2) {
5586       Opc = AArch64::MSUBWrrr;
5587       RC = &AArch64::GPR32RegClass;
5588     } else {
5589       Opc = AArch64::MSUBXrrr;
5590       RC = &AArch64::GPR64RegClass;
5591     }
5592     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5593     break;
5594   case MachineCombinerPattern::MULSUBWI_OP1:
5595   case MachineCombinerPattern::MULSUBXI_OP1: {
5596     // MUL I=A,B,0
5597     // SUB R,I, Imm
5598     // ==> ORR  V, ZR, -Imm
5599     // ==> MADD R,A,B,V // = -Imm + A*B
5600     // --- Create(MADD);
5601     const TargetRegisterClass *OrrRC;
5602     unsigned BitSize, OrrOpc, ZeroReg;
5603     if (Pattern == MachineCombinerPattern::MULSUBWI_OP1) {
5604       OrrOpc = AArch64::ORRWri;
5605       OrrRC = &AArch64::GPR32spRegClass;
5606       BitSize = 32;
5607       ZeroReg = AArch64::WZR;
5608       Opc = AArch64::MADDWrrr;
5609       RC = &AArch64::GPR32RegClass;
5610     } else {
5611       OrrOpc = AArch64::ORRXri;
5612       OrrRC = &AArch64::GPR64spRegClass;
5613       BitSize = 64;
5614       ZeroReg = AArch64::XZR;
5615       Opc = AArch64::MADDXrrr;
5616       RC = &AArch64::GPR64RegClass;
5617     }
5618     Register NewVR = MRI.createVirtualRegister(OrrRC);
5619     uint64_t Imm = Root.getOperand(2).getImm();
5620     if (Root.getOperand(3).isImm()) {
5621       unsigned Val = Root.getOperand(3).getImm();
5622       Imm = Imm << Val;
5623     }
5624     uint64_t UImm = SignExtend64(-Imm, BitSize);
5625     uint64_t Encoding;
5626     if (!AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding))
5627       return;
5628     MachineInstrBuilder MIB1 =
5629         BuildMI(MF, Root.getDebugLoc(), TII->get(OrrOpc), NewVR)
5630             .addReg(ZeroReg)
5631             .addImm(Encoding);
5632     InsInstrs.push_back(MIB1);
5633     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
5634     MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
5635     break;
5636   }
5637 
5638   case MachineCombinerPattern::MULADDv8i8_OP1:
5639     Opc = AArch64::MLAv8i8;
5640     RC = &AArch64::FPR64RegClass;
5641     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5642     break;
5643   case MachineCombinerPattern::MULADDv8i8_OP2:
5644     Opc = AArch64::MLAv8i8;
5645     RC = &AArch64::FPR64RegClass;
5646     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5647     break;
5648   case MachineCombinerPattern::MULADDv16i8_OP1:
5649     Opc = AArch64::MLAv16i8;
5650     RC = &AArch64::FPR128RegClass;
5651     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5652     break;
5653   case MachineCombinerPattern::MULADDv16i8_OP2:
5654     Opc = AArch64::MLAv16i8;
5655     RC = &AArch64::FPR128RegClass;
5656     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5657     break;
5658   case MachineCombinerPattern::MULADDv4i16_OP1:
5659     Opc = AArch64::MLAv4i16;
5660     RC = &AArch64::FPR64RegClass;
5661     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5662     break;
5663   case MachineCombinerPattern::MULADDv4i16_OP2:
5664     Opc = AArch64::MLAv4i16;
5665     RC = &AArch64::FPR64RegClass;
5666     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5667     break;
5668   case MachineCombinerPattern::MULADDv8i16_OP1:
5669     Opc = AArch64::MLAv8i16;
5670     RC = &AArch64::FPR128RegClass;
5671     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5672     break;
5673   case MachineCombinerPattern::MULADDv8i16_OP2:
5674     Opc = AArch64::MLAv8i16;
5675     RC = &AArch64::FPR128RegClass;
5676     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5677     break;
5678   case MachineCombinerPattern::MULADDv2i32_OP1:
5679     Opc = AArch64::MLAv2i32;
5680     RC = &AArch64::FPR64RegClass;
5681     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5682     break;
5683   case MachineCombinerPattern::MULADDv2i32_OP2:
5684     Opc = AArch64::MLAv2i32;
5685     RC = &AArch64::FPR64RegClass;
5686     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5687     break;
5688   case MachineCombinerPattern::MULADDv4i32_OP1:
5689     Opc = AArch64::MLAv4i32;
5690     RC = &AArch64::FPR128RegClass;
5691     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5692     break;
5693   case MachineCombinerPattern::MULADDv4i32_OP2:
5694     Opc = AArch64::MLAv4i32;
5695     RC = &AArch64::FPR128RegClass;
5696     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5697     break;
5698 
5699   case MachineCombinerPattern::MULSUBv8i8_OP1:
5700     Opc = AArch64::MLAv8i8;
5701     RC = &AArch64::FPR64RegClass;
5702     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5703                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
5704                                  RC);
5705     break;
5706   case MachineCombinerPattern::MULSUBv8i8_OP2:
5707     Opc = AArch64::MLSv8i8;
5708     RC = &AArch64::FPR64RegClass;
5709     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5710     break;
5711   case MachineCombinerPattern::MULSUBv16i8_OP1:
5712     Opc = AArch64::MLAv16i8;
5713     RC = &AArch64::FPR128RegClass;
5714     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5715                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
5716                                  RC);
5717     break;
5718   case MachineCombinerPattern::MULSUBv16i8_OP2:
5719     Opc = AArch64::MLSv16i8;
5720     RC = &AArch64::FPR128RegClass;
5721     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5722     break;
5723   case MachineCombinerPattern::MULSUBv4i16_OP1:
5724     Opc = AArch64::MLAv4i16;
5725     RC = &AArch64::FPR64RegClass;
5726     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5727                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
5728                                  RC);
5729     break;
5730   case MachineCombinerPattern::MULSUBv4i16_OP2:
5731     Opc = AArch64::MLSv4i16;
5732     RC = &AArch64::FPR64RegClass;
5733     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5734     break;
5735   case MachineCombinerPattern::MULSUBv8i16_OP1:
5736     Opc = AArch64::MLAv8i16;
5737     RC = &AArch64::FPR128RegClass;
5738     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5739                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
5740                                  RC);
5741     break;
5742   case MachineCombinerPattern::MULSUBv8i16_OP2:
5743     Opc = AArch64::MLSv8i16;
5744     RC = &AArch64::FPR128RegClass;
5745     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5746     break;
5747   case MachineCombinerPattern::MULSUBv2i32_OP1:
5748     Opc = AArch64::MLAv2i32;
5749     RC = &AArch64::FPR64RegClass;
5750     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5751                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
5752                                  RC);
5753     break;
5754   case MachineCombinerPattern::MULSUBv2i32_OP2:
5755     Opc = AArch64::MLSv2i32;
5756     RC = &AArch64::FPR64RegClass;
5757     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5758     break;
5759   case MachineCombinerPattern::MULSUBv4i32_OP1:
5760     Opc = AArch64::MLAv4i32;
5761     RC = &AArch64::FPR128RegClass;
5762     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5763                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
5764                                  RC);
5765     break;
5766   case MachineCombinerPattern::MULSUBv4i32_OP2:
5767     Opc = AArch64::MLSv4i32;
5768     RC = &AArch64::FPR128RegClass;
5769     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5770     break;
5771 
5772   case MachineCombinerPattern::MULADDv4i16_indexed_OP1:
5773     Opc = AArch64::MLAv4i16_indexed;
5774     RC = &AArch64::FPR64RegClass;
5775     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5776     break;
5777   case MachineCombinerPattern::MULADDv4i16_indexed_OP2:
5778     Opc = AArch64::MLAv4i16_indexed;
5779     RC = &AArch64::FPR64RegClass;
5780     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5781     break;
5782   case MachineCombinerPattern::MULADDv8i16_indexed_OP1:
5783     Opc = AArch64::MLAv8i16_indexed;
5784     RC = &AArch64::FPR128RegClass;
5785     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5786     break;
5787   case MachineCombinerPattern::MULADDv8i16_indexed_OP2:
5788     Opc = AArch64::MLAv8i16_indexed;
5789     RC = &AArch64::FPR128RegClass;
5790     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5791     break;
5792   case MachineCombinerPattern::MULADDv2i32_indexed_OP1:
5793     Opc = AArch64::MLAv2i32_indexed;
5794     RC = &AArch64::FPR64RegClass;
5795     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5796     break;
5797   case MachineCombinerPattern::MULADDv2i32_indexed_OP2:
5798     Opc = AArch64::MLAv2i32_indexed;
5799     RC = &AArch64::FPR64RegClass;
5800     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5801     break;
5802   case MachineCombinerPattern::MULADDv4i32_indexed_OP1:
5803     Opc = AArch64::MLAv4i32_indexed;
5804     RC = &AArch64::FPR128RegClass;
5805     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5806     break;
5807   case MachineCombinerPattern::MULADDv4i32_indexed_OP2:
5808     Opc = AArch64::MLAv4i32_indexed;
5809     RC = &AArch64::FPR128RegClass;
5810     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5811     break;
5812 
5813   case MachineCombinerPattern::MULSUBv4i16_indexed_OP1:
5814     Opc = AArch64::MLAv4i16_indexed;
5815     RC = &AArch64::FPR64RegClass;
5816     MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
5817                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
5818                                  RC);
5819     break;
5820   case MachineCombinerPattern::MULSUBv4i16_indexed_OP2:
5821     Opc = AArch64::MLSv4i16_indexed;
5822     RC = &AArch64::FPR64RegClass;
5823     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5824     break;
5825   case MachineCombinerPattern::MULSUBv8i16_indexed_OP1:
5826     Opc = AArch64::MLAv8i16_indexed;
5827     RC = &AArch64::FPR128RegClass;
5828     MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
5829                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
5830                                  RC);
5831     break;
5832   case MachineCombinerPattern::MULSUBv8i16_indexed_OP2:
5833     Opc = AArch64::MLSv8i16_indexed;
5834     RC = &AArch64::FPR128RegClass;
5835     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5836     break;
5837   case MachineCombinerPattern::MULSUBv2i32_indexed_OP1:
5838     Opc = AArch64::MLAv2i32_indexed;
5839     RC = &AArch64::FPR64RegClass;
5840     MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
5841                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
5842                                  RC);
5843     break;
5844   case MachineCombinerPattern::MULSUBv2i32_indexed_OP2:
5845     Opc = AArch64::MLSv2i32_indexed;
5846     RC = &AArch64::FPR64RegClass;
5847     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5848     break;
5849   case MachineCombinerPattern::MULSUBv4i32_indexed_OP1:
5850     Opc = AArch64::MLAv4i32_indexed;
5851     RC = &AArch64::FPR128RegClass;
5852     MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
5853                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
5854                                  RC);
5855     break;
5856   case MachineCombinerPattern::MULSUBv4i32_indexed_OP2:
5857     Opc = AArch64::MLSv4i32_indexed;
5858     RC = &AArch64::FPR128RegClass;
5859     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5860     break;
5861 
5862   // Floating Point Support
5863   case MachineCombinerPattern::FMULADDH_OP1:
5864     Opc = AArch64::FMADDHrrr;
5865     RC = &AArch64::FPR16RegClass;
5866     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5867     break;
5868   case MachineCombinerPattern::FMULADDS_OP1:
5869     Opc = AArch64::FMADDSrrr;
5870     RC = &AArch64::FPR32RegClass;
5871     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5872     break;
5873   case MachineCombinerPattern::FMULADDD_OP1:
5874     Opc = AArch64::FMADDDrrr;
5875     RC = &AArch64::FPR64RegClass;
5876     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5877     break;
5878 
5879   case MachineCombinerPattern::FMULADDH_OP2:
5880     Opc = AArch64::FMADDHrrr;
5881     RC = &AArch64::FPR16RegClass;
5882     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5883     break;
5884   case MachineCombinerPattern::FMULADDS_OP2:
5885     Opc = AArch64::FMADDSrrr;
5886     RC = &AArch64::FPR32RegClass;
5887     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5888     break;
5889   case MachineCombinerPattern::FMULADDD_OP2:
5890     Opc = AArch64::FMADDDrrr;
5891     RC = &AArch64::FPR64RegClass;
5892     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5893     break;
5894 
5895   case MachineCombinerPattern::FMLAv1i32_indexed_OP1:
5896     Opc = AArch64::FMLAv1i32_indexed;
5897     RC = &AArch64::FPR32RegClass;
5898     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5899                            FMAInstKind::Indexed);
5900     break;
5901   case MachineCombinerPattern::FMLAv1i32_indexed_OP2:
5902     Opc = AArch64::FMLAv1i32_indexed;
5903     RC = &AArch64::FPR32RegClass;
5904     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5905                            FMAInstKind::Indexed);
5906     break;
5907 
5908   case MachineCombinerPattern::FMLAv1i64_indexed_OP1:
5909     Opc = AArch64::FMLAv1i64_indexed;
5910     RC = &AArch64::FPR64RegClass;
5911     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5912                            FMAInstKind::Indexed);
5913     break;
5914   case MachineCombinerPattern::FMLAv1i64_indexed_OP2:
5915     Opc = AArch64::FMLAv1i64_indexed;
5916     RC = &AArch64::FPR64RegClass;
5917     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5918                            FMAInstKind::Indexed);
5919     break;
5920 
5921   case MachineCombinerPattern::FMLAv4i16_indexed_OP1:
5922     RC = &AArch64::FPR64RegClass;
5923     Opc = AArch64::FMLAv4i16_indexed;
5924     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5925                            FMAInstKind::Indexed);
5926     break;
5927   case MachineCombinerPattern::FMLAv4f16_OP1:
5928     RC = &AArch64::FPR64RegClass;
5929     Opc = AArch64::FMLAv4f16;
5930     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5931                            FMAInstKind::Accumulator);
5932     break;
5933   case MachineCombinerPattern::FMLAv4i16_indexed_OP2:
5934     RC = &AArch64::FPR64RegClass;
5935     Opc = AArch64::FMLAv4i16_indexed;
5936     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5937                            FMAInstKind::Indexed);
5938     break;
5939   case MachineCombinerPattern::FMLAv4f16_OP2:
5940     RC = &AArch64::FPR64RegClass;
5941     Opc = AArch64::FMLAv4f16;
5942     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5943                            FMAInstKind::Accumulator);
5944     break;
5945 
5946   case MachineCombinerPattern::FMLAv2i32_indexed_OP1:
5947   case MachineCombinerPattern::FMLAv2f32_OP1:
5948     RC = &AArch64::FPR64RegClass;
5949     if (Pattern == MachineCombinerPattern::FMLAv2i32_indexed_OP1) {
5950       Opc = AArch64::FMLAv2i32_indexed;
5951       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5952                              FMAInstKind::Indexed);
5953     } else {
5954       Opc = AArch64::FMLAv2f32;
5955       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5956                              FMAInstKind::Accumulator);
5957     }
5958     break;
5959   case MachineCombinerPattern::FMLAv2i32_indexed_OP2:
5960   case MachineCombinerPattern::FMLAv2f32_OP2:
5961     RC = &AArch64::FPR64RegClass;
5962     if (Pattern == MachineCombinerPattern::FMLAv2i32_indexed_OP2) {
5963       Opc = AArch64::FMLAv2i32_indexed;
5964       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5965                              FMAInstKind::Indexed);
5966     } else {
5967       Opc = AArch64::FMLAv2f32;
5968       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5969                              FMAInstKind::Accumulator);
5970     }
5971     break;
5972 
5973   case MachineCombinerPattern::FMLAv8i16_indexed_OP1:
5974     RC = &AArch64::FPR128RegClass;
5975     Opc = AArch64::FMLAv8i16_indexed;
5976     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5977                            FMAInstKind::Indexed);
5978     break;
5979   case MachineCombinerPattern::FMLAv8f16_OP1:
5980     RC = &AArch64::FPR128RegClass;
5981     Opc = AArch64::FMLAv8f16;
5982     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5983                            FMAInstKind::Accumulator);
5984     break;
5985   case MachineCombinerPattern::FMLAv8i16_indexed_OP2:
5986     RC = &AArch64::FPR128RegClass;
5987     Opc = AArch64::FMLAv8i16_indexed;
5988     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5989                            FMAInstKind::Indexed);
5990     break;
5991   case MachineCombinerPattern::FMLAv8f16_OP2:
5992     RC = &AArch64::FPR128RegClass;
5993     Opc = AArch64::FMLAv8f16;
5994     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5995                            FMAInstKind::Accumulator);
5996     break;
5997 
5998   case MachineCombinerPattern::FMLAv2i64_indexed_OP1:
5999   case MachineCombinerPattern::FMLAv2f64_OP1:
6000     RC = &AArch64::FPR128RegClass;
6001     if (Pattern == MachineCombinerPattern::FMLAv2i64_indexed_OP1) {
6002       Opc = AArch64::FMLAv2i64_indexed;
6003       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6004                              FMAInstKind::Indexed);
6005     } else {
6006       Opc = AArch64::FMLAv2f64;
6007       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6008                              FMAInstKind::Accumulator);
6009     }
6010     break;
6011   case MachineCombinerPattern::FMLAv2i64_indexed_OP2:
6012   case MachineCombinerPattern::FMLAv2f64_OP2:
6013     RC = &AArch64::FPR128RegClass;
6014     if (Pattern == MachineCombinerPattern::FMLAv2i64_indexed_OP2) {
6015       Opc = AArch64::FMLAv2i64_indexed;
6016       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6017                              FMAInstKind::Indexed);
6018     } else {
6019       Opc = AArch64::FMLAv2f64;
6020       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6021                              FMAInstKind::Accumulator);
6022     }
6023     break;
6024 
6025   case MachineCombinerPattern::FMLAv4i32_indexed_OP1:
6026   case MachineCombinerPattern::FMLAv4f32_OP1:
6027     RC = &AArch64::FPR128RegClass;
6028     if (Pattern == MachineCombinerPattern::FMLAv4i32_indexed_OP1) {
6029       Opc = AArch64::FMLAv4i32_indexed;
6030       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6031                              FMAInstKind::Indexed);
6032     } else {
6033       Opc = AArch64::FMLAv4f32;
6034       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6035                              FMAInstKind::Accumulator);
6036     }
6037     break;
6038 
6039   case MachineCombinerPattern::FMLAv4i32_indexed_OP2:
6040   case MachineCombinerPattern::FMLAv4f32_OP2:
6041     RC = &AArch64::FPR128RegClass;
6042     if (Pattern == MachineCombinerPattern::FMLAv4i32_indexed_OP2) {
6043       Opc = AArch64::FMLAv4i32_indexed;
6044       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6045                              FMAInstKind::Indexed);
6046     } else {
6047       Opc = AArch64::FMLAv4f32;
6048       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6049                              FMAInstKind::Accumulator);
6050     }
6051     break;
6052 
6053   case MachineCombinerPattern::FMULSUBH_OP1:
6054     Opc = AArch64::FNMSUBHrrr;
6055     RC = &AArch64::FPR16RegClass;
6056     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6057     break;
6058   case MachineCombinerPattern::FMULSUBS_OP1:
6059     Opc = AArch64::FNMSUBSrrr;
6060     RC = &AArch64::FPR32RegClass;
6061     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6062     break;
6063   case MachineCombinerPattern::FMULSUBD_OP1:
6064     Opc = AArch64::FNMSUBDrrr;
6065     RC = &AArch64::FPR64RegClass;
6066     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6067     break;
6068 
6069   case MachineCombinerPattern::FNMULSUBH_OP1:
6070     Opc = AArch64::FNMADDHrrr;
6071     RC = &AArch64::FPR16RegClass;
6072     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6073     break;
6074   case MachineCombinerPattern::FNMULSUBS_OP1:
6075     Opc = AArch64::FNMADDSrrr;
6076     RC = &AArch64::FPR32RegClass;
6077     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6078     break;
6079   case MachineCombinerPattern::FNMULSUBD_OP1:
6080     Opc = AArch64::FNMADDDrrr;
6081     RC = &AArch64::FPR64RegClass;
6082     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6083     break;
6084 
6085   case MachineCombinerPattern::FMULSUBH_OP2:
6086     Opc = AArch64::FMSUBHrrr;
6087     RC = &AArch64::FPR16RegClass;
6088     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
6089     break;
6090   case MachineCombinerPattern::FMULSUBS_OP2:
6091     Opc = AArch64::FMSUBSrrr;
6092     RC = &AArch64::FPR32RegClass;
6093     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
6094     break;
6095   case MachineCombinerPattern::FMULSUBD_OP2:
6096     Opc = AArch64::FMSUBDrrr;
6097     RC = &AArch64::FPR64RegClass;
6098     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
6099     break;
6100 
6101   case MachineCombinerPattern::FMLSv1i32_indexed_OP2:
6102     Opc = AArch64::FMLSv1i32_indexed;
6103     RC = &AArch64::FPR32RegClass;
6104     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6105                            FMAInstKind::Indexed);
6106     break;
6107 
6108   case MachineCombinerPattern::FMLSv1i64_indexed_OP2:
6109     Opc = AArch64::FMLSv1i64_indexed;
6110     RC = &AArch64::FPR64RegClass;
6111     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6112                            FMAInstKind::Indexed);
6113     break;
6114 
6115   case MachineCombinerPattern::FMLSv4f16_OP1:
6116   case MachineCombinerPattern::FMLSv4i16_indexed_OP1: {
6117     RC = &AArch64::FPR64RegClass;
6118     Register NewVR = MRI.createVirtualRegister(RC);
6119     MachineInstrBuilder MIB1 =
6120         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv4f16), NewVR)
6121             .add(Root.getOperand(2));
6122     InsInstrs.push_back(MIB1);
6123     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6124     if (Pattern == MachineCombinerPattern::FMLSv4f16_OP1) {
6125       Opc = AArch64::FMLAv4f16;
6126       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6127                              FMAInstKind::Accumulator, &NewVR);
6128     } else {
6129       Opc = AArch64::FMLAv4i16_indexed;
6130       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6131                              FMAInstKind::Indexed, &NewVR);
6132     }
6133     break;
6134   }
6135   case MachineCombinerPattern::FMLSv4f16_OP2:
6136     RC = &AArch64::FPR64RegClass;
6137     Opc = AArch64::FMLSv4f16;
6138     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6139                            FMAInstKind::Accumulator);
6140     break;
6141   case MachineCombinerPattern::FMLSv4i16_indexed_OP2:
6142     RC = &AArch64::FPR64RegClass;
6143     Opc = AArch64::FMLSv4i16_indexed;
6144     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6145                            FMAInstKind::Indexed);
6146     break;
6147 
6148   case MachineCombinerPattern::FMLSv2f32_OP2:
6149   case MachineCombinerPattern::FMLSv2i32_indexed_OP2:
6150     RC = &AArch64::FPR64RegClass;
6151     if (Pattern == MachineCombinerPattern::FMLSv2i32_indexed_OP2) {
6152       Opc = AArch64::FMLSv2i32_indexed;
6153       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6154                              FMAInstKind::Indexed);
6155     } else {
6156       Opc = AArch64::FMLSv2f32;
6157       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6158                              FMAInstKind::Accumulator);
6159     }
6160     break;
6161 
6162   case MachineCombinerPattern::FMLSv8f16_OP1:
6163   case MachineCombinerPattern::FMLSv8i16_indexed_OP1: {
6164     RC = &AArch64::FPR128RegClass;
6165     Register NewVR = MRI.createVirtualRegister(RC);
6166     MachineInstrBuilder MIB1 =
6167         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv8f16), NewVR)
6168             .add(Root.getOperand(2));
6169     InsInstrs.push_back(MIB1);
6170     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6171     if (Pattern == MachineCombinerPattern::FMLSv8f16_OP1) {
6172       Opc = AArch64::FMLAv8f16;
6173       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6174                              FMAInstKind::Accumulator, &NewVR);
6175     } else {
6176       Opc = AArch64::FMLAv8i16_indexed;
6177       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6178                              FMAInstKind::Indexed, &NewVR);
6179     }
6180     break;
6181   }
6182   case MachineCombinerPattern::FMLSv8f16_OP2:
6183     RC = &AArch64::FPR128RegClass;
6184     Opc = AArch64::FMLSv8f16;
6185     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6186                            FMAInstKind::Accumulator);
6187     break;
6188   case MachineCombinerPattern::FMLSv8i16_indexed_OP2:
6189     RC = &AArch64::FPR128RegClass;
6190     Opc = AArch64::FMLSv8i16_indexed;
6191     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6192                            FMAInstKind::Indexed);
6193     break;
6194 
6195   case MachineCombinerPattern::FMLSv2f64_OP2:
6196   case MachineCombinerPattern::FMLSv2i64_indexed_OP2:
6197     RC = &AArch64::FPR128RegClass;
6198     if (Pattern == MachineCombinerPattern::FMLSv2i64_indexed_OP2) {
6199       Opc = AArch64::FMLSv2i64_indexed;
6200       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6201                              FMAInstKind::Indexed);
6202     } else {
6203       Opc = AArch64::FMLSv2f64;
6204       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6205                              FMAInstKind::Accumulator);
6206     }
6207     break;
6208 
6209   case MachineCombinerPattern::FMLSv4f32_OP2:
6210   case MachineCombinerPattern::FMLSv4i32_indexed_OP2:
6211     RC = &AArch64::FPR128RegClass;
6212     if (Pattern == MachineCombinerPattern::FMLSv4i32_indexed_OP2) {
6213       Opc = AArch64::FMLSv4i32_indexed;
6214       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6215                              FMAInstKind::Indexed);
6216     } else {
6217       Opc = AArch64::FMLSv4f32;
6218       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6219                              FMAInstKind::Accumulator);
6220     }
6221     break;
6222   case MachineCombinerPattern::FMLSv2f32_OP1:
6223   case MachineCombinerPattern::FMLSv2i32_indexed_OP1: {
6224     RC = &AArch64::FPR64RegClass;
6225     Register NewVR = MRI.createVirtualRegister(RC);
6226     MachineInstrBuilder MIB1 =
6227         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv2f32), NewVR)
6228             .add(Root.getOperand(2));
6229     InsInstrs.push_back(MIB1);
6230     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6231     if (Pattern == MachineCombinerPattern::FMLSv2i32_indexed_OP1) {
6232       Opc = AArch64::FMLAv2i32_indexed;
6233       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6234                              FMAInstKind::Indexed, &NewVR);
6235     } else {
6236       Opc = AArch64::FMLAv2f32;
6237       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6238                              FMAInstKind::Accumulator, &NewVR);
6239     }
6240     break;
6241   }
6242   case MachineCombinerPattern::FMLSv4f32_OP1:
6243   case MachineCombinerPattern::FMLSv4i32_indexed_OP1: {
6244     RC = &AArch64::FPR128RegClass;
6245     Register NewVR = MRI.createVirtualRegister(RC);
6246     MachineInstrBuilder MIB1 =
6247         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv4f32), NewVR)
6248             .add(Root.getOperand(2));
6249     InsInstrs.push_back(MIB1);
6250     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6251     if (Pattern == MachineCombinerPattern::FMLSv4i32_indexed_OP1) {
6252       Opc = AArch64::FMLAv4i32_indexed;
6253       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6254                              FMAInstKind::Indexed, &NewVR);
6255     } else {
6256       Opc = AArch64::FMLAv4f32;
6257       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6258                              FMAInstKind::Accumulator, &NewVR);
6259     }
6260     break;
6261   }
6262   case MachineCombinerPattern::FMLSv2f64_OP1:
6263   case MachineCombinerPattern::FMLSv2i64_indexed_OP1: {
6264     RC = &AArch64::FPR128RegClass;
6265     Register NewVR = MRI.createVirtualRegister(RC);
6266     MachineInstrBuilder MIB1 =
6267         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv2f64), NewVR)
6268             .add(Root.getOperand(2));
6269     InsInstrs.push_back(MIB1);
6270     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6271     if (Pattern == MachineCombinerPattern::FMLSv2i64_indexed_OP1) {
6272       Opc = AArch64::FMLAv2i64_indexed;
6273       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6274                              FMAInstKind::Indexed, &NewVR);
6275     } else {
6276       Opc = AArch64::FMLAv2f64;
6277       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6278                              FMAInstKind::Accumulator, &NewVR);
6279     }
6280     break;
6281   }
6282   case MachineCombinerPattern::FMULv2i32_indexed_OP1:
6283   case MachineCombinerPattern::FMULv2i32_indexed_OP2: {
6284     unsigned IdxDupOp =
6285         (Pattern == MachineCombinerPattern::FMULv2i32_indexed_OP1) ? 1 : 2;
6286     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
6287                        &AArch64::FPR128RegClass, MRI);
6288     break;
6289   }
6290   case MachineCombinerPattern::FMULv2i64_indexed_OP1:
6291   case MachineCombinerPattern::FMULv2i64_indexed_OP2: {
6292     unsigned IdxDupOp =
6293         (Pattern == MachineCombinerPattern::FMULv2i64_indexed_OP1) ? 1 : 2;
6294     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
6295                        &AArch64::FPR128RegClass, MRI);
6296     break;
6297   }
6298   case MachineCombinerPattern::FMULv4i16_indexed_OP1:
6299   case MachineCombinerPattern::FMULv4i16_indexed_OP2: {
6300     unsigned IdxDupOp =
6301         (Pattern == MachineCombinerPattern::FMULv4i16_indexed_OP1) ? 1 : 2;
6302     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
6303                        &AArch64::FPR128_loRegClass, MRI);
6304     break;
6305   }
6306   case MachineCombinerPattern::FMULv4i32_indexed_OP1:
6307   case MachineCombinerPattern::FMULv4i32_indexed_OP2: {
6308     unsigned IdxDupOp =
6309         (Pattern == MachineCombinerPattern::FMULv4i32_indexed_OP1) ? 1 : 2;
6310     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
6311                        &AArch64::FPR128RegClass, MRI);
6312     break;
6313   }
6314   case MachineCombinerPattern::FMULv8i16_indexed_OP1:
6315   case MachineCombinerPattern::FMULv8i16_indexed_OP2: {
6316     unsigned IdxDupOp =
6317         (Pattern == MachineCombinerPattern::FMULv8i16_indexed_OP1) ? 1 : 2;
6318     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
6319                        &AArch64::FPR128_loRegClass, MRI);
6320     break;
6321   }
6322   } // end switch (Pattern)
6323   // Record MUL and ADD/SUB for deletion
6324   if (MUL)
6325     DelInstrs.push_back(MUL);
6326   DelInstrs.push_back(&Root);
6327 
6328   // Set the flags on the inserted instructions to be the merged flags of the
6329   // instructions that we have combined.
6330   uint16_t Flags = Root.getFlags();
6331   if (MUL)
6332     Flags = Root.mergeFlagsWith(*MUL);
6333   for (auto *MI : InsInstrs)
6334     MI->setFlags(Flags);
6335 }
6336 
6337 /// Replace csincr-branch sequence by simple conditional branch
6338 ///
6339 /// Examples:
6340 /// 1. \code
6341 ///   csinc  w9, wzr, wzr, <condition code>
6342 ///   tbnz   w9, #0, 0x44
6343 ///    \endcode
6344 /// to
6345 ///    \code
6346 ///   b.<inverted condition code>
6347 ///    \endcode
6348 ///
6349 /// 2. \code
6350 ///   csinc w9, wzr, wzr, <condition code>
6351 ///   tbz   w9, #0, 0x44
6352 ///    \endcode
6353 /// to
6354 ///    \code
6355 ///   b.<condition code>
6356 ///    \endcode
6357 ///
6358 /// Replace compare and branch sequence by TBZ/TBNZ instruction when the
6359 /// compare's constant operand is power of 2.
6360 ///
6361 /// Examples:
6362 ///    \code
6363 ///   and  w8, w8, #0x400
6364 ///   cbnz w8, L1
6365 ///    \endcode
6366 /// to
6367 ///    \code
6368 ///   tbnz w8, #10, L1
6369 ///    \endcode
6370 ///
6371 /// \param  MI Conditional Branch
6372 /// \return True when the simple conditional branch is generated
6373 ///
6374 bool AArch64InstrInfo::optimizeCondBranch(MachineInstr &MI) const {
6375   bool IsNegativeBranch = false;
6376   bool IsTestAndBranch = false;
6377   unsigned TargetBBInMI = 0;
6378   switch (MI.getOpcode()) {
6379   default:
6380     llvm_unreachable("Unknown branch instruction?");
6381   case AArch64::Bcc:
6382     return false;
6383   case AArch64::CBZW:
6384   case AArch64::CBZX:
6385     TargetBBInMI = 1;
6386     break;
6387   case AArch64::CBNZW:
6388   case AArch64::CBNZX:
6389     TargetBBInMI = 1;
6390     IsNegativeBranch = true;
6391     break;
6392   case AArch64::TBZW:
6393   case AArch64::TBZX:
6394     TargetBBInMI = 2;
6395     IsTestAndBranch = true;
6396     break;
6397   case AArch64::TBNZW:
6398   case AArch64::TBNZX:
6399     TargetBBInMI = 2;
6400     IsNegativeBranch = true;
6401     IsTestAndBranch = true;
6402     break;
6403   }
6404   // So we increment a zero register and test for bits other
6405   // than bit 0? Conservatively bail out in case the verifier
6406   // missed this case.
6407   if (IsTestAndBranch && MI.getOperand(1).getImm())
6408     return false;
6409 
6410   // Find Definition.
6411   assert(MI.getParent() && "Incomplete machine instruciton\n");
6412   MachineBasicBlock *MBB = MI.getParent();
6413   MachineFunction *MF = MBB->getParent();
6414   MachineRegisterInfo *MRI = &MF->getRegInfo();
6415   Register VReg = MI.getOperand(0).getReg();
6416   if (!Register::isVirtualRegister(VReg))
6417     return false;
6418 
6419   MachineInstr *DefMI = MRI->getVRegDef(VReg);
6420 
6421   // Look through COPY instructions to find definition.
6422   while (DefMI->isCopy()) {
6423     Register CopyVReg = DefMI->getOperand(1).getReg();
6424     if (!MRI->hasOneNonDBGUse(CopyVReg))
6425       return false;
6426     if (!MRI->hasOneDef(CopyVReg))
6427       return false;
6428     DefMI = MRI->getVRegDef(CopyVReg);
6429   }
6430 
6431   switch (DefMI->getOpcode()) {
6432   default:
6433     return false;
6434   // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
6435   case AArch64::ANDWri:
6436   case AArch64::ANDXri: {
6437     if (IsTestAndBranch)
6438       return false;
6439     if (DefMI->getParent() != MBB)
6440       return false;
6441     if (!MRI->hasOneNonDBGUse(VReg))
6442       return false;
6443 
6444     bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
6445     uint64_t Mask = AArch64_AM::decodeLogicalImmediate(
6446         DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
6447     if (!isPowerOf2_64(Mask))
6448       return false;
6449 
6450     MachineOperand &MO = DefMI->getOperand(1);
6451     Register NewReg = MO.getReg();
6452     if (!Register::isVirtualRegister(NewReg))
6453       return false;
6454 
6455     assert(!MRI->def_empty(NewReg) && "Register must be defined.");
6456 
6457     MachineBasicBlock &RefToMBB = *MBB;
6458     MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
6459     DebugLoc DL = MI.getDebugLoc();
6460     unsigned Imm = Log2_64(Mask);
6461     unsigned Opc = (Imm < 32)
6462                        ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
6463                        : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
6464     MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
6465                               .addReg(NewReg)
6466                               .addImm(Imm)
6467                               .addMBB(TBB);
6468     // Register lives on to the CBZ now.
6469     MO.setIsKill(false);
6470 
6471     // For immediate smaller than 32, we need to use the 32-bit
6472     // variant (W) in all cases. Indeed the 64-bit variant does not
6473     // allow to encode them.
6474     // Therefore, if the input register is 64-bit, we need to take the
6475     // 32-bit sub-part.
6476     if (!Is32Bit && Imm < 32)
6477       NewMI->getOperand(0).setSubReg(AArch64::sub_32);
6478     MI.eraseFromParent();
6479     return true;
6480   }
6481   // Look for CSINC
6482   case AArch64::CSINCWr:
6483   case AArch64::CSINCXr: {
6484     if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
6485           DefMI->getOperand(2).getReg() == AArch64::WZR) &&
6486         !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
6487           DefMI->getOperand(2).getReg() == AArch64::XZR))
6488       return false;
6489 
6490     if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) != -1)
6491       return false;
6492 
6493     AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
6494     // Convert only when the condition code is not modified between
6495     // the CSINC and the branch. The CC may be used by other
6496     // instructions in between.
6497     if (areCFlagsAccessedBetweenInstrs(DefMI, MI, &getRegisterInfo(), AK_Write))
6498       return false;
6499     MachineBasicBlock &RefToMBB = *MBB;
6500     MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
6501     DebugLoc DL = MI.getDebugLoc();
6502     if (IsNegativeBranch)
6503       CC = AArch64CC::getInvertedCondCode(CC);
6504     BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
6505     MI.eraseFromParent();
6506     return true;
6507   }
6508   }
6509 }
6510 
6511 std::pair<unsigned, unsigned>
6512 AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
6513   const unsigned Mask = AArch64II::MO_FRAGMENT;
6514   return std::make_pair(TF & Mask, TF & ~Mask);
6515 }
6516 
6517 ArrayRef<std::pair<unsigned, const char *>>
6518 AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
6519   using namespace AArch64II;
6520 
6521   static const std::pair<unsigned, const char *> TargetFlags[] = {
6522       {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
6523       {MO_G3, "aarch64-g3"},     {MO_G2, "aarch64-g2"},
6524       {MO_G1, "aarch64-g1"},     {MO_G0, "aarch64-g0"},
6525       {MO_HI12, "aarch64-hi12"}};
6526   return makeArrayRef(TargetFlags);
6527 }
6528 
6529 ArrayRef<std::pair<unsigned, const char *>>
6530 AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
6531   using namespace AArch64II;
6532 
6533   static const std::pair<unsigned, const char *> TargetFlags[] = {
6534       {MO_COFFSTUB, "aarch64-coffstub"},
6535       {MO_GOT, "aarch64-got"},
6536       {MO_NC, "aarch64-nc"},
6537       {MO_S, "aarch64-s"},
6538       {MO_TLS, "aarch64-tls"},
6539       {MO_DLLIMPORT, "aarch64-dllimport"},
6540       {MO_PREL, "aarch64-prel"},
6541       {MO_TAGGED, "aarch64-tagged"}};
6542   return makeArrayRef(TargetFlags);
6543 }
6544 
6545 ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
6546 AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
6547   static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
6548       {{MOSuppressPair, "aarch64-suppress-pair"},
6549        {MOStridedAccess, "aarch64-strided-access"}};
6550   return makeArrayRef(TargetFlags);
6551 }
6552 
6553 /// Constants defining how certain sequences should be outlined.
6554 /// This encompasses how an outlined function should be called, and what kind of
6555 /// frame should be emitted for that outlined function.
6556 ///
6557 /// \p MachineOutlinerDefault implies that the function should be called with
6558 /// a save and restore of LR to the stack.
6559 ///
6560 /// That is,
6561 ///
6562 /// I1     Save LR                    OUTLINED_FUNCTION:
6563 /// I2 --> BL OUTLINED_FUNCTION       I1
6564 /// I3     Restore LR                 I2
6565 ///                                   I3
6566 ///                                   RET
6567 ///
6568 /// * Call construction overhead: 3 (save + BL + restore)
6569 /// * Frame construction overhead: 1 (ret)
6570 /// * Requires stack fixups? Yes
6571 ///
6572 /// \p MachineOutlinerTailCall implies that the function is being created from
6573 /// a sequence of instructions ending in a return.
6574 ///
6575 /// That is,
6576 ///
6577 /// I1                             OUTLINED_FUNCTION:
6578 /// I2 --> B OUTLINED_FUNCTION     I1
6579 /// RET                            I2
6580 ///                                RET
6581 ///
6582 /// * Call construction overhead: 1 (B)
6583 /// * Frame construction overhead: 0 (Return included in sequence)
6584 /// * Requires stack fixups? No
6585 ///
6586 /// \p MachineOutlinerNoLRSave implies that the function should be called using
6587 /// a BL instruction, but doesn't require LR to be saved and restored. This
6588 /// happens when LR is known to be dead.
6589 ///
6590 /// That is,
6591 ///
6592 /// I1                                OUTLINED_FUNCTION:
6593 /// I2 --> BL OUTLINED_FUNCTION       I1
6594 /// I3                                I2
6595 ///                                   I3
6596 ///                                   RET
6597 ///
6598 /// * Call construction overhead: 1 (BL)
6599 /// * Frame construction overhead: 1 (RET)
6600 /// * Requires stack fixups? No
6601 ///
6602 /// \p MachineOutlinerThunk implies that the function is being created from
6603 /// a sequence of instructions ending in a call. The outlined function is
6604 /// called with a BL instruction, and the outlined function tail-calls the
6605 /// original call destination.
6606 ///
6607 /// That is,
6608 ///
6609 /// I1                                OUTLINED_FUNCTION:
6610 /// I2 --> BL OUTLINED_FUNCTION       I1
6611 /// BL f                              I2
6612 ///                                   B f
6613 /// * Call construction overhead: 1 (BL)
6614 /// * Frame construction overhead: 0
6615 /// * Requires stack fixups? No
6616 ///
6617 /// \p MachineOutlinerRegSave implies that the function should be called with a
6618 /// save and restore of LR to an available register. This allows us to avoid
6619 /// stack fixups. Note that this outlining variant is compatible with the
6620 /// NoLRSave case.
6621 ///
6622 /// That is,
6623 ///
6624 /// I1     Save LR                    OUTLINED_FUNCTION:
6625 /// I2 --> BL OUTLINED_FUNCTION       I1
6626 /// I3     Restore LR                 I2
6627 ///                                   I3
6628 ///                                   RET
6629 ///
6630 /// * Call construction overhead: 3 (save + BL + restore)
6631 /// * Frame construction overhead: 1 (ret)
6632 /// * Requires stack fixups? No
6633 enum MachineOutlinerClass {
6634   MachineOutlinerDefault,  /// Emit a save, restore, call, and return.
6635   MachineOutlinerTailCall, /// Only emit a branch.
6636   MachineOutlinerNoLRSave, /// Emit a call and return.
6637   MachineOutlinerThunk,    /// Emit a call and tail-call.
6638   MachineOutlinerRegSave   /// Same as default, but save to a register.
6639 };
6640 
6641 enum MachineOutlinerMBBFlags {
6642   LRUnavailableSomewhere = 0x2,
6643   HasCalls = 0x4,
6644   UnsafeRegsDead = 0x8
6645 };
6646 
6647 Register
6648 AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
6649   MachineFunction *MF = C.getMF();
6650   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
6651   const AArch64RegisterInfo *ARI =
6652       static_cast<const AArch64RegisterInfo *>(&TRI);
6653   // Check if there is an available register across the sequence that we can
6654   // use.
6655   for (unsigned Reg : AArch64::GPR64RegClass) {
6656     if (!ARI->isReservedReg(*MF, Reg) &&
6657         Reg != AArch64::LR &&  // LR is not reserved, but don't use it.
6658         Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
6659         Reg != AArch64::X17 && // Ditto for X17.
6660         C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
6661         C.isAvailableInsideSeq(Reg, TRI))
6662       return Reg;
6663   }
6664   return Register();
6665 }
6666 
6667 static bool
6668 outliningCandidatesSigningScopeConsensus(const outliner::Candidate &a,
6669                                          const outliner::Candidate &b) {
6670   const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
6671   const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
6672 
6673   return MFIa->shouldSignReturnAddress(false) == MFIb->shouldSignReturnAddress(false) &&
6674          MFIa->shouldSignReturnAddress(true) == MFIb->shouldSignReturnAddress(true);
6675 }
6676 
6677 static bool
6678 outliningCandidatesSigningKeyConsensus(const outliner::Candidate &a,
6679                                        const outliner::Candidate &b) {
6680   const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
6681   const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
6682 
6683   return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
6684 }
6685 
6686 static bool outliningCandidatesV8_3OpsConsensus(const outliner::Candidate &a,
6687                                                 const outliner::Candidate &b) {
6688   const AArch64Subtarget &SubtargetA =
6689       a.getMF()->getSubtarget<AArch64Subtarget>();
6690   const AArch64Subtarget &SubtargetB =
6691       b.getMF()->getSubtarget<AArch64Subtarget>();
6692   return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
6693 }
6694 
6695 outliner::OutlinedFunction AArch64InstrInfo::getOutliningCandidateInfo(
6696     std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
6697   outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
6698   unsigned SequenceSize =
6699       std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0,
6700                       [this](unsigned Sum, const MachineInstr &MI) {
6701                         return Sum + getInstSizeInBytes(MI);
6702                       });
6703   unsigned NumBytesToCreateFrame = 0;
6704 
6705   // We only allow outlining for functions having exactly matching return
6706   // address signing attributes, i.e., all share the same value for the
6707   // attribute "sign-return-address" and all share the same type of key they
6708   // are signed with.
6709   // Additionally we require all functions to simultaniously either support
6710   // v8.3a features or not. Otherwise an outlined function could get signed
6711   // using dedicated v8.3 instructions and a call from a function that doesn't
6712   // support v8.3 instructions would therefore be invalid.
6713   if (std::adjacent_find(
6714           RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
6715           [](const outliner::Candidate &a, const outliner::Candidate &b) {
6716             // Return true if a and b are non-equal w.r.t. return address
6717             // signing or support of v8.3a features
6718             if (outliningCandidatesSigningScopeConsensus(a, b) &&
6719                 outliningCandidatesSigningKeyConsensus(a, b) &&
6720                 outliningCandidatesV8_3OpsConsensus(a, b)) {
6721               return false;
6722             }
6723             return true;
6724           }) != RepeatedSequenceLocs.end()) {
6725     return outliner::OutlinedFunction();
6726   }
6727 
6728   // Since at this point all candidates agree on their return address signing
6729   // picking just one is fine. If the candidate functions potentially sign their
6730   // return addresses, the outlined function should do the same. Note that in
6731   // the case of "sign-return-address"="non-leaf" this is an assumption: It is
6732   // not certainly true that the outlined function will have to sign its return
6733   // address but this decision is made later, when the decision to outline
6734   // has already been made.
6735   // The same holds for the number of additional instructions we need: On
6736   // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
6737   // necessary. However, at this point we don't know if the outlined function
6738   // will have a RET instruction so we assume the worst.
6739   const TargetRegisterInfo &TRI = getRegisterInfo();
6740   if (FirstCand.getMF()
6741           ->getInfo<AArch64FunctionInfo>()
6742           ->shouldSignReturnAddress(true)) {
6743     // One PAC and one AUT instructions
6744     NumBytesToCreateFrame += 8;
6745 
6746     // We have to check if sp modifying instructions would get outlined.
6747     // If so we only allow outlining if sp is unchanged overall, so matching
6748     // sub and add instructions are okay to outline, all other sp modifications
6749     // are not
6750     auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
6751       int SPValue = 0;
6752       MachineBasicBlock::iterator MBBI = C.front();
6753       for (;;) {
6754         if (MBBI->modifiesRegister(AArch64::SP, &TRI)) {
6755           switch (MBBI->getOpcode()) {
6756           case AArch64::ADDXri:
6757           case AArch64::ADDWri:
6758             assert(MBBI->getNumOperands() == 4 && "Wrong number of operands");
6759             assert(MBBI->getOperand(2).isImm() &&
6760                    "Expected operand to be immediate");
6761             assert(MBBI->getOperand(1).isReg() &&
6762                    "Expected operand to be a register");
6763             // Check if the add just increments sp. If so, we search for
6764             // matching sub instructions that decrement sp. If not, the
6765             // modification is illegal
6766             if (MBBI->getOperand(1).getReg() == AArch64::SP)
6767               SPValue += MBBI->getOperand(2).getImm();
6768             else
6769               return true;
6770             break;
6771           case AArch64::SUBXri:
6772           case AArch64::SUBWri:
6773             assert(MBBI->getNumOperands() == 4 && "Wrong number of operands");
6774             assert(MBBI->getOperand(2).isImm() &&
6775                    "Expected operand to be immediate");
6776             assert(MBBI->getOperand(1).isReg() &&
6777                    "Expected operand to be a register");
6778             // Check if the sub just decrements sp. If so, we search for
6779             // matching add instructions that increment sp. If not, the
6780             // modification is illegal
6781             if (MBBI->getOperand(1).getReg() == AArch64::SP)
6782               SPValue -= MBBI->getOperand(2).getImm();
6783             else
6784               return true;
6785             break;
6786           default:
6787             return true;
6788           }
6789         }
6790         if (MBBI == C.back())
6791           break;
6792         ++MBBI;
6793       }
6794       if (SPValue)
6795         return true;
6796       return false;
6797     };
6798     // Remove candidates with illegal stack modifying instructions
6799     llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification);
6800 
6801     // If the sequence doesn't have enough candidates left, then we're done.
6802     if (RepeatedSequenceLocs.size() < 2)
6803       return outliner::OutlinedFunction();
6804   }
6805 
6806   // Properties about candidate MBBs that hold for all of them.
6807   unsigned FlagsSetInAll = 0xF;
6808 
6809   // Compute liveness information for each candidate, and set FlagsSetInAll.
6810   std::for_each(RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
6811                 [&FlagsSetInAll](outliner::Candidate &C) {
6812                   FlagsSetInAll &= C.Flags;
6813                 });
6814 
6815   // According to the AArch64 Procedure Call Standard, the following are
6816   // undefined on entry/exit from a function call:
6817   //
6818   // * Registers x16, x17, (and thus w16, w17)
6819   // * Condition codes (and thus the NZCV register)
6820   //
6821   // Because if this, we can't outline any sequence of instructions where
6822   // one
6823   // of these registers is live into/across it. Thus, we need to delete
6824   // those
6825   // candidates.
6826   auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) {
6827     // If the unsafe registers in this block are all dead, then we don't need
6828     // to compute liveness here.
6829     if (C.Flags & UnsafeRegsDead)
6830       return false;
6831     return C.isAnyUnavailableAcrossOrOutOfSeq(
6832         {AArch64::W16, AArch64::W17, AArch64::NZCV}, TRI);
6833   };
6834 
6835   // Are there any candidates where those registers are live?
6836   if (!(FlagsSetInAll & UnsafeRegsDead)) {
6837     // Erase every candidate that violates the restrictions above. (It could be
6838     // true that we have viable candidates, so it's not worth bailing out in
6839     // the case that, say, 1 out of 20 candidates violate the restructions.)
6840     llvm::erase_if(RepeatedSequenceLocs, CantGuaranteeValueAcrossCall);
6841 
6842     // If the sequence doesn't have enough candidates left, then we're done.
6843     if (RepeatedSequenceLocs.size() < 2)
6844       return outliner::OutlinedFunction();
6845   }
6846 
6847   // At this point, we have only "safe" candidates to outline. Figure out
6848   // frame + call instruction information.
6849 
6850   unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode();
6851 
6852   // Helper lambda which sets call information for every candidate.
6853   auto SetCandidateCallInfo =
6854       [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
6855         for (outliner::Candidate &C : RepeatedSequenceLocs)
6856           C.setCallInfo(CallID, NumBytesForCall);
6857       };
6858 
6859   unsigned FrameID = MachineOutlinerDefault;
6860   NumBytesToCreateFrame += 4;
6861 
6862   bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
6863     return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
6864   });
6865 
6866   // We check to see if CFI Instructions are present, and if they are
6867   // we find the number of CFI Instructions in the candidates.
6868   unsigned CFICount = 0;
6869   MachineBasicBlock::iterator MBBI = RepeatedSequenceLocs[0].front();
6870   for (unsigned Loc = RepeatedSequenceLocs[0].getStartIdx();
6871        Loc < RepeatedSequenceLocs[0].getEndIdx() + 1; Loc++) {
6872     if (MBBI->isCFIInstruction())
6873       CFICount++;
6874     MBBI++;
6875   }
6876 
6877   // We compare the number of found CFI Instructions to  the number of CFI
6878   // instructions in the parent function for each candidate.  We must check this
6879   // since if we outline one of the CFI instructions in a function, we have to
6880   // outline them all for correctness. If we do not, the address offsets will be
6881   // incorrect between the two sections of the program.
6882   for (outliner::Candidate &C : RepeatedSequenceLocs) {
6883     std::vector<MCCFIInstruction> CFIInstructions =
6884         C.getMF()->getFrameInstructions();
6885 
6886     if (CFICount > 0 && CFICount != CFIInstructions.size())
6887       return outliner::OutlinedFunction();
6888   }
6889 
6890   // Returns true if an instructions is safe to fix up, false otherwise.
6891   auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
6892     if (MI.isCall())
6893       return true;
6894 
6895     if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
6896         !MI.readsRegister(AArch64::SP, &TRI))
6897       return true;
6898 
6899     // Any modification of SP will break our code to save/restore LR.
6900     // FIXME: We could handle some instructions which add a constant
6901     // offset to SP, with a bit more work.
6902     if (MI.modifiesRegister(AArch64::SP, &TRI))
6903       return false;
6904 
6905     // At this point, we have a stack instruction that we might need to
6906     // fix up. We'll handle it if it's a load or store.
6907     if (MI.mayLoadOrStore()) {
6908       const MachineOperand *Base; // Filled with the base operand of MI.
6909       int64_t Offset;             // Filled with the offset of MI.
6910       bool OffsetIsScalable;
6911 
6912       // Does it allow us to offset the base operand and is the base the
6913       // register SP?
6914       if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable, &TRI) ||
6915           !Base->isReg() || Base->getReg() != AArch64::SP)
6916         return false;
6917 
6918       // Fixe-up code below assumes bytes.
6919       if (OffsetIsScalable)
6920         return false;
6921 
6922       // Find the minimum/maximum offset for this instruction and check
6923       // if fixing it up would be in range.
6924       int64_t MinOffset,
6925           MaxOffset;  // Unscaled offsets for the instruction.
6926       TypeSize Scale(0U, false); // The scale to multiply the offsets by.
6927       unsigned DummyWidth;
6928       getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
6929 
6930       Offset += 16; // Update the offset to what it would be if we outlined.
6931       if (Offset < MinOffset * (int64_t)Scale.getFixedSize() ||
6932           Offset > MaxOffset * (int64_t)Scale.getFixedSize())
6933         return false;
6934 
6935       // It's in range, so we can outline it.
6936       return true;
6937     }
6938 
6939     // FIXME: Add handling for instructions like "add x0, sp, #8".
6940 
6941     // We can't fix it up, so don't outline it.
6942     return false;
6943   };
6944 
6945   // True if it's possible to fix up each stack instruction in this sequence.
6946   // Important for frames/call variants that modify the stack.
6947   bool AllStackInstrsSafe = std::all_of(
6948       FirstCand.front(), std::next(FirstCand.back()), IsSafeToFixup);
6949 
6950   // If the last instruction in any candidate is a terminator, then we should
6951   // tail call all of the candidates.
6952   if (RepeatedSequenceLocs[0].back()->isTerminator()) {
6953     FrameID = MachineOutlinerTailCall;
6954     NumBytesToCreateFrame = 0;
6955     SetCandidateCallInfo(MachineOutlinerTailCall, 4);
6956   }
6957 
6958   else if (LastInstrOpcode == AArch64::BL ||
6959            ((LastInstrOpcode == AArch64::BLR ||
6960              LastInstrOpcode == AArch64::BLRNoIP) &&
6961             !HasBTI)) {
6962     // FIXME: Do we need to check if the code after this uses the value of LR?
6963     FrameID = MachineOutlinerThunk;
6964     NumBytesToCreateFrame = 0;
6965     SetCandidateCallInfo(MachineOutlinerThunk, 4);
6966   }
6967 
6968   else {
6969     // We need to decide how to emit calls + frames. We can always emit the same
6970     // frame if we don't need to save to the stack. If we have to save to the
6971     // stack, then we need a different frame.
6972     unsigned NumBytesNoStackCalls = 0;
6973     std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
6974 
6975     // Check if we have to save LR.
6976     for (outliner::Candidate &C : RepeatedSequenceLocs) {
6977       // If we have a noreturn caller, then we're going to be conservative and
6978       // say that we have to save LR. If we don't have a ret at the end of the
6979       // block, then we can't reason about liveness accurately.
6980       //
6981       // FIXME: We can probably do better than always disabling this in
6982       // noreturn functions by fixing up the liveness info.
6983       bool IsNoReturn =
6984           C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
6985 
6986       // Is LR available? If so, we don't need a save.
6987       if (C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) && !IsNoReturn) {
6988         NumBytesNoStackCalls += 4;
6989         C.setCallInfo(MachineOutlinerNoLRSave, 4);
6990         CandidatesWithoutStackFixups.push_back(C);
6991       }
6992 
6993       // Is an unused register available? If so, we won't modify the stack, so
6994       // we can outline with the same frame type as those that don't save LR.
6995       else if (findRegisterToSaveLRTo(C)) {
6996         NumBytesNoStackCalls += 12;
6997         C.setCallInfo(MachineOutlinerRegSave, 12);
6998         CandidatesWithoutStackFixups.push_back(C);
6999       }
7000 
7001       // Is SP used in the sequence at all? If not, we don't have to modify
7002       // the stack, so we are guaranteed to get the same frame.
7003       else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
7004         NumBytesNoStackCalls += 12;
7005         C.setCallInfo(MachineOutlinerDefault, 12);
7006         CandidatesWithoutStackFixups.push_back(C);
7007       }
7008 
7009       // If we outline this, we need to modify the stack. Pretend we don't
7010       // outline this by saving all of its bytes.
7011       else {
7012         NumBytesNoStackCalls += SequenceSize;
7013       }
7014     }
7015 
7016     // If there are no places where we have to save LR, then note that we
7017     // don't have to update the stack. Otherwise, give every candidate the
7018     // default call type, as long as it's safe to do so.
7019     if (!AllStackInstrsSafe ||
7020         NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
7021       RepeatedSequenceLocs = CandidatesWithoutStackFixups;
7022       FrameID = MachineOutlinerNoLRSave;
7023     } else {
7024       SetCandidateCallInfo(MachineOutlinerDefault, 12);
7025 
7026       // Bugzilla ID: 46767
7027       // TODO: Check if fixing up the stack more than once is safe so we can
7028       // outline these.
7029       //
7030       // An outline resulting in a caller that requires stack fixups at the
7031       // callsite to a callee that also requires stack fixups can happen when
7032       // there are no available registers at the candidate callsite for a
7033       // candidate that itself also has calls.
7034       //
7035       // In other words if function_containing_sequence in the following pseudo
7036       // assembly requires that we save LR at the point of the call, but there
7037       // are no available registers: in this case we save using SP and as a
7038       // result the SP offsets requires stack fixups by multiples of 16.
7039       //
7040       // function_containing_sequence:
7041       //   ...
7042       //   save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
7043       //   call OUTLINED_FUNCTION_N
7044       //   restore LR from SP
7045       //   ...
7046       //
7047       // OUTLINED_FUNCTION_N:
7048       //   save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
7049       //   ...
7050       //   bl foo
7051       //   restore LR from SP
7052       //   ret
7053       //
7054       // Because the code to handle more than one stack fixup does not
7055       // currently have the proper checks for legality, these cases will assert
7056       // in the AArch64 MachineOutliner. This is because the code to do this
7057       // needs more hardening, testing, better checks that generated code is
7058       // legal, etc and because it is only verified to handle a single pass of
7059       // stack fixup.
7060       //
7061       // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
7062       // these cases until they are known to be handled. Bugzilla 46767 is
7063       // referenced in comments at the assert site.
7064       //
7065       // To avoid asserting (or generating non-legal code on noassert builds)
7066       // we remove all candidates which would need more than one stack fixup by
7067       // pruning the cases where the candidate has calls while also having no
7068       // available LR and having no available general purpose registers to copy
7069       // LR to (ie one extra stack save/restore).
7070       //
7071       if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
7072         erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
7073           return (std::any_of(
7074                      C.front(), std::next(C.back()),
7075                      [](const MachineInstr &MI) { return MI.isCall(); })) &&
7076                  (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
7077                   !findRegisterToSaveLRTo(C));
7078         });
7079       }
7080     }
7081 
7082     // If we dropped all of the candidates, bail out here.
7083     if (RepeatedSequenceLocs.size() < 2) {
7084       RepeatedSequenceLocs.clear();
7085       return outliner::OutlinedFunction();
7086     }
7087   }
7088 
7089   // Does every candidate's MBB contain a call? If so, then we might have a call
7090   // in the range.
7091   if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
7092     // Check if the range contains a call. These require a save + restore of the
7093     // link register.
7094     bool ModStackToSaveLR = false;
7095     if (std::any_of(FirstCand.front(), FirstCand.back(),
7096                     [](const MachineInstr &MI) { return MI.isCall(); }))
7097       ModStackToSaveLR = true;
7098 
7099     // Handle the last instruction separately. If this is a tail call, then the
7100     // last instruction is a call. We don't want to save + restore in this case.
7101     // However, it could be possible that the last instruction is a call without
7102     // it being valid to tail call this sequence. We should consider this as
7103     // well.
7104     else if (FrameID != MachineOutlinerThunk &&
7105              FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall())
7106       ModStackToSaveLR = true;
7107 
7108     if (ModStackToSaveLR) {
7109       // We can't fix up the stack. Bail out.
7110       if (!AllStackInstrsSafe) {
7111         RepeatedSequenceLocs.clear();
7112         return outliner::OutlinedFunction();
7113       }
7114 
7115       // Save + restore LR.
7116       NumBytesToCreateFrame += 8;
7117     }
7118   }
7119 
7120   // If we have CFI instructions, we can only outline if the outlined section
7121   // can be a tail call
7122   if (FrameID != MachineOutlinerTailCall && CFICount > 0)
7123     return outliner::OutlinedFunction();
7124 
7125   return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
7126                                     NumBytesToCreateFrame, FrameID);
7127 }
7128 
7129 bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
7130     MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
7131   const Function &F = MF.getFunction();
7132 
7133   // Can F be deduplicated by the linker? If it can, don't outline from it.
7134   if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
7135     return false;
7136 
7137   // Don't outline from functions with section markings; the program could
7138   // expect that all the code is in the named section.
7139   // FIXME: Allow outlining from multiple functions with the same section
7140   // marking.
7141   if (F.hasSection())
7142     return false;
7143 
7144   // Outlining from functions with redzones is unsafe since the outliner may
7145   // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
7146   // outline from it.
7147   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
7148   if (!AFI || AFI->hasRedZone().getValueOr(true))
7149     return false;
7150 
7151   // FIXME: Teach the outliner to generate/handle Windows unwind info.
7152   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI())
7153     return false;
7154 
7155   // It's safe to outline from MF.
7156   return true;
7157 }
7158 
7159 bool AArch64InstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
7160                                               unsigned &Flags) const {
7161   if (!TargetInstrInfo::isMBBSafeToOutlineFrom(MBB, Flags))
7162     return false;
7163   // Check if LR is available through all of the MBB. If it's not, then set
7164   // a flag.
7165   assert(MBB.getParent()->getRegInfo().tracksLiveness() &&
7166          "Suitable Machine Function for outlining must track liveness");
7167   LiveRegUnits LRU(getRegisterInfo());
7168 
7169   std::for_each(MBB.rbegin(), MBB.rend(),
7170                 [&LRU](MachineInstr &MI) { LRU.accumulate(MI); });
7171 
7172   // Check if each of the unsafe registers are available...
7173   bool W16AvailableInBlock = LRU.available(AArch64::W16);
7174   bool W17AvailableInBlock = LRU.available(AArch64::W17);
7175   bool NZCVAvailableInBlock = LRU.available(AArch64::NZCV);
7176 
7177   // If all of these are dead (and not live out), we know we don't have to check
7178   // them later.
7179   if (W16AvailableInBlock && W17AvailableInBlock && NZCVAvailableInBlock)
7180     Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead;
7181 
7182   // Now, add the live outs to the set.
7183   LRU.addLiveOuts(MBB);
7184 
7185   // If any of these registers is available in the MBB, but also a live out of
7186   // the block, then we know outlining is unsafe.
7187   if (W16AvailableInBlock && !LRU.available(AArch64::W16))
7188     return false;
7189   if (W17AvailableInBlock && !LRU.available(AArch64::W17))
7190     return false;
7191   if (NZCVAvailableInBlock && !LRU.available(AArch64::NZCV))
7192     return false;
7193 
7194   // Check if there's a call inside this MachineBasicBlock. If there is, then
7195   // set a flag.
7196   if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); }))
7197     Flags |= MachineOutlinerMBBFlags::HasCalls;
7198 
7199   MachineFunction *MF = MBB.getParent();
7200 
7201   // In the event that we outline, we may have to save LR. If there is an
7202   // available register in the MBB, then we'll always save LR there. Check if
7203   // this is true.
7204   bool CanSaveLR = false;
7205   const AArch64RegisterInfo *ARI = static_cast<const AArch64RegisterInfo *>(
7206       MF->getSubtarget().getRegisterInfo());
7207 
7208   // Check if there is an available register across the sequence that we can
7209   // use.
7210   for (unsigned Reg : AArch64::GPR64RegClass) {
7211     if (!ARI->isReservedReg(*MF, Reg) && Reg != AArch64::LR &&
7212         Reg != AArch64::X16 && Reg != AArch64::X17 && LRU.available(Reg)) {
7213       CanSaveLR = true;
7214       break;
7215     }
7216   }
7217 
7218   // Check if we have a register we can save LR to, and if LR was used
7219   // somewhere. If both of those things are true, then we need to evaluate the
7220   // safety of outlining stack instructions later.
7221   if (!CanSaveLR && !LRU.available(AArch64::LR))
7222     Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere;
7223 
7224   return true;
7225 }
7226 
7227 outliner::InstrType
7228 AArch64InstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT,
7229                                    unsigned Flags) const {
7230   MachineInstr &MI = *MIT;
7231   MachineBasicBlock *MBB = MI.getParent();
7232   MachineFunction *MF = MBB->getParent();
7233   AArch64FunctionInfo *FuncInfo = MF->getInfo<AArch64FunctionInfo>();
7234 
7235   // Don't outline anything used for return address signing. The outlined
7236   // function will get signed later if needed
7237   switch (MI.getOpcode()) {
7238   case AArch64::PACIASP:
7239   case AArch64::PACIBSP:
7240   case AArch64::AUTIASP:
7241   case AArch64::AUTIBSP:
7242   case AArch64::RETAA:
7243   case AArch64::RETAB:
7244   case AArch64::EMITBKEY:
7245     return outliner::InstrType::Illegal;
7246   }
7247 
7248   // Don't outline LOHs.
7249   if (FuncInfo->getLOHRelated().count(&MI))
7250     return outliner::InstrType::Illegal;
7251 
7252   // We can only outline these if we will tail call the outlined function, or
7253   // fix up the CFI offsets. Currently, CFI instructions are outlined only if
7254   // in a tail call.
7255   //
7256   // FIXME: If the proper fixups for the offset are implemented, this should be
7257   // possible.
7258   if (MI.isCFIInstruction())
7259     return outliner::InstrType::Legal;
7260 
7261   // Don't allow debug values to impact outlining type.
7262   if (MI.isDebugInstr() || MI.isIndirectDebugValue())
7263     return outliner::InstrType::Invisible;
7264 
7265   // At this point, KILL instructions don't really tell us much so we can go
7266   // ahead and skip over them.
7267   if (MI.isKill())
7268     return outliner::InstrType::Invisible;
7269 
7270   // Is this a terminator for a basic block?
7271   if (MI.isTerminator()) {
7272 
7273     // Is this the end of a function?
7274     if (MI.getParent()->succ_empty())
7275       return outliner::InstrType::Legal;
7276 
7277     // It's not, so don't outline it.
7278     return outliner::InstrType::Illegal;
7279   }
7280 
7281   // Make sure none of the operands are un-outlinable.
7282   for (const MachineOperand &MOP : MI.operands()) {
7283     if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() ||
7284         MOP.isTargetIndex())
7285       return outliner::InstrType::Illegal;
7286 
7287     // If it uses LR or W30 explicitly, then don't touch it.
7288     if (MOP.isReg() && !MOP.isImplicit() &&
7289         (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
7290       return outliner::InstrType::Illegal;
7291   }
7292 
7293   // Special cases for instructions that can always be outlined, but will fail
7294   // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
7295   // be outlined because they don't require a *specific* value to be in LR.
7296   if (MI.getOpcode() == AArch64::ADRP)
7297     return outliner::InstrType::Legal;
7298 
7299   // If MI is a call we might be able to outline it. We don't want to outline
7300   // any calls that rely on the position of items on the stack. When we outline
7301   // something containing a call, we have to emit a save and restore of LR in
7302   // the outlined function. Currently, this always happens by saving LR to the
7303   // stack. Thus, if we outline, say, half the parameters for a function call
7304   // plus the call, then we'll break the callee's expectations for the layout
7305   // of the stack.
7306   //
7307   // FIXME: Allow calls to functions which construct a stack frame, as long
7308   // as they don't access arguments on the stack.
7309   // FIXME: Figure out some way to analyze functions defined in other modules.
7310   // We should be able to compute the memory usage based on the IR calling
7311   // convention, even if we can't see the definition.
7312   if (MI.isCall()) {
7313     // Get the function associated with the call. Look at each operand and find
7314     // the one that represents the callee and get its name.
7315     const Function *Callee = nullptr;
7316     for (const MachineOperand &MOP : MI.operands()) {
7317       if (MOP.isGlobal()) {
7318         Callee = dyn_cast<Function>(MOP.getGlobal());
7319         break;
7320       }
7321     }
7322 
7323     // Never outline calls to mcount.  There isn't any rule that would require
7324     // this, but the Linux kernel's "ftrace" feature depends on it.
7325     if (Callee && Callee->getName() == "\01_mcount")
7326       return outliner::InstrType::Illegal;
7327 
7328     // If we don't know anything about the callee, assume it depends on the
7329     // stack layout of the caller. In that case, it's only legal to outline
7330     // as a tail-call. Explicitly list the call instructions we know about so we
7331     // don't get unexpected results with call pseudo-instructions.
7332     auto UnknownCallOutlineType = outliner::InstrType::Illegal;
7333     if (MI.getOpcode() == AArch64::BLR ||
7334         MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
7335       UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
7336 
7337     if (!Callee)
7338       return UnknownCallOutlineType;
7339 
7340     // We have a function we have information about. Check it if it's something
7341     // can safely outline.
7342     MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee);
7343 
7344     // We don't know what's going on with the callee at all. Don't touch it.
7345     if (!CalleeMF)
7346       return UnknownCallOutlineType;
7347 
7348     // Check if we know anything about the callee saves on the function. If we
7349     // don't, then don't touch it, since that implies that we haven't
7350     // computed anything about its stack frame yet.
7351     MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
7352     if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
7353         MFI.getNumObjects() > 0)
7354       return UnknownCallOutlineType;
7355 
7356     // At this point, we can say that CalleeMF ought to not pass anything on the
7357     // stack. Therefore, we can outline it.
7358     return outliner::InstrType::Legal;
7359   }
7360 
7361   // Don't outline positions.
7362   if (MI.isPosition())
7363     return outliner::InstrType::Illegal;
7364 
7365   // Don't touch the link register or W30.
7366   if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
7367       MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
7368     return outliner::InstrType::Illegal;
7369 
7370   // Don't outline BTI instructions, because that will prevent the outlining
7371   // site from being indirectly callable.
7372   if (MI.getOpcode() == AArch64::HINT) {
7373     int64_t Imm = MI.getOperand(0).getImm();
7374     if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
7375       return outliner::InstrType::Illegal;
7376   }
7377 
7378   return outliner::InstrType::Legal;
7379 }
7380 
7381 void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
7382   for (MachineInstr &MI : MBB) {
7383     const MachineOperand *Base;
7384     unsigned Width;
7385     int64_t Offset;
7386     bool OffsetIsScalable;
7387 
7388     // Is this a load or store with an immediate offset with SP as the base?
7389     if (!MI.mayLoadOrStore() ||
7390         !getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable, Width,
7391                                       &RI) ||
7392         (Base->isReg() && Base->getReg() != AArch64::SP))
7393       continue;
7394 
7395     // It is, so we have to fix it up.
7396     TypeSize Scale(0U, false);
7397     int64_t Dummy1, Dummy2;
7398 
7399     MachineOperand &StackOffsetOperand = getMemOpBaseRegImmOfsOffsetOperand(MI);
7400     assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
7401     getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
7402     assert(Scale != 0 && "Unexpected opcode!");
7403     assert(!OffsetIsScalable && "Expected offset to be a byte offset");
7404 
7405     // We've pushed the return address to the stack, so add 16 to the offset.
7406     // This is safe, since we already checked if it would overflow when we
7407     // checked if this instruction was legal to outline.
7408     int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedSize();
7409     StackOffsetOperand.setImm(NewImm);
7410   }
7411 }
7412 
7413 static void signOutlinedFunction(MachineFunction &MF, MachineBasicBlock &MBB,
7414                                  bool ShouldSignReturnAddr,
7415                                  bool ShouldSignReturnAddrWithAKey) {
7416   if (ShouldSignReturnAddr) {
7417     MachineBasicBlock::iterator MBBPAC = MBB.begin();
7418     MachineBasicBlock::iterator MBBAUT = MBB.getFirstTerminator();
7419     const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
7420     const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7421     DebugLoc DL;
7422 
7423     if (MBBAUT != MBB.end())
7424       DL = MBBAUT->getDebugLoc();
7425 
7426     // At the very beginning of the basic block we insert the following
7427     // depending on the key type
7428     //
7429     // a_key:                   b_key:
7430     //    PACIASP                   EMITBKEY
7431     //    CFI_INSTRUCTION           PACIBSP
7432     //                              CFI_INSTRUCTION
7433     unsigned PACI;
7434     if (ShouldSignReturnAddrWithAKey) {
7435       PACI = Subtarget.hasPAuth() ? AArch64::PACIA : AArch64::PACIASP;
7436     } else {
7437       BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::EMITBKEY))
7438           .setMIFlag(MachineInstr::FrameSetup);
7439       PACI = Subtarget.hasPAuth() ? AArch64::PACIB : AArch64::PACIBSP;
7440     }
7441 
7442     auto MI = BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(PACI));
7443     if (Subtarget.hasPAuth())
7444       MI.addReg(AArch64::LR, RegState::Define)
7445           .addReg(AArch64::LR)
7446           .addReg(AArch64::SP, RegState::InternalRead);
7447     MI.setMIFlag(MachineInstr::FrameSetup);
7448 
7449     unsigned CFIIndex =
7450         MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
7451     BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::CFI_INSTRUCTION))
7452         .addCFIIndex(CFIIndex)
7453         .setMIFlags(MachineInstr::FrameSetup);
7454 
7455     // If v8.3a features are available we can replace a RET instruction by
7456     // RETAA or RETAB and omit the AUT instructions
7457     if (Subtarget.hasPAuth() && MBBAUT != MBB.end() &&
7458         MBBAUT->getOpcode() == AArch64::RET) {
7459       BuildMI(MBB, MBBAUT, DL,
7460               TII->get(ShouldSignReturnAddrWithAKey ? AArch64::RETAA
7461                                                     : AArch64::RETAB))
7462           .copyImplicitOps(*MBBAUT);
7463       MBB.erase(MBBAUT);
7464     } else {
7465       BuildMI(MBB, MBBAUT, DL,
7466               TII->get(ShouldSignReturnAddrWithAKey ? AArch64::AUTIASP
7467                                                     : AArch64::AUTIBSP))
7468           .setMIFlag(MachineInstr::FrameDestroy);
7469     }
7470   }
7471 }
7472 
7473 void AArch64InstrInfo::buildOutlinedFrame(
7474     MachineBasicBlock &MBB, MachineFunction &MF,
7475     const outliner::OutlinedFunction &OF) const {
7476 
7477   AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
7478 
7479   if (OF.FrameConstructionID == MachineOutlinerTailCall)
7480     FI->setOutliningStyle("Tail Call");
7481   else if (OF.FrameConstructionID == MachineOutlinerThunk) {
7482     // For thunk outlining, rewrite the last instruction from a call to a
7483     // tail-call.
7484     MachineInstr *Call = &*--MBB.instr_end();
7485     unsigned TailOpcode;
7486     if (Call->getOpcode() == AArch64::BL) {
7487       TailOpcode = AArch64::TCRETURNdi;
7488     } else {
7489       assert(Call->getOpcode() == AArch64::BLR ||
7490              Call->getOpcode() == AArch64::BLRNoIP);
7491       TailOpcode = AArch64::TCRETURNriALL;
7492     }
7493     MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
7494                            .add(Call->getOperand(0))
7495                            .addImm(0);
7496     MBB.insert(MBB.end(), TC);
7497     Call->eraseFromParent();
7498 
7499     FI->setOutliningStyle("Thunk");
7500   }
7501 
7502   bool IsLeafFunction = true;
7503 
7504   // Is there a call in the outlined range?
7505   auto IsNonTailCall = [](const MachineInstr &MI) {
7506     return MI.isCall() && !MI.isReturn();
7507   };
7508 
7509   if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
7510     // Fix up the instructions in the range, since we're going to modify the
7511     // stack.
7512 
7513     // Bugzilla ID: 46767
7514     // TODO: Check if fixing up twice is safe so we can outline these.
7515     assert(OF.FrameConstructionID != MachineOutlinerDefault &&
7516            "Can only fix up stack references once");
7517     fixupPostOutline(MBB);
7518 
7519     IsLeafFunction = false;
7520 
7521     // LR has to be a live in so that we can save it.
7522     if (!MBB.isLiveIn(AArch64::LR))
7523       MBB.addLiveIn(AArch64::LR);
7524 
7525     MachineBasicBlock::iterator It = MBB.begin();
7526     MachineBasicBlock::iterator Et = MBB.end();
7527 
7528     if (OF.FrameConstructionID == MachineOutlinerTailCall ||
7529         OF.FrameConstructionID == MachineOutlinerThunk)
7530       Et = std::prev(MBB.end());
7531 
7532     // Insert a save before the outlined region
7533     MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
7534                                 .addReg(AArch64::SP, RegState::Define)
7535                                 .addReg(AArch64::LR)
7536                                 .addReg(AArch64::SP)
7537                                 .addImm(-16);
7538     It = MBB.insert(It, STRXpre);
7539 
7540     const TargetSubtargetInfo &STI = MF.getSubtarget();
7541     const MCRegisterInfo *MRI = STI.getRegisterInfo();
7542     unsigned DwarfReg = MRI->getDwarfRegNum(AArch64::LR, true);
7543 
7544     // Add a CFI saying the stack was moved 16 B down.
7545     int64_t StackPosEntry =
7546         MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 16));
7547     BuildMI(MBB, It, DebugLoc(), get(AArch64::CFI_INSTRUCTION))
7548         .addCFIIndex(StackPosEntry)
7549         .setMIFlags(MachineInstr::FrameSetup);
7550 
7551     // Add a CFI saying that the LR that we want to find is now 16 B higher than
7552     // before.
7553     int64_t LRPosEntry =
7554         MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg, -16));
7555     BuildMI(MBB, It, DebugLoc(), get(AArch64::CFI_INSTRUCTION))
7556         .addCFIIndex(LRPosEntry)
7557         .setMIFlags(MachineInstr::FrameSetup);
7558 
7559     // Insert a restore before the terminator for the function.
7560     MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
7561                                  .addReg(AArch64::SP, RegState::Define)
7562                                  .addReg(AArch64::LR, RegState::Define)
7563                                  .addReg(AArch64::SP)
7564                                  .addImm(16);
7565     Et = MBB.insert(Et, LDRXpost);
7566   }
7567 
7568   // If a bunch of candidates reach this point they must agree on their return
7569   // address signing. It is therefore enough to just consider the signing
7570   // behaviour of one of them
7571   const auto &MFI = *OF.Candidates.front().getMF()->getInfo<AArch64FunctionInfo>();
7572   bool ShouldSignReturnAddr = MFI.shouldSignReturnAddress(!IsLeafFunction);
7573 
7574   // a_key is the default
7575   bool ShouldSignReturnAddrWithAKey = !MFI.shouldSignWithBKey();
7576 
7577   // If this is a tail call outlined function, then there's already a return.
7578   if (OF.FrameConstructionID == MachineOutlinerTailCall ||
7579       OF.FrameConstructionID == MachineOutlinerThunk) {
7580     signOutlinedFunction(MF, MBB, ShouldSignReturnAddr,
7581                          ShouldSignReturnAddrWithAKey);
7582     return;
7583   }
7584 
7585   // It's not a tail call, so we have to insert the return ourselves.
7586 
7587   // LR has to be a live in so that we can return to it.
7588   if (!MBB.isLiveIn(AArch64::LR))
7589     MBB.addLiveIn(AArch64::LR);
7590 
7591   MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
7592                           .addReg(AArch64::LR);
7593   MBB.insert(MBB.end(), ret);
7594 
7595   signOutlinedFunction(MF, MBB, ShouldSignReturnAddr,
7596                        ShouldSignReturnAddrWithAKey);
7597 
7598   FI->setOutliningStyle("Function");
7599 
7600   // Did we have to modify the stack by saving the link register?
7601   if (OF.FrameConstructionID != MachineOutlinerDefault)
7602     return;
7603 
7604   // We modified the stack.
7605   // Walk over the basic block and fix up all the stack accesses.
7606   fixupPostOutline(MBB);
7607 }
7608 
7609 MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
7610     Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It,
7611     MachineFunction &MF, outliner::Candidate &C) const {
7612 
7613   // Are we tail calling?
7614   if (C.CallConstructionID == MachineOutlinerTailCall) {
7615     // If yes, then we can just branch to the label.
7616     It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
7617                             .addGlobalAddress(M.getNamedValue(MF.getName()))
7618                             .addImm(0));
7619     return It;
7620   }
7621 
7622   // Are we saving the link register?
7623   if (C.CallConstructionID == MachineOutlinerNoLRSave ||
7624       C.CallConstructionID == MachineOutlinerThunk) {
7625     // No, so just insert the call.
7626     It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
7627                             .addGlobalAddress(M.getNamedValue(MF.getName())));
7628     return It;
7629   }
7630 
7631   // We want to return the spot where we inserted the call.
7632   MachineBasicBlock::iterator CallPt;
7633 
7634   // Instructions for saving and restoring LR around the call instruction we're
7635   // going to insert.
7636   MachineInstr *Save;
7637   MachineInstr *Restore;
7638   // Can we save to a register?
7639   if (C.CallConstructionID == MachineOutlinerRegSave) {
7640     // FIXME: This logic should be sunk into a target-specific interface so that
7641     // we don't have to recompute the register.
7642     Register Reg = findRegisterToSaveLRTo(C);
7643     assert(Reg && "No callee-saved register available?");
7644 
7645     // LR has to be a live in so that we can save it.
7646     if (!MBB.isLiveIn(AArch64::LR))
7647       MBB.addLiveIn(AArch64::LR);
7648 
7649     // Save and restore LR from Reg.
7650     Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
7651                .addReg(AArch64::XZR)
7652                .addReg(AArch64::LR)
7653                .addImm(0);
7654     Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
7655                 .addReg(AArch64::XZR)
7656                 .addReg(Reg)
7657                 .addImm(0);
7658   } else {
7659     // We have the default case. Save and restore from SP.
7660     Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
7661                .addReg(AArch64::SP, RegState::Define)
7662                .addReg(AArch64::LR)
7663                .addReg(AArch64::SP)
7664                .addImm(-16);
7665     Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
7666                   .addReg(AArch64::SP, RegState::Define)
7667                   .addReg(AArch64::LR, RegState::Define)
7668                   .addReg(AArch64::SP)
7669                   .addImm(16);
7670   }
7671 
7672   It = MBB.insert(It, Save);
7673   It++;
7674 
7675   // Insert the call.
7676   It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
7677                           .addGlobalAddress(M.getNamedValue(MF.getName())));
7678   CallPt = It;
7679   It++;
7680 
7681   It = MBB.insert(It, Restore);
7682   return CallPt;
7683 }
7684 
7685 bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
7686   MachineFunction &MF) const {
7687   return MF.getFunction().hasMinSize();
7688 }
7689 
7690 Optional<DestSourcePair>
7691 AArch64InstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
7692 
7693   // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
7694   // and zero immediate operands used as an alias for mov instruction.
7695   if (MI.getOpcode() == AArch64::ORRWrs &&
7696       MI.getOperand(1).getReg() == AArch64::WZR &&
7697       MI.getOperand(3).getImm() == 0x0) {
7698     return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
7699   }
7700 
7701   if (MI.getOpcode() == AArch64::ORRXrs &&
7702       MI.getOperand(1).getReg() == AArch64::XZR &&
7703       MI.getOperand(3).getImm() == 0x0) {
7704     return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
7705   }
7706 
7707   return None;
7708 }
7709 
7710 Optional<RegImmPair> AArch64InstrInfo::isAddImmediate(const MachineInstr &MI,
7711                                                       Register Reg) const {
7712   int Sign = 1;
7713   int64_t Offset = 0;
7714 
7715   // TODO: Handle cases where Reg is a super- or sub-register of the
7716   // destination register.
7717   const MachineOperand &Op0 = MI.getOperand(0);
7718   if (!Op0.isReg() || Reg != Op0.getReg())
7719     return None;
7720 
7721   switch (MI.getOpcode()) {
7722   default:
7723     return None;
7724   case AArch64::SUBWri:
7725   case AArch64::SUBXri:
7726   case AArch64::SUBSWri:
7727   case AArch64::SUBSXri:
7728     Sign *= -1;
7729     LLVM_FALLTHROUGH;
7730   case AArch64::ADDSWri:
7731   case AArch64::ADDSXri:
7732   case AArch64::ADDWri:
7733   case AArch64::ADDXri: {
7734     // TODO: Third operand can be global address (usually some string).
7735     if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
7736         !MI.getOperand(2).isImm())
7737       return None;
7738     int Shift = MI.getOperand(3).getImm();
7739     assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
7740     Offset = Sign * (MI.getOperand(2).getImm() << Shift);
7741   }
7742   }
7743   return RegImmPair{MI.getOperand(1).getReg(), Offset};
7744 }
7745 
7746 /// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
7747 /// the destination register then, if possible, describe the value in terms of
7748 /// the source register.
7749 static Optional<ParamLoadedValue>
7750 describeORRLoadedValue(const MachineInstr &MI, Register DescribedReg,
7751                        const TargetInstrInfo *TII,
7752                        const TargetRegisterInfo *TRI) {
7753   auto DestSrc = TII->isCopyInstr(MI);
7754   if (!DestSrc)
7755     return None;
7756 
7757   Register DestReg = DestSrc->Destination->getReg();
7758   Register SrcReg = DestSrc->Source->getReg();
7759 
7760   auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
7761 
7762   // If the described register is the destination, just return the source.
7763   if (DestReg == DescribedReg)
7764     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
7765 
7766   // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
7767   if (MI.getOpcode() == AArch64::ORRWrs &&
7768       TRI->isSuperRegister(DestReg, DescribedReg))
7769     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
7770 
7771   // We may need to describe the lower part of a ORRXrs move.
7772   if (MI.getOpcode() == AArch64::ORRXrs &&
7773       TRI->isSubRegister(DestReg, DescribedReg)) {
7774     Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
7775     return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
7776   }
7777 
7778   assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
7779          "Unhandled ORR[XW]rs copy case");
7780 
7781   return None;
7782 }
7783 
7784 Optional<ParamLoadedValue>
7785 AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
7786                                       Register Reg) const {
7787   const MachineFunction *MF = MI.getMF();
7788   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
7789   switch (MI.getOpcode()) {
7790   case AArch64::MOVZWi:
7791   case AArch64::MOVZXi: {
7792     // MOVZWi may be used for producing zero-extended 32-bit immediates in
7793     // 64-bit parameters, so we need to consider super-registers.
7794     if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
7795       return None;
7796 
7797     if (!MI.getOperand(1).isImm())
7798       return None;
7799     int64_t Immediate = MI.getOperand(1).getImm();
7800     int Shift = MI.getOperand(2).getImm();
7801     return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
7802                             nullptr);
7803   }
7804   case AArch64::ORRWrs:
7805   case AArch64::ORRXrs:
7806     return describeORRLoadedValue(MI, Reg, this, TRI);
7807   }
7808 
7809   return TargetInstrInfo::describeLoadedValue(MI, Reg);
7810 }
7811 
7812 bool AArch64InstrInfo::isExtendLikelyToBeFolded(
7813     MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
7814   assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
7815          ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
7816          ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
7817 
7818   // Anyexts are nops.
7819   if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
7820     return true;
7821 
7822   Register DefReg = ExtMI.getOperand(0).getReg();
7823   if (!MRI.hasOneNonDBGUse(DefReg))
7824     return false;
7825 
7826   // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
7827   // addressing mode.
7828   auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
7829   return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
7830 }
7831 
7832 uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
7833   return get(Opc).TSFlags & AArch64::ElementSizeMask;
7834 }
7835 
7836 bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
7837   return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
7838 }
7839 
7840 bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
7841   return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
7842 }
7843 
7844 unsigned int
7845 AArch64InstrInfo::getTailDuplicateSize(CodeGenOpt::Level OptLevel) const {
7846   return OptLevel >= CodeGenOpt::Aggressive ? 6 : 2;
7847 }
7848 
7849 unsigned llvm::getBLRCallOpcode(const MachineFunction &MF) {
7850   if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
7851     return AArch64::BLRNoIP;
7852   else
7853     return AArch64::BLR;
7854 }
7855 
7856 #define GET_INSTRINFO_HELPERS
7857 #define GET_INSTRMAP_INFO
7858 #include "AArch64GenInstrInfo.inc"
7859