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