1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
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 TargetFrameLowering class.
10 //
11 // On AArch64, stack frames are structured as follows:
12 //
13 // The stack grows downward.
14 //
15 // All of the individual frame areas on the frame below are optional, i.e. it's
16 // possible to create a function so that the particular area isn't present
17 // in the frame.
18 //
19 // At function entry, the "frame" looks as follows:
20 //
21 // |                                   | Higher address
22 // |-----------------------------------|
23 // |                                   |
24 // | arguments passed on the stack     |
25 // |                                   |
26 // |-----------------------------------| <- sp
27 // |                                   | Lower address
28 //
29 //
30 // After the prologue has run, the frame has the following general structure.
31 // Note that this doesn't depict the case where a red-zone is used. Also,
32 // technically the last frame area (VLAs) doesn't get created until in the
33 // main function body, after the prologue is run. However, it's depicted here
34 // for completeness.
35 //
36 // |                                   | Higher address
37 // |-----------------------------------|
38 // |                                   |
39 // | arguments passed on the stack     |
40 // |                                   |
41 // |-----------------------------------|
42 // |                                   |
43 // | (Win64 only) varargs from reg     |
44 // |                                   |
45 // |-----------------------------------|
46 // |                                   |
47 // | callee-saved gpr registers        | <--.
48 // |                                   |    | On Darwin platforms these
49 // |- - - - - - - - - - - - - - - - - -|    | callee saves are swapped,
50 // |                                   |    | (frame record first)
51 // | prev_fp, prev_lr                  | <--'
52 // | (a.k.a. "frame record")           |
53 // |-----------------------------------| <- fp(=x29)
54 // |                                   |
55 // | callee-saved fp/simd/SVE regs     |
56 // |                                   |
57 // |-----------------------------------|
58 // |                                   |
59 // |        SVE stack objects          |
60 // |                                   |
61 // |-----------------------------------|
62 // |.empty.space.to.make.part.below....|
63 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
64 // |.the.standard.16-byte.alignment....|  compile time; if present)
65 // |-----------------------------------|
66 // |                                   |
67 // | local variables of fixed size     |
68 // | including spill slots             |
69 // |-----------------------------------| <- bp(not defined by ABI,
70 // |.variable-sized.local.variables....|       LLVM chooses X19)
71 // |.(VLAs)............................| (size of this area is unknown at
72 // |...................................|  compile time)
73 // |-----------------------------------| <- sp
74 // |                                   | Lower address
75 //
76 //
77 // To access the data in a frame, at-compile time, a constant offset must be
78 // computable from one of the pointers (fp, bp, sp) to access it. The size
79 // of the areas with a dotted background cannot be computed at compile-time
80 // if they are present, making it required to have all three of fp, bp and
81 // sp to be set up to be able to access all contents in the frame areas,
82 // assuming all of the frame areas are non-empty.
83 //
84 // For most functions, some of the frame areas are empty. For those functions,
85 // it may not be necessary to set up fp or bp:
86 // * A base pointer is definitely needed when there are both VLAs and local
87 //   variables with more-than-default alignment requirements.
88 // * A frame pointer is definitely needed when there are local variables with
89 //   more-than-default alignment requirements.
90 //
91 // For Darwin platforms the frame-record (fp, lr) is stored at the top of the
92 // callee-saved area, since the unwind encoding does not allow for encoding
93 // this dynamically and existing tools depend on this layout. For other
94 // platforms, the frame-record is stored at the bottom of the (gpr) callee-saved
95 // area to allow SVE stack objects (allocated directly below the callee-saves,
96 // if available) to be accessed directly from the framepointer.
97 // The SVE spill/fill instructions have VL-scaled addressing modes such
98 // as:
99 //    ldr z8, [fp, #-7 mul vl]
100 // For SVE the size of the vector length (VL) is not known at compile-time, so
101 // '#-7 mul vl' is an offset that can only be evaluated at runtime. With this
102 // layout, we don't need to add an unscaled offset to the framepointer before
103 // accessing the SVE object in the frame.
104 //
105 // In some cases when a base pointer is not strictly needed, it is generated
106 // anyway when offsets from the frame pointer to access local variables become
107 // so large that the offset can't be encoded in the immediate fields of loads
108 // or stores.
109 //
110 // FIXME: also explain the redzone concept.
111 // FIXME: also explain the concept of reserved call frames.
112 //
113 //===----------------------------------------------------------------------===//
114 
115 #include "AArch64FrameLowering.h"
116 #include "AArch64InstrInfo.h"
117 #include "AArch64MachineFunctionInfo.h"
118 #include "AArch64RegisterInfo.h"
119 #include "AArch64StackOffset.h"
120 #include "AArch64Subtarget.h"
121 #include "AArch64TargetMachine.h"
122 #include "MCTargetDesc/AArch64AddressingModes.h"
123 #include "llvm/ADT/ScopeExit.h"
124 #include "llvm/ADT/SmallVector.h"
125 #include "llvm/ADT/Statistic.h"
126 #include "llvm/CodeGen/LivePhysRegs.h"
127 #include "llvm/CodeGen/MachineBasicBlock.h"
128 #include "llvm/CodeGen/MachineFrameInfo.h"
129 #include "llvm/CodeGen/MachineFunction.h"
130 #include "llvm/CodeGen/MachineInstr.h"
131 #include "llvm/CodeGen/MachineInstrBuilder.h"
132 #include "llvm/CodeGen/MachineMemOperand.h"
133 #include "llvm/CodeGen/MachineModuleInfo.h"
134 #include "llvm/CodeGen/MachineOperand.h"
135 #include "llvm/CodeGen/MachineRegisterInfo.h"
136 #include "llvm/CodeGen/RegisterScavenging.h"
137 #include "llvm/CodeGen/TargetInstrInfo.h"
138 #include "llvm/CodeGen/TargetRegisterInfo.h"
139 #include "llvm/CodeGen/TargetSubtargetInfo.h"
140 #include "llvm/CodeGen/WinEHFuncInfo.h"
141 #include "llvm/IR/Attributes.h"
142 #include "llvm/IR/CallingConv.h"
143 #include "llvm/IR/DataLayout.h"
144 #include "llvm/IR/DebugLoc.h"
145 #include "llvm/IR/Function.h"
146 #include "llvm/MC/MCAsmInfo.h"
147 #include "llvm/MC/MCDwarf.h"
148 #include "llvm/Support/CommandLine.h"
149 #include "llvm/Support/Debug.h"
150 #include "llvm/Support/ErrorHandling.h"
151 #include "llvm/Support/MathExtras.h"
152 #include "llvm/Support/raw_ostream.h"
153 #include "llvm/Target/TargetMachine.h"
154 #include "llvm/Target/TargetOptions.h"
155 #include <cassert>
156 #include <cstdint>
157 #include <iterator>
158 #include <vector>
159 
160 using namespace llvm;
161 
162 #define DEBUG_TYPE "frame-info"
163 
164 static cl::opt<bool> EnableRedZone("aarch64-redzone",
165                                    cl::desc("enable use of redzone on AArch64"),
166                                    cl::init(false), cl::Hidden);
167 
168 static cl::opt<bool>
169     ReverseCSRRestoreSeq("reverse-csr-restore-seq",
170                          cl::desc("reverse the CSR restore sequence"),
171                          cl::init(false), cl::Hidden);
172 
173 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
174 
175 /// This is the biggest offset to the stack pointer we can encode in aarch64
176 /// instructions (without using a separate calculation and a temp register).
177 /// Note that the exception here are vector stores/loads which cannot encode any
178 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
179 static const unsigned DefaultSafeSPDisplacement = 255;
180 
181 /// Look at each instruction that references stack frames and return the stack
182 /// size limit beyond which some of these instructions will require a scratch
183 /// register during their expansion later.
184 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
185   // FIXME: For now, just conservatively guestimate based on unscaled indexing
186   // range. We'll end up allocating an unnecessary spill slot a lot, but
187   // realistically that's not a big deal at this stage of the game.
188   for (MachineBasicBlock &MBB : MF) {
189     for (MachineInstr &MI : MBB) {
190       if (MI.isDebugInstr() || MI.isPseudo() ||
191           MI.getOpcode() == AArch64::ADDXri ||
192           MI.getOpcode() == AArch64::ADDSXri)
193         continue;
194 
195       for (const MachineOperand &MO : MI.operands()) {
196         if (!MO.isFI())
197           continue;
198 
199         StackOffset Offset;
200         if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
201             AArch64FrameOffsetCannotUpdate)
202           return 0;
203       }
204     }
205   }
206   return DefaultSafeSPDisplacement;
207 }
208 
209 TargetStackID::Value
210 AArch64FrameLowering::getStackIDForScalableVectors() const {
211   return TargetStackID::SVEVector;
212 }
213 
214 /// Returns the size of the entire SVE stackframe (calleesaves + spills).
215 static StackOffset getSVEStackSize(const MachineFunction &MF) {
216   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
217   return {(int64_t)AFI->getStackSizeSVE(), MVT::nxv1i8};
218 }
219 
220 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
221   if (!EnableRedZone)
222     return false;
223   // Don't use the red zone if the function explicitly asks us not to.
224   // This is typically used for kernel code.
225   if (MF.getFunction().hasFnAttribute(Attribute::NoRedZone))
226     return false;
227 
228   const MachineFrameInfo &MFI = MF.getFrameInfo();
229   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
230   unsigned NumBytes = AFI->getLocalStackSize();
231 
232   return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128 ||
233            getSVEStackSize(MF));
234 }
235 
236 /// hasFP - Return true if the specified function should have a dedicated frame
237 /// pointer register.
238 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
239   const MachineFrameInfo &MFI = MF.getFrameInfo();
240   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
241   // Win64 EH requires a frame pointer if funclets are present, as the locals
242   // are accessed off the frame pointer in both the parent function and the
243   // funclets.
244   if (MF.hasEHFunclets())
245     return true;
246   // Retain behavior of always omitting the FP for leaf functions when possible.
247   if (MFI.hasCalls() && MF.getTarget().Options.DisableFramePointerElim(MF))
248     return true;
249   if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
250       MFI.hasStackMap() || MFI.hasPatchPoint() ||
251       RegInfo->needsStackRealignment(MF))
252     return true;
253   // With large callframes around we may need to use FP to access the scavenging
254   // emergency spillslot.
255   //
256   // Unfortunately some calls to hasFP() like machine verifier ->
257   // getReservedReg() -> hasFP in the middle of global isel are too early
258   // to know the max call frame size. Hopefully conservatively returning "true"
259   // in those cases is fine.
260   // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
261   if (!MFI.isMaxCallFrameSizeComputed() ||
262       MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
263     return true;
264 
265   return false;
266 }
267 
268 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
269 /// not required, we reserve argument space for call sites in the function
270 /// immediately on entry to the current function.  This eliminates the need for
271 /// add/sub sp brackets around call sites.  Returns true if the call frame is
272 /// included as part of the stack frame.
273 bool
274 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
275   return !MF.getFrameInfo().hasVarSizedObjects();
276 }
277 
278 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
279     MachineFunction &MF, MachineBasicBlock &MBB,
280     MachineBasicBlock::iterator I) const {
281   const AArch64InstrInfo *TII =
282       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
283   DebugLoc DL = I->getDebugLoc();
284   unsigned Opc = I->getOpcode();
285   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
286   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
287 
288   if (!hasReservedCallFrame(MF)) {
289     unsigned Align = getStackAlignment();
290 
291     int64_t Amount = I->getOperand(0).getImm();
292     Amount = alignTo(Amount, Align);
293     if (!IsDestroy)
294       Amount = -Amount;
295 
296     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
297     // doesn't have to pop anything), then the first operand will be zero too so
298     // this adjustment is a no-op.
299     if (CalleePopAmount == 0) {
300       // FIXME: in-function stack adjustment for calls is limited to 24-bits
301       // because there's no guaranteed temporary register available.
302       //
303       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
304       // 1) For offset <= 12-bit, we use LSL #0
305       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
306       // LSL #0, and the other uses LSL #12.
307       //
308       // Most call frames will be allocated at the start of a function so
309       // this is OK, but it is a limitation that needs dealing with.
310       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
311       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, {Amount, MVT::i8},
312                       TII);
313     }
314   } else if (CalleePopAmount != 0) {
315     // If the calling convention demands that the callee pops arguments from the
316     // stack, we want to add it back if we have a reserved call frame.
317     assert(CalleePopAmount < 0xffffff && "call frame too large");
318     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
319                     {-(int64_t)CalleePopAmount, MVT::i8}, TII);
320   }
321   return MBB.erase(I);
322 }
323 
324 static bool ShouldSignReturnAddress(MachineFunction &MF) {
325   // The function should be signed in the following situations:
326   // - sign-return-address=all
327   // - sign-return-address=non-leaf and the functions spills the LR
328 
329   const Function &F = MF.getFunction();
330   if (!F.hasFnAttribute("sign-return-address"))
331     return false;
332 
333   StringRef Scope = F.getFnAttribute("sign-return-address").getValueAsString();
334   if (Scope.equals("none"))
335     return false;
336 
337   if (Scope.equals("all"))
338     return true;
339 
340   assert(Scope.equals("non-leaf") && "Expected all, none or non-leaf");
341 
342   for (const auto &Info : MF.getFrameInfo().getCalleeSavedInfo())
343     if (Info.getReg() == AArch64::LR)
344       return true;
345 
346   return false;
347 }
348 
349 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
350     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
351   MachineFunction &MF = *MBB.getParent();
352   MachineFrameInfo &MFI = MF.getFrameInfo();
353   const TargetSubtargetInfo &STI = MF.getSubtarget();
354   const MCRegisterInfo *MRI = STI.getRegisterInfo();
355   const TargetInstrInfo *TII = STI.getInstrInfo();
356   DebugLoc DL = MBB.findDebugLoc(MBBI);
357 
358   // Add callee saved registers to move list.
359   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
360   if (CSI.empty())
361     return;
362 
363   for (const auto &Info : CSI) {
364     unsigned Reg = Info.getReg();
365     int64_t Offset =
366         MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
367     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
368     unsigned CFIIndex = MF.addFrameInst(
369         MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
370     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
371         .addCFIIndex(CFIIndex)
372         .setMIFlags(MachineInstr::FrameSetup);
373   }
374 }
375 
376 // Find a scratch register that we can use at the start of the prologue to
377 // re-align the stack pointer.  We avoid using callee-save registers since they
378 // may appear to be free when this is called from canUseAsPrologue (during
379 // shrink wrapping), but then no longer be free when this is called from
380 // emitPrologue.
381 //
382 // FIXME: This is a bit conservative, since in the above case we could use one
383 // of the callee-save registers as a scratch temp to re-align the stack pointer,
384 // but we would then have to make sure that we were in fact saving at least one
385 // callee-save register in the prologue, which is additional complexity that
386 // doesn't seem worth the benefit.
387 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
388   MachineFunction *MF = MBB->getParent();
389 
390   // If MBB is an entry block, use X9 as the scratch register
391   if (&MF->front() == MBB)
392     return AArch64::X9;
393 
394   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
395   const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
396   LivePhysRegs LiveRegs(TRI);
397   LiveRegs.addLiveIns(*MBB);
398 
399   // Mark callee saved registers as used so we will not choose them.
400   const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
401   for (unsigned i = 0; CSRegs[i]; ++i)
402     LiveRegs.addReg(CSRegs[i]);
403 
404   // Prefer X9 since it was historically used for the prologue scratch reg.
405   const MachineRegisterInfo &MRI = MF->getRegInfo();
406   if (LiveRegs.available(MRI, AArch64::X9))
407     return AArch64::X9;
408 
409   for (unsigned Reg : AArch64::GPR64RegClass) {
410     if (LiveRegs.available(MRI, Reg))
411       return Reg;
412   }
413   return AArch64::NoRegister;
414 }
415 
416 bool AArch64FrameLowering::canUseAsPrologue(
417     const MachineBasicBlock &MBB) const {
418   const MachineFunction *MF = MBB.getParent();
419   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
420   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
421   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
422 
423   // Don't need a scratch register if we're not going to re-align the stack.
424   if (!RegInfo->needsStackRealignment(*MF))
425     return true;
426   // Otherwise, we can use any block as long as it has a scratch register
427   // available.
428   return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
429 }
430 
431 static bool windowsRequiresStackProbe(MachineFunction &MF,
432                                       unsigned StackSizeInBytes) {
433   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
434   if (!Subtarget.isTargetWindows())
435     return false;
436   const Function &F = MF.getFunction();
437   // TODO: When implementing stack protectors, take that into account
438   // for the probe threshold.
439   unsigned StackProbeSize = 4096;
440   if (F.hasFnAttribute("stack-probe-size"))
441     F.getFnAttribute("stack-probe-size")
442         .getValueAsString()
443         .getAsInteger(0, StackProbeSize);
444   return (StackSizeInBytes >= StackProbeSize) &&
445          !F.hasFnAttribute("no-stack-arg-probe");
446 }
447 
448 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
449     MachineFunction &MF, unsigned StackBumpBytes) const {
450   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
451   const MachineFrameInfo &MFI = MF.getFrameInfo();
452   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
453   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
454 
455   if (MF.getFunction().hasOptSize())
456     return false;
457 
458   if (AFI->getLocalStackSize() == 0)
459     return false;
460 
461   // 512 is the maximum immediate for stp/ldp that will be used for
462   // callee-save save/restores
463   if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
464     return false;
465 
466   if (MFI.hasVarSizedObjects())
467     return false;
468 
469   if (RegInfo->needsStackRealignment(MF))
470     return false;
471 
472   // This isn't strictly necessary, but it simplifies things a bit since the
473   // current RedZone handling code assumes the SP is adjusted by the
474   // callee-save save/restore code.
475   if (canUseRedZone(MF))
476     return false;
477 
478   // When there is an SVE area on the stack, always allocate the
479   // callee-saves and spills/locals separately.
480   if (getSVEStackSize(MF))
481     return false;
482 
483   return true;
484 }
485 
486 // Given a load or a store instruction, generate an appropriate unwinding SEH
487 // code on Windows.
488 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,
489                                              const TargetInstrInfo &TII,
490                                              MachineInstr::MIFlag Flag) {
491   unsigned Opc = MBBI->getOpcode();
492   MachineBasicBlock *MBB = MBBI->getParent();
493   MachineFunction &MF = *MBB->getParent();
494   DebugLoc DL = MBBI->getDebugLoc();
495   unsigned ImmIdx = MBBI->getNumOperands() - 1;
496   int Imm = MBBI->getOperand(ImmIdx).getImm();
497   MachineInstrBuilder MIB;
498   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
499   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
500 
501   switch (Opc) {
502   default:
503     llvm_unreachable("No SEH Opcode for this instruction");
504   case AArch64::LDPDpost:
505     Imm = -Imm;
506     LLVM_FALLTHROUGH;
507   case AArch64::STPDpre: {
508     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
509     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
510     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
511               .addImm(Reg0)
512               .addImm(Reg1)
513               .addImm(Imm * 8)
514               .setMIFlag(Flag);
515     break;
516   }
517   case AArch64::LDPXpost:
518     Imm = -Imm;
519     LLVM_FALLTHROUGH;
520   case AArch64::STPXpre: {
521     Register Reg0 = MBBI->getOperand(1).getReg();
522     Register Reg1 = MBBI->getOperand(2).getReg();
523     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
524       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
525                 .addImm(Imm * 8)
526                 .setMIFlag(Flag);
527     else
528       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
529                 .addImm(RegInfo->getSEHRegNum(Reg0))
530                 .addImm(RegInfo->getSEHRegNum(Reg1))
531                 .addImm(Imm * 8)
532                 .setMIFlag(Flag);
533     break;
534   }
535   case AArch64::LDRDpost:
536     Imm = -Imm;
537     LLVM_FALLTHROUGH;
538   case AArch64::STRDpre: {
539     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
540     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
541               .addImm(Reg)
542               .addImm(Imm)
543               .setMIFlag(Flag);
544     break;
545   }
546   case AArch64::LDRXpost:
547     Imm = -Imm;
548     LLVM_FALLTHROUGH;
549   case AArch64::STRXpre: {
550     unsigned Reg =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
551     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
552               .addImm(Reg)
553               .addImm(Imm)
554               .setMIFlag(Flag);
555     break;
556   }
557   case AArch64::STPDi:
558   case AArch64::LDPDi: {
559     unsigned Reg0 =  RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
560     unsigned Reg1 =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
561     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
562               .addImm(Reg0)
563               .addImm(Reg1)
564               .addImm(Imm * 8)
565               .setMIFlag(Flag);
566     break;
567   }
568   case AArch64::STPXi:
569   case AArch64::LDPXi: {
570     Register Reg0 = MBBI->getOperand(0).getReg();
571     Register Reg1 = MBBI->getOperand(1).getReg();
572     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
573       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
574                 .addImm(Imm * 8)
575                 .setMIFlag(Flag);
576     else
577       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
578                 .addImm(RegInfo->getSEHRegNum(Reg0))
579                 .addImm(RegInfo->getSEHRegNum(Reg1))
580                 .addImm(Imm * 8)
581                 .setMIFlag(Flag);
582     break;
583   }
584   case AArch64::STRXui:
585   case AArch64::LDRXui: {
586     int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
587     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
588               .addImm(Reg)
589               .addImm(Imm * 8)
590               .setMIFlag(Flag);
591     break;
592   }
593   case AArch64::STRDui:
594   case AArch64::LDRDui: {
595     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
596     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
597               .addImm(Reg)
598               .addImm(Imm * 8)
599               .setMIFlag(Flag);
600     break;
601   }
602   }
603   auto I = MBB->insertAfter(MBBI, MIB);
604   return I;
605 }
606 
607 // Fix up the SEH opcode associated with the save/restore instruction.
608 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,
609                            unsigned LocalStackSize) {
610   MachineOperand *ImmOpnd = nullptr;
611   unsigned ImmIdx = MBBI->getNumOperands() - 1;
612   switch (MBBI->getOpcode()) {
613   default:
614     llvm_unreachable("Fix the offset in the SEH instruction");
615   case AArch64::SEH_SaveFPLR:
616   case AArch64::SEH_SaveRegP:
617   case AArch64::SEH_SaveReg:
618   case AArch64::SEH_SaveFRegP:
619   case AArch64::SEH_SaveFReg:
620     ImmOpnd = &MBBI->getOperand(ImmIdx);
621     break;
622   }
623   if (ImmOpnd)
624     ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);
625 }
626 
627 // Convert callee-save register save/restore instruction to do stack pointer
628 // decrement/increment to allocate/deallocate the callee-save stack area by
629 // converting store/load to use pre/post increment version.
630 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
631     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
632     const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,
633     bool NeedsWinCFI, bool *HasWinCFI, bool InProlog = true) {
634   // Ignore instructions that do not operate on SP, i.e. shadow call stack
635   // instructions and associated CFI instruction.
636   while (MBBI->getOpcode() == AArch64::STRXpost ||
637          MBBI->getOpcode() == AArch64::LDRXpre ||
638          MBBI->getOpcode() == AArch64::CFI_INSTRUCTION) {
639     if (MBBI->getOpcode() != AArch64::CFI_INSTRUCTION)
640       assert(MBBI->getOperand(0).getReg() != AArch64::SP);
641     ++MBBI;
642   }
643   unsigned NewOpc;
644   int Scale = 1;
645   switch (MBBI->getOpcode()) {
646   default:
647     llvm_unreachable("Unexpected callee-save save/restore opcode!");
648   case AArch64::STPXi:
649     NewOpc = AArch64::STPXpre;
650     Scale = 8;
651     break;
652   case AArch64::STPDi:
653     NewOpc = AArch64::STPDpre;
654     Scale = 8;
655     break;
656   case AArch64::STPQi:
657     NewOpc = AArch64::STPQpre;
658     Scale = 16;
659     break;
660   case AArch64::STRXui:
661     NewOpc = AArch64::STRXpre;
662     break;
663   case AArch64::STRDui:
664     NewOpc = AArch64::STRDpre;
665     break;
666   case AArch64::STRQui:
667     NewOpc = AArch64::STRQpre;
668     break;
669   case AArch64::LDPXi:
670     NewOpc = AArch64::LDPXpost;
671     Scale = 8;
672     break;
673   case AArch64::LDPDi:
674     NewOpc = AArch64::LDPDpost;
675     Scale = 8;
676     break;
677   case AArch64::LDPQi:
678     NewOpc = AArch64::LDPQpost;
679     Scale = 16;
680     break;
681   case AArch64::LDRXui:
682     NewOpc = AArch64::LDRXpost;
683     break;
684   case AArch64::LDRDui:
685     NewOpc = AArch64::LDRDpost;
686     break;
687   case AArch64::LDRQui:
688     NewOpc = AArch64::LDRQpost;
689     break;
690   }
691   // Get rid of the SEH code associated with the old instruction.
692   if (NeedsWinCFI) {
693     auto SEH = std::next(MBBI);
694     if (AArch64InstrInfo::isSEHInstruction(*SEH))
695       SEH->eraseFromParent();
696   }
697 
698   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
699   MIB.addReg(AArch64::SP, RegState::Define);
700 
701   // Copy all operands other than the immediate offset.
702   unsigned OpndIdx = 0;
703   for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
704        ++OpndIdx)
705     MIB.add(MBBI->getOperand(OpndIdx));
706 
707   assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
708          "Unexpected immediate offset in first/last callee-save save/restore "
709          "instruction!");
710   assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
711          "Unexpected base register in callee-save save/restore instruction!");
712   assert(CSStackSizeInc % Scale == 0);
713   MIB.addImm(CSStackSizeInc / Scale);
714 
715   MIB.setMIFlags(MBBI->getFlags());
716   MIB.setMemRefs(MBBI->memoperands());
717 
718   // Generate a new SEH code that corresponds to the new instruction.
719   if (NeedsWinCFI) {
720     *HasWinCFI = true;
721     InsertSEH(*MIB, *TII,
722               InProlog ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy);
723   }
724 
725   return std::prev(MBB.erase(MBBI));
726 }
727 
728 // Fixup callee-save register save/restore instructions to take into account
729 // combined SP bump by adding the local stack size to the stack offsets.
730 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
731                                               unsigned LocalStackSize,
732                                               bool NeedsWinCFI,
733                                               bool *HasWinCFI) {
734   if (AArch64InstrInfo::isSEHInstruction(MI))
735     return;
736 
737   unsigned Opc = MI.getOpcode();
738 
739   // Ignore instructions that do not operate on SP, i.e. shadow call stack
740   // instructions and associated CFI instruction.
741   if (Opc == AArch64::STRXpost || Opc == AArch64::LDRXpre ||
742       Opc == AArch64::CFI_INSTRUCTION) {
743     if (Opc != AArch64::CFI_INSTRUCTION)
744       assert(MI.getOperand(0).getReg() != AArch64::SP);
745     return;
746   }
747 
748   unsigned Scale;
749   switch (Opc) {
750   case AArch64::STPXi:
751   case AArch64::STRXui:
752   case AArch64::STPDi:
753   case AArch64::STRDui:
754   case AArch64::LDPXi:
755   case AArch64::LDRXui:
756   case AArch64::LDPDi:
757   case AArch64::LDRDui:
758     Scale = 8;
759     break;
760   case AArch64::STPQi:
761   case AArch64::STRQui:
762   case AArch64::LDPQi:
763   case AArch64::LDRQui:
764     Scale = 16;
765     break;
766   default:
767     llvm_unreachable("Unexpected callee-save save/restore opcode!");
768   }
769 
770   unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
771   assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
772          "Unexpected base register in callee-save save/restore instruction!");
773   // Last operand is immediate offset that needs fixing.
774   MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
775   // All generated opcodes have scaled offsets.
776   assert(LocalStackSize % Scale == 0);
777   OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
778 
779   if (NeedsWinCFI) {
780     *HasWinCFI = true;
781     auto MBBI = std::next(MachineBasicBlock::iterator(MI));
782     assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");
783     assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&
784            "Expecting a SEH instruction");
785     fixupSEHOpcode(MBBI, LocalStackSize);
786   }
787 }
788 
789 static void adaptForLdStOpt(MachineBasicBlock &MBB,
790                             MachineBasicBlock::iterator FirstSPPopI,
791                             MachineBasicBlock::iterator LastPopI) {
792   // Sometimes (when we restore in the same order as we save), we can end up
793   // with code like this:
794   //
795   // ldp      x26, x25, [sp]
796   // ldp      x24, x23, [sp, #16]
797   // ldp      x22, x21, [sp, #32]
798   // ldp      x20, x19, [sp, #48]
799   // add      sp, sp, #64
800   //
801   // In this case, it is always better to put the first ldp at the end, so
802   // that the load-store optimizer can run and merge the ldp and the add into
803   // a post-index ldp.
804   // If we managed to grab the first pop instruction, move it to the end.
805   if (ReverseCSRRestoreSeq)
806     MBB.splice(FirstSPPopI, &MBB, LastPopI);
807   // We should end up with something like this now:
808   //
809   // ldp      x24, x23, [sp, #16]
810   // ldp      x22, x21, [sp, #32]
811   // ldp      x20, x19, [sp, #48]
812   // ldp      x26, x25, [sp]
813   // add      sp, sp, #64
814   //
815   // and the load-store optimizer can merge the last two instructions into:
816   //
817   // ldp      x26, x25, [sp], #64
818   //
819 }
820 
821 static bool ShouldSignWithAKey(MachineFunction &MF) {
822   const Function &F = MF.getFunction();
823   if (!F.hasFnAttribute("sign-return-address-key"))
824     return true;
825 
826   const StringRef Key =
827       F.getFnAttribute("sign-return-address-key").getValueAsString();
828   assert(Key.equals_lower("a_key") || Key.equals_lower("b_key"));
829   return Key.equals_lower("a_key");
830 }
831 
832 static bool needsWinCFI(const MachineFunction &MF) {
833   const Function &F = MF.getFunction();
834   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
835          F.needsUnwindTableEntry();
836 }
837 
838 static bool isTargetDarwin(const MachineFunction &MF) {
839   return MF.getSubtarget<AArch64Subtarget>().isTargetDarwin();
840 }
841 
842 // Convenience function to determine whether I is an SVE callee save.
843 bool IsSVECalleeSave(MachineBasicBlock::iterator I) {
844   switch (I->getOpcode()) {
845   default:
846     return false;
847   case AArch64::STR_ZXI:
848   case AArch64::STR_PXI:
849   case AArch64::LDR_ZXI:
850   case AArch64::LDR_PXI:
851     return I->getFlag(MachineInstr::FrameSetup) ||
852            I->getFlag(MachineInstr::FrameDestroy);
853   }
854 }
855 
856 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
857                                         MachineBasicBlock &MBB) const {
858   MachineBasicBlock::iterator MBBI = MBB.begin();
859   const MachineFrameInfo &MFI = MF.getFrameInfo();
860   const Function &F = MF.getFunction();
861   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
862   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
863   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
864   MachineModuleInfo &MMI = MF.getMMI();
865   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
866   bool needsFrameMoves =
867       MF.needsFrameMoves() && !MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
868   bool HasFP = hasFP(MF);
869   bool NeedsWinCFI = needsWinCFI(MF);
870   bool HasWinCFI = false;
871   auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); });
872 
873   bool IsFunclet = MBB.isEHFuncletEntry();
874 
875   // At this point, we're going to decide whether or not the function uses a
876   // redzone. In most cases, the function doesn't have a redzone so let's
877   // assume that's false and set it to true in the case that there's a redzone.
878   AFI->setHasRedZone(false);
879 
880   // Debug location must be unknown since the first debug location is used
881   // to determine the end of the prologue.
882   DebugLoc DL;
883 
884   if (ShouldSignReturnAddress(MF)) {
885     if (ShouldSignWithAKey(MF))
886       BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIASP))
887           .setMIFlag(MachineInstr::FrameSetup);
888     else {
889       BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
890           .setMIFlag(MachineInstr::FrameSetup);
891       BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIBSP))
892           .setMIFlag(MachineInstr::FrameSetup);
893     }
894 
895     unsigned CFIIndex =
896         MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
897     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
898         .addCFIIndex(CFIIndex)
899         .setMIFlags(MachineInstr::FrameSetup);
900   }
901 
902   // All calls are tail calls in GHC calling conv, and functions have no
903   // prologue/epilogue.
904   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
905     return;
906 
907   // Set tagged base pointer to the bottom of the stack frame.
908   // Ideally it should match SP value after prologue.
909   AFI->setTaggedBasePointerOffset(MFI.getStackSize());
910 
911   const StackOffset &SVEStackSize = getSVEStackSize(MF);
912 
913   // getStackSize() includes all the locals in its size calculation. We don't
914   // include these locals when computing the stack size of a funclet, as they
915   // are allocated in the parent's stack frame and accessed via the frame
916   // pointer from the funclet.  We only save the callee saved registers in the
917   // funclet, which are really the callee saved registers of the parent
918   // function, including the funclet.
919   int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF)
920                            : (int)MFI.getStackSize();
921   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
922     assert(!HasFP && "unexpected function without stack frame but with FP");
923     assert(!SVEStackSize &&
924            "unexpected function without stack frame but with SVE objects");
925     // All of the stack allocation is for locals.
926     AFI->setLocalStackSize(NumBytes);
927     if (!NumBytes)
928       return;
929     // REDZONE: If the stack size is less than 128 bytes, we don't need
930     // to actually allocate.
931     if (canUseRedZone(MF)) {
932       AFI->setHasRedZone(true);
933       ++NumRedZoneFunctions;
934     } else {
935       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
936                       {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup,
937                       false, NeedsWinCFI, &HasWinCFI);
938       if (!NeedsWinCFI) {
939         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
940         MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
941         // Encode the stack size of the leaf function.
942         unsigned CFIIndex = MF.addFrameInst(
943             MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
944         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
945             .addCFIIndex(CFIIndex)
946             .setMIFlags(MachineInstr::FrameSetup);
947       }
948     }
949 
950     if (NeedsWinCFI) {
951       HasWinCFI = true;
952       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
953           .setMIFlag(MachineInstr::FrameSetup);
954     }
955 
956     return;
957   }
958 
959   bool IsWin64 =
960       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
961   // Var args are accounted for in the containing function, so don't
962   // include them for funclets.
963   unsigned FixedObject = (IsWin64 && !IsFunclet) ?
964                          alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
965 
966   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
967   // All of the remaining stack allocations are for locals.
968   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
969   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
970   if (CombineSPBump) {
971     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
972     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
973                     {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup, false,
974                     NeedsWinCFI, &HasWinCFI);
975     NumBytes = 0;
976   } else if (PrologueSaveSize != 0) {
977     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
978         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI);
979     NumBytes -= PrologueSaveSize;
980   }
981   assert(NumBytes >= 0 && "Negative stack allocation size!?");
982 
983   // Move past the saves of the callee-saved registers, fixing up the offsets
984   // and pre-inc if we decided to combine the callee-save and local stack
985   // pointer bump above.
986   MachineBasicBlock::iterator End = MBB.end();
987   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) &&
988          !IsSVECalleeSave(MBBI)) {
989     if (CombineSPBump)
990       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
991                                         NeedsWinCFI, &HasWinCFI);
992     ++MBBI;
993   }
994 
995   // The code below is not applicable to funclets. We have emitted all the SEH
996   // opcodes that we needed to emit.  The FP and BP belong to the containing
997   // function.
998   if (IsFunclet) {
999     if (NeedsWinCFI) {
1000       HasWinCFI = true;
1001       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1002           .setMIFlag(MachineInstr::FrameSetup);
1003     }
1004 
1005     // SEH funclets are passed the frame pointer in X1.  If the parent
1006     // function uses the base register, then the base register is used
1007     // directly, and is not retrieved from X1.
1008     if (F.hasPersonalityFn()) {
1009       EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());
1010       if (isAsynchronousEHPersonality(Per)) {
1011         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)
1012             .addReg(AArch64::X1).setMIFlag(MachineInstr::FrameSetup);
1013         MBB.addLiveIn(AArch64::X1);
1014       }
1015     }
1016 
1017     return;
1018   }
1019 
1020   if (HasFP) {
1021     // Only set up FP if we actually need to.
1022     int FPOffset = isTargetDarwin(MF) ? (AFI->getCalleeSavedStackSize() - 16) : 0;
1023 
1024     if (CombineSPBump)
1025       FPOffset += AFI->getLocalStackSize();
1026 
1027     // Issue    sub fp, sp, FPOffset or
1028     //          mov fp,sp          when FPOffset is zero.
1029     // Note: All stores of callee-saved registers are marked as "FrameSetup".
1030     // This code marks the instruction(s) that set the FP also.
1031     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP,
1032                     {FPOffset, MVT::i8}, TII, MachineInstr::FrameSetup, false,
1033                     NeedsWinCFI, &HasWinCFI);
1034   }
1035 
1036   if (windowsRequiresStackProbe(MF, NumBytes)) {
1037     uint32_t NumWords = NumBytes >> 4;
1038     if (NeedsWinCFI) {
1039       HasWinCFI = true;
1040       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
1041       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
1042       // This is at most two instructions, MOVZ follwed by MOVK.
1043       // TODO: Fix to use multiple stack alloc unwind codes for stacks
1044       // exceeding 256MB in size.
1045       if (NumBytes >= (1 << 28))
1046         report_fatal_error("Stack size cannot exceed 256MB for stack "
1047                             "unwinding purposes");
1048 
1049       uint32_t LowNumWords = NumWords & 0xFFFF;
1050       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
1051             .addImm(LowNumWords)
1052             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1053             .setMIFlag(MachineInstr::FrameSetup);
1054       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1055             .setMIFlag(MachineInstr::FrameSetup);
1056       if ((NumWords & 0xFFFF0000) != 0) {
1057           BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
1058               .addReg(AArch64::X15)
1059               .addImm((NumWords & 0xFFFF0000) >> 16) // High half
1060               .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
1061               .setMIFlag(MachineInstr::FrameSetup);
1062           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1063             .setMIFlag(MachineInstr::FrameSetup);
1064       }
1065     } else {
1066       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
1067           .addImm(NumWords)
1068           .setMIFlags(MachineInstr::FrameSetup);
1069     }
1070 
1071     switch (MF.getTarget().getCodeModel()) {
1072     case CodeModel::Tiny:
1073     case CodeModel::Small:
1074     case CodeModel::Medium:
1075     case CodeModel::Kernel:
1076       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
1077           .addExternalSymbol("__chkstk")
1078           .addReg(AArch64::X15, RegState::Implicit)
1079           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1080           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1081           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1082           .setMIFlags(MachineInstr::FrameSetup);
1083       if (NeedsWinCFI) {
1084         HasWinCFI = true;
1085         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1086             .setMIFlag(MachineInstr::FrameSetup);
1087       }
1088       break;
1089     case CodeModel::Large:
1090       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
1091           .addReg(AArch64::X16, RegState::Define)
1092           .addExternalSymbol("__chkstk")
1093           .addExternalSymbol("__chkstk")
1094           .setMIFlags(MachineInstr::FrameSetup);
1095       if (NeedsWinCFI) {
1096         HasWinCFI = true;
1097         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1098             .setMIFlag(MachineInstr::FrameSetup);
1099       }
1100 
1101       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR))
1102           .addReg(AArch64::X16, RegState::Kill)
1103           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
1104           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1105           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1106           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1107           .setMIFlags(MachineInstr::FrameSetup);
1108       if (NeedsWinCFI) {
1109         HasWinCFI = true;
1110         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1111             .setMIFlag(MachineInstr::FrameSetup);
1112       }
1113       break;
1114     }
1115 
1116     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
1117         .addReg(AArch64::SP, RegState::Kill)
1118         .addReg(AArch64::X15, RegState::Kill)
1119         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
1120         .setMIFlags(MachineInstr::FrameSetup);
1121     if (NeedsWinCFI) {
1122       HasWinCFI = true;
1123       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1124           .addImm(NumBytes)
1125           .setMIFlag(MachineInstr::FrameSetup);
1126     }
1127     NumBytes = 0;
1128   }
1129 
1130   StackOffset AllocateBefore = SVEStackSize, AllocateAfter = {};
1131   MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;
1132 
1133   // Process the SVE callee-saves to determine what space needs to be
1134   // allocated.
1135   if (AFI->getSVECalleeSavedStackSize()) {
1136     // Find callee save instructions in frame.
1137     CalleeSavesBegin = MBBI;
1138     assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");
1139     while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())
1140       ++MBBI;
1141     CalleeSavesEnd = MBBI;
1142 
1143     int64_t OffsetToFirstCalleeSaveFromSP =
1144         MFI.getObjectOffset(AFI->getMaxSVECSFrameIndex());
1145     StackOffset OffsetToCalleeSavesFromSP =
1146         StackOffset(OffsetToFirstCalleeSaveFromSP, MVT::nxv1i8) + SVEStackSize;
1147     AllocateBefore -= OffsetToCalleeSavesFromSP;
1148     AllocateAfter = SVEStackSize - AllocateBefore;
1149   }
1150 
1151   // Allocate space for the callee saves (if any).
1152   emitFrameOffset(MBB, CalleeSavesBegin, DL, AArch64::SP, AArch64::SP,
1153                   -AllocateBefore, TII,
1154                   MachineInstr::FrameSetup);
1155 
1156   // Finally allocate remaining SVE stack space.
1157   emitFrameOffset(MBB, CalleeSavesEnd, DL, AArch64::SP, AArch64::SP,
1158                   -AllocateAfter, TII,
1159                   MachineInstr::FrameSetup);
1160 
1161   // Allocate space for the rest of the frame.
1162   if (NumBytes) {
1163     const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
1164     unsigned scratchSPReg = AArch64::SP;
1165 
1166     if (NeedsRealignment) {
1167       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
1168       assert(scratchSPReg != AArch64::NoRegister);
1169     }
1170 
1171     // If we're a leaf function, try using the red zone.
1172     if (!canUseRedZone(MF))
1173       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1174       // the correct value here, as NumBytes also includes padding bytes,
1175       // which shouldn't be counted here.
1176       emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP,
1177                       {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup,
1178                       false, NeedsWinCFI, &HasWinCFI);
1179 
1180     if (NeedsRealignment) {
1181       const unsigned Alignment = MFI.getMaxAlignment();
1182       const unsigned NrBitsToZero = countTrailingZeros(Alignment);
1183       assert(NrBitsToZero > 1);
1184       assert(scratchSPReg != AArch64::SP);
1185 
1186       // SUB X9, SP, NumBytes
1187       //   -- X9 is temporary register, so shouldn't contain any live data here,
1188       //   -- free to use. This is already produced by emitFrameOffset above.
1189       // AND SP, X9, 0b11111...0000
1190       // The logical immediates have a non-trivial encoding. The following
1191       // formula computes the encoded immediate with all ones but
1192       // NrBitsToZero zero bits as least significant bits.
1193       uint32_t andMaskEncoded = (1 << 12)                         // = N
1194                                 | ((64 - NrBitsToZero) << 6)      // immr
1195                                 | ((64 - NrBitsToZero - 1) << 0); // imms
1196 
1197       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1198           .addReg(scratchSPReg, RegState::Kill)
1199           .addImm(andMaskEncoded);
1200       AFI->setStackRealigned(true);
1201       if (NeedsWinCFI) {
1202         HasWinCFI = true;
1203         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1204             .addImm(NumBytes & andMaskEncoded)
1205             .setMIFlag(MachineInstr::FrameSetup);
1206       }
1207     }
1208   }
1209 
1210   // If we need a base pointer, set it up here. It's whatever the value of the
1211   // stack pointer is at this point. Any variable size objects will be allocated
1212   // after this, so we can still use the base pointer to reference locals.
1213   //
1214   // FIXME: Clarify FrameSetup flags here.
1215   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1216   // needed.
1217   if (RegInfo->hasBasePointer(MF)) {
1218     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
1219                      false);
1220     if (NeedsWinCFI) {
1221       HasWinCFI = true;
1222       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1223           .setMIFlag(MachineInstr::FrameSetup);
1224     }
1225   }
1226 
1227   // The very last FrameSetup instruction indicates the end of prologue. Emit a
1228   // SEH opcode indicating the prologue end.
1229   if (NeedsWinCFI && HasWinCFI) {
1230     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1231         .setMIFlag(MachineInstr::FrameSetup);
1232   }
1233 
1234   if (needsFrameMoves) {
1235     const DataLayout &TD = MF.getDataLayout();
1236     const int StackGrowth = isTargetDarwin(MF)
1237                                 ? (2 * -TD.getPointerSize(0))
1238                                 : -AFI->getCalleeSavedStackSize();
1239     Register FramePtr = RegInfo->getFrameRegister(MF);
1240     // An example of the prologue:
1241     //
1242     //     .globl __foo
1243     //     .align 2
1244     //  __foo:
1245     // Ltmp0:
1246     //     .cfi_startproc
1247     //     .cfi_personality 155, ___gxx_personality_v0
1248     // Leh_func_begin:
1249     //     .cfi_lsda 16, Lexception33
1250     //
1251     //     stp  xa,bx, [sp, -#offset]!
1252     //     ...
1253     //     stp  x28, x27, [sp, #offset-32]
1254     //     stp  fp, lr, [sp, #offset-16]
1255     //     add  fp, sp, #offset - 16
1256     //     sub  sp, sp, #1360
1257     //
1258     // The Stack:
1259     //       +-------------------------------------------+
1260     // 10000 | ........ | ........ | ........ | ........ |
1261     // 10004 | ........ | ........ | ........ | ........ |
1262     //       +-------------------------------------------+
1263     // 10008 | ........ | ........ | ........ | ........ |
1264     // 1000c | ........ | ........ | ........ | ........ |
1265     //       +===========================================+
1266     // 10010 |                X28 Register               |
1267     // 10014 |                X28 Register               |
1268     //       +-------------------------------------------+
1269     // 10018 |                X27 Register               |
1270     // 1001c |                X27 Register               |
1271     //       +===========================================+
1272     // 10020 |                Frame Pointer              |
1273     // 10024 |                Frame Pointer              |
1274     //       +-------------------------------------------+
1275     // 10028 |                Link Register              |
1276     // 1002c |                Link Register              |
1277     //       +===========================================+
1278     // 10030 | ........ | ........ | ........ | ........ |
1279     // 10034 | ........ | ........ | ........ | ........ |
1280     //       +-------------------------------------------+
1281     // 10038 | ........ | ........ | ........ | ........ |
1282     // 1003c | ........ | ........ | ........ | ........ |
1283     //       +-------------------------------------------+
1284     //
1285     //     [sp] = 10030        ::    >>initial value<<
1286     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
1287     //     fp = sp == 10020    ::  mov fp, sp
1288     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
1289     //     sp == 10010         ::    >>final value<<
1290     //
1291     // The frame pointer (w29) points to address 10020. If we use an offset of
1292     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
1293     // for w27, and -32 for w28:
1294     //
1295     //  Ltmp1:
1296     //     .cfi_def_cfa w29, 16
1297     //  Ltmp2:
1298     //     .cfi_offset w30, -8
1299     //  Ltmp3:
1300     //     .cfi_offset w29, -16
1301     //  Ltmp4:
1302     //     .cfi_offset w27, -24
1303     //  Ltmp5:
1304     //     .cfi_offset w28, -32
1305 
1306     if (HasFP) {
1307       // Define the current CFA rule to use the provided FP.
1308       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
1309       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
1310           nullptr, Reg, StackGrowth - FixedObject));
1311       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1312           .addCFIIndex(CFIIndex)
1313           .setMIFlags(MachineInstr::FrameSetup);
1314     } else {
1315       // Encode the stack size of the leaf function.
1316       unsigned CFIIndex = MF.addFrameInst(
1317           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
1318       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1319           .addCFIIndex(CFIIndex)
1320           .setMIFlags(MachineInstr::FrameSetup);
1321     }
1322 
1323     // Now emit the moves for whatever callee saved regs we have (including FP,
1324     // LR if those are saved).
1325     emitCalleeSavedFrameMoves(MBB, MBBI);
1326   }
1327 }
1328 
1329 static void InsertReturnAddressAuth(MachineFunction &MF,
1330                                     MachineBasicBlock &MBB) {
1331   if (!ShouldSignReturnAddress(MF))
1332     return;
1333   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1334   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1335 
1336   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1337   DebugLoc DL;
1338   if (MBBI != MBB.end())
1339     DL = MBBI->getDebugLoc();
1340 
1341   // The AUTIASP instruction assembles to a hint instruction before v8.3a so
1342   // this instruction can safely used for any v8a architecture.
1343   // From v8.3a onwards there are optimised authenticate LR and return
1344   // instructions, namely RETA{A,B}, that can be used instead.
1345   if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() &&
1346       MBBI->getOpcode() == AArch64::RET_ReallyLR) {
1347     BuildMI(MBB, MBBI, DL,
1348             TII->get(ShouldSignWithAKey(MF) ? AArch64::RETAA : AArch64::RETAB))
1349         .copyImplicitOps(*MBBI);
1350     MBB.erase(MBBI);
1351   } else {
1352     BuildMI(
1353         MBB, MBBI, DL,
1354         TII->get(ShouldSignWithAKey(MF) ? AArch64::AUTIASP : AArch64::AUTIBSP))
1355         .setMIFlag(MachineInstr::FrameDestroy);
1356   }
1357 }
1358 
1359 static bool isFuncletReturnInstr(const MachineInstr &MI) {
1360   switch (MI.getOpcode()) {
1361   default:
1362     return false;
1363   case AArch64::CATCHRET:
1364   case AArch64::CLEANUPRET:
1365     return true;
1366   }
1367 }
1368 
1369 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
1370                                         MachineBasicBlock &MBB) const {
1371   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1372   MachineFrameInfo &MFI = MF.getFrameInfo();
1373   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1374   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1375   DebugLoc DL;
1376   bool IsTailCallReturn = false;
1377   bool NeedsWinCFI = needsWinCFI(MF);
1378   bool HasWinCFI = false;
1379   bool IsFunclet = false;
1380   auto WinCFI = make_scope_exit([&]() {
1381     if (!MF.hasWinCFI())
1382       MF.setHasWinCFI(HasWinCFI);
1383   });
1384 
1385   if (MBB.end() != MBBI) {
1386     DL = MBBI->getDebugLoc();
1387     unsigned RetOpcode = MBBI->getOpcode();
1388     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
1389                        RetOpcode == AArch64::TCRETURNri ||
1390                        RetOpcode == AArch64::TCRETURNriBTI;
1391     IsFunclet = isFuncletReturnInstr(*MBBI);
1392   }
1393 
1394   int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF)
1395                            : MFI.getStackSize();
1396   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1397 
1398   // All calls are tail calls in GHC calling conv, and functions have no
1399   // prologue/epilogue.
1400   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1401     return;
1402 
1403   // Initial and residual are named for consistency with the prologue. Note that
1404   // in the epilogue, the residual adjustment is executed first.
1405   uint64_t ArgumentPopSize = 0;
1406   if (IsTailCallReturn) {
1407     MachineOperand &StackAdjust = MBBI->getOperand(1);
1408 
1409     // For a tail-call in a callee-pops-arguments environment, some or all of
1410     // the stack may actually be in use for the call's arguments, this is
1411     // calculated during LowerCall and consumed here...
1412     ArgumentPopSize = StackAdjust.getImm();
1413   } else {
1414     // ... otherwise the amount to pop is *all* of the argument space,
1415     // conveniently stored in the MachineFunctionInfo by
1416     // LowerFormalArguments. This will, of course, be zero for the C calling
1417     // convention.
1418     ArgumentPopSize = AFI->getArgumentStackToRestore();
1419   }
1420 
1421   // The stack frame should be like below,
1422   //
1423   //      ----------------------                     ---
1424   //      |                    |                      |
1425   //      | BytesInStackArgArea|              CalleeArgStackSize
1426   //      | (NumReusableBytes) |                (of tail call)
1427   //      |                    |                     ---
1428   //      |                    |                      |
1429   //      ---------------------|        ---           |
1430   //      |                    |         |            |
1431   //      |   CalleeSavedReg   |         |            |
1432   //      | (CalleeSavedStackSize)|      |            |
1433   //      |                    |         |            |
1434   //      ---------------------|         |         NumBytes
1435   //      |                    |     StackSize  (StackAdjustUp)
1436   //      |   LocalStackSize   |         |            |
1437   //      | (covering callee   |         |            |
1438   //      |       args)        |         |            |
1439   //      |                    |         |            |
1440   //      ----------------------        ---          ---
1441   //
1442   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
1443   //             = StackSize + ArgumentPopSize
1444   //
1445   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
1446   // it as the 2nd argument of AArch64ISD::TC_RETURN.
1447 
1448   auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); });
1449 
1450   bool IsWin64 =
1451       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1452   // Var args are accounted for in the containing function, so don't
1453   // include them for funclets.
1454   unsigned FixedObject =
1455       (IsWin64 && !IsFunclet) ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1456 
1457   uint64_t AfterCSRPopSize = ArgumentPopSize;
1458   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1459   // We cannot rely on the local stack size set in emitPrologue if the function
1460   // has funclets, as funclets have different local stack size requirements, and
1461   // the current value set in emitPrologue may be that of the containing
1462   // function.
1463   if (MF.hasEHFunclets())
1464     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1465   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1466   // Assume we can't combine the last pop with the sp restore.
1467 
1468   if (!CombineSPBump && PrologueSaveSize != 0) {
1469     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
1470     while (AArch64InstrInfo::isSEHInstruction(*Pop))
1471       Pop = std::prev(Pop);
1472     // Converting the last ldp to a post-index ldp is valid only if the last
1473     // ldp's offset is 0.
1474     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
1475     // If the offset is 0, convert it to a post-index ldp.
1476     if (OffsetOp.getImm() == 0)
1477       convertCalleeSaveRestoreToSPPrePostIncDec(
1478           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, false);
1479     else {
1480       // If not, make sure to emit an add after the last ldp.
1481       // We're doing this by transfering the size to be restored from the
1482       // adjustment *before* the CSR pops to the adjustment *after* the CSR
1483       // pops.
1484       AfterCSRPopSize += PrologueSaveSize;
1485     }
1486   }
1487 
1488   // Move past the restores of the callee-saved registers.
1489   // If we plan on combining the sp bump of the local stack size and the callee
1490   // save stack size, we might need to adjust the CSR save and restore offsets.
1491   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
1492   MachineBasicBlock::iterator Begin = MBB.begin();
1493   while (LastPopI != Begin) {
1494     --LastPopI;
1495     if (!LastPopI->getFlag(MachineInstr::FrameDestroy) ||
1496         IsSVECalleeSave(LastPopI)) {
1497       ++LastPopI;
1498       break;
1499     } else if (CombineSPBump)
1500       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
1501                                         NeedsWinCFI, &HasWinCFI);
1502   }
1503 
1504   if (NeedsWinCFI) {
1505     HasWinCFI = true;
1506     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
1507         .setMIFlag(MachineInstr::FrameDestroy);
1508   }
1509 
1510   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1511 
1512   // If there is a single SP update, insert it before the ret and we're done.
1513   if (CombineSPBump) {
1514     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
1515     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
1516                     {NumBytes + (int64_t)AfterCSRPopSize, MVT::i8}, TII,
1517                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1518     if (NeedsWinCFI && HasWinCFI)
1519       BuildMI(MBB, MBB.getFirstTerminator(), DL,
1520               TII->get(AArch64::SEH_EpilogEnd))
1521           .setMIFlag(MachineInstr::FrameDestroy);
1522     return;
1523   }
1524 
1525   NumBytes -= PrologueSaveSize;
1526   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1527 
1528   // Process the SVE callee-saves to determine what space needs to be
1529   // deallocated.
1530   StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize;
1531   MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI;
1532   if (AFI->getSVECalleeSavedStackSize()) {
1533     RestoreBegin = std::prev(RestoreEnd);;
1534     while (IsSVECalleeSave(RestoreBegin) &&
1535            RestoreBegin != MBB.begin())
1536       --RestoreBegin;
1537     ++RestoreBegin;
1538 
1539     assert(IsSVECalleeSave(RestoreBegin) &&
1540            IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction");
1541 
1542     int64_t OffsetToFirstCalleeSaveFromSP =
1543         MFI.getObjectOffset(AFI->getMaxSVECSFrameIndex());
1544     StackOffset OffsetToCalleeSavesFromSP =
1545         StackOffset(OffsetToFirstCalleeSaveFromSP, MVT::nxv1i8) + SVEStackSize;
1546     DeallocateBefore = OffsetToCalleeSavesFromSP;
1547     DeallocateAfter = SVEStackSize - DeallocateBefore;
1548   }
1549 
1550   // Deallocate the SVE area.
1551   if (SVEStackSize) {
1552     if (AFI->isStackRealigned()) {
1553       if (AFI->getSVECalleeSavedStackSize())
1554         // Set SP to start of SVE area, from which the callee-save reloads
1555         // can be done. The code below will deallocate the stack space
1556         // space by moving FP -> SP.
1557         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP,
1558                         -SVEStackSize, TII, MachineInstr::FrameDestroy);
1559     } else {
1560       if (AFI->getSVECalleeSavedStackSize()) {
1561         // Deallocate the non-SVE locals first before we can deallocate (and
1562         // restore callee saves) from the SVE area.
1563         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
1564                         {NumBytes, MVT::i8}, TII, MachineInstr::FrameDestroy);
1565         NumBytes = 0;
1566       }
1567 
1568       emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
1569                       DeallocateBefore, TII, MachineInstr::FrameDestroy);
1570 
1571       emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP,
1572                       DeallocateAfter, TII, MachineInstr::FrameDestroy);
1573     }
1574   }
1575 
1576   if (!hasFP(MF)) {
1577     bool RedZone = canUseRedZone(MF);
1578     // If this was a redzone leaf function, we don't need to restore the
1579     // stack pointer (but we may need to pop stack args for fastcc).
1580     if (RedZone && AfterCSRPopSize == 0)
1581       return;
1582 
1583     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
1584     int StackRestoreBytes = RedZone ? 0 : NumBytes;
1585     if (NoCalleeSaveRestore)
1586       StackRestoreBytes += AfterCSRPopSize;
1587 
1588     // If we were able to combine the local stack pop with the argument pop,
1589     // then we're done.
1590     bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0;
1591 
1592     // If we're done after this, make sure to help the load store optimizer.
1593     if (Done)
1594       adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI);
1595 
1596     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1597                     {StackRestoreBytes, MVT::i8}, TII,
1598                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1599     if (Done) {
1600       if (NeedsWinCFI) {
1601         HasWinCFI = true;
1602         BuildMI(MBB, MBB.getFirstTerminator(), DL,
1603                 TII->get(AArch64::SEH_EpilogEnd))
1604             .setMIFlag(MachineInstr::FrameDestroy);
1605       }
1606       return;
1607     }
1608 
1609     NumBytes = 0;
1610   }
1611 
1612   // Restore the original stack pointer.
1613   // FIXME: Rather than doing the math here, we should instead just use
1614   // non-post-indexed loads for the restores if we aren't actually going to
1615   // be able to save any instructions.
1616   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) {
1617     int64_t OffsetToFrameRecord =
1618         isTargetDarwin(MF) ? (-(int64_t)AFI->getCalleeSavedStackSize() + 16) : 0;
1619     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
1620                     {OffsetToFrameRecord, MVT::i8},
1621                     TII, MachineInstr::FrameDestroy, false, NeedsWinCFI);
1622   } else if (NumBytes)
1623     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1624                     {NumBytes, MVT::i8}, TII, MachineInstr::FrameDestroy, false,
1625                     NeedsWinCFI);
1626 
1627   // This must be placed after the callee-save restore code because that code
1628   // assumes the SP is at the same location as it was after the callee-save save
1629   // code in the prologue.
1630   if (AfterCSRPopSize) {
1631     // Find an insertion point for the first ldp so that it goes before the
1632     // shadow call stack epilog instruction. This ensures that the restore of
1633     // lr from x18 is placed after the restore from sp.
1634     auto FirstSPPopI = MBB.getFirstTerminator();
1635     while (FirstSPPopI != Begin) {
1636       auto Prev = std::prev(FirstSPPopI);
1637       if (Prev->getOpcode() != AArch64::LDRXpre ||
1638           Prev->getOperand(0).getReg() == AArch64::SP)
1639         break;
1640       FirstSPPopI = Prev;
1641     }
1642 
1643     adaptForLdStOpt(MBB, FirstSPPopI, LastPopI);
1644 
1645     emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP,
1646                     {(int64_t)AfterCSRPopSize, MVT::i8}, TII,
1647                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1648   }
1649   if (NeedsWinCFI && HasWinCFI)
1650     BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::SEH_EpilogEnd))
1651         .setMIFlag(MachineInstr::FrameDestroy);
1652 
1653   MF.setHasWinCFI(HasWinCFI);
1654 }
1655 
1656 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1657 /// debug info.  It's the same as what we use for resolving the code-gen
1658 /// references for now.  FIXME: This can go wrong when references are
1659 /// SP-relative and simple call frames aren't used.
1660 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
1661                                                  int FI,
1662                                                  unsigned &FrameReg) const {
1663   return resolveFrameIndexReference(
1664              MF, FI, FrameReg,
1665              /*PreferFP=*/
1666              MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress),
1667              /*ForSimm=*/false)
1668       .getBytes();
1669 }
1670 
1671 int AArch64FrameLowering::getNonLocalFrameIndexReference(
1672   const MachineFunction &MF, int FI) const {
1673   return getSEHFrameIndexOffset(MF, FI);
1674 }
1675 
1676 static StackOffset getFPOffset(const MachineFunction &MF, int ObjectOffset) {
1677   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1678   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1679   bool IsWin64 =
1680       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1681   unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1682   unsigned FPAdjust = isTargetDarwin(MF)
1683                         ? 16 : AFI->getCalleeSavedStackSize(MF.getFrameInfo());
1684   return {ObjectOffset + FixedObject + FPAdjust, MVT::i8};
1685 }
1686 
1687 static StackOffset getStackOffset(const MachineFunction &MF, int ObjectOffset) {
1688   const auto &MFI = MF.getFrameInfo();
1689   return {ObjectOffset + (int)MFI.getStackSize(), MVT::i8};
1690 }
1691 
1692 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,
1693                                                  int FI) const {
1694   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
1695       MF.getSubtarget().getRegisterInfo());
1696   int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);
1697   return RegInfo->getLocalAddressRegister(MF) == AArch64::FP
1698              ? getFPOffset(MF, ObjectOffset).getBytes()
1699              : getStackOffset(MF, ObjectOffset).getBytes();
1700 }
1701 
1702 StackOffset AArch64FrameLowering::resolveFrameIndexReference(
1703     const MachineFunction &MF, int FI, unsigned &FrameReg, bool PreferFP,
1704     bool ForSimm) const {
1705   const auto &MFI = MF.getFrameInfo();
1706   int ObjectOffset = MFI.getObjectOffset(FI);
1707   bool isFixed = MFI.isFixedObjectIndex(FI);
1708   bool isSVE = MFI.getStackID(FI) == TargetStackID::SVEVector;
1709   return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg,
1710                                      PreferFP, ForSimm);
1711 }
1712 
1713 StackOffset AArch64FrameLowering::resolveFrameOffsetReference(
1714     const MachineFunction &MF, int ObjectOffset, bool isFixed, bool isSVE,
1715     unsigned &FrameReg, bool PreferFP, bool ForSimm) const {
1716   const auto &MFI = MF.getFrameInfo();
1717   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
1718       MF.getSubtarget().getRegisterInfo());
1719   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1720   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1721 
1722   int FPOffset = getFPOffset(MF, ObjectOffset).getBytes();
1723   int Offset = getStackOffset(MF, ObjectOffset).getBytes();
1724   bool isCSR =
1725       !isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
1726 
1727   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1728 
1729   // Use frame pointer to reference fixed objects. Use it for locals if
1730   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1731   // reliable as a base). Make sure useFPForScavengingIndex() does the
1732   // right thing for the emergency spill slot.
1733   bool UseFP = false;
1734   if (AFI->hasStackFrame() && !isSVE) {
1735     // We shouldn't prefer using the FP when there is an SVE area
1736     // in between the FP and the non-SVE locals/spills.
1737     PreferFP &= !SVEStackSize;
1738 
1739     // Note: Keeping the following as multiple 'if' statements rather than
1740     // merging to a single expression for readability.
1741     //
1742     // Argument access should always use the FP.
1743     if (isFixed) {
1744       UseFP = hasFP(MF);
1745     } else if (isCSR && RegInfo->needsStackRealignment(MF)) {
1746       // References to the CSR area must use FP if we're re-aligning the stack
1747       // since the dynamically-sized alignment padding is between the SP/BP and
1748       // the CSR area.
1749       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1750       UseFP = true;
1751     } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) {
1752       // If the FPOffset is negative and we're producing a signed immediate, we
1753       // have to keep in mind that the available offset range for negative
1754       // offsets is smaller than for positive ones. If an offset is available
1755       // via the FP and the SP, use whichever is closest.
1756       bool FPOffsetFits = !ForSimm || FPOffset >= -256;
1757       PreferFP |= Offset > -FPOffset;
1758 
1759       if (MFI.hasVarSizedObjects()) {
1760         // If we have variable sized objects, we can use either FP or BP, as the
1761         // SP offset is unknown. We can use the base pointer if we have one and
1762         // FP is not preferred. If not, we're stuck with using FP.
1763         bool CanUseBP = RegInfo->hasBasePointer(MF);
1764         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1765           UseFP = PreferFP;
1766         else if (!CanUseBP) { // Can't use BP. Forced to use FP.
1767           assert(!SVEStackSize && "Expected BP to be available");
1768           UseFP = true;
1769         }
1770         // else we can use BP and FP, but the offset from FP won't fit.
1771         // That will make us scavenge registers which we can probably avoid by
1772         // using BP. If it won't fit for BP either, we'll scavenge anyway.
1773       } else if (FPOffset >= 0) {
1774         // Use SP or FP, whichever gives us the best chance of the offset
1775         // being in range for direct access. If the FPOffset is positive,
1776         // that'll always be best, as the SP will be even further away.
1777         UseFP = true;
1778       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
1779         // Funclets access the locals contained in the parent's stack frame
1780         // via the frame pointer, so we have to use the FP in the parent
1781         // function.
1782         (void) Subtarget;
1783         assert(
1784             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
1785             "Funclets should only be present on Win64");
1786         UseFP = true;
1787       } else {
1788         // We have the choice between FP and (SP or BP).
1789         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1790           UseFP = true;
1791       }
1792     }
1793   }
1794 
1795   assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
1796          "In the presence of dynamic stack pointer realignment, "
1797          "non-argument/CSR objects cannot be accessed through the frame pointer");
1798 
1799   if (isSVE) {
1800     int64_t OffsetToSVEArea =
1801         MFI.getStackSize() - AFI->getCalleeSavedStackSize();
1802     StackOffset FPOffset = {ObjectOffset, MVT::nxv1i8};
1803     StackOffset SPOffset = SVEStackSize +
1804                            StackOffset(ObjectOffset, MVT::nxv1i8) +
1805                            StackOffset(OffsetToSVEArea, MVT::i8);
1806     // Always use the FP for SVE spills if available and beneficial.
1807     if (hasFP(MF) &&
1808         (SPOffset.getBytes() ||
1809          FPOffset.getScalableBytes() < SPOffset.getScalableBytes() ||
1810          RegInfo->needsStackRealignment(MF))) {
1811       FrameReg = RegInfo->getFrameRegister(MF);
1812       return FPOffset;
1813     }
1814 
1815     FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
1816                                            : (unsigned)AArch64::SP;
1817     return SPOffset;
1818   }
1819 
1820   StackOffset ScalableOffset = {};
1821   if (UseFP && !(isFixed || isCSR))
1822     ScalableOffset = -SVEStackSize;
1823   if (!UseFP && (isFixed || isCSR))
1824     ScalableOffset = SVEStackSize;
1825 
1826   if (UseFP) {
1827     FrameReg = RegInfo->getFrameRegister(MF);
1828     return StackOffset(FPOffset, MVT::i8) + ScalableOffset;
1829   }
1830 
1831   // Use the base pointer if we have one.
1832   if (RegInfo->hasBasePointer(MF))
1833     FrameReg = RegInfo->getBaseRegister();
1834   else {
1835     assert(!MFI.hasVarSizedObjects() &&
1836            "Can't use SP when we have var sized objects.");
1837     FrameReg = AArch64::SP;
1838     // If we're using the red zone for this function, the SP won't actually
1839     // be adjusted, so the offsets will be negative. They're also all
1840     // within range of the signed 9-bit immediate instructions.
1841     if (canUseRedZone(MF))
1842       Offset -= AFI->getLocalStackSize();
1843   }
1844 
1845   return StackOffset(Offset, MVT::i8) + ScalableOffset;
1846 }
1847 
1848 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
1849   // Do not set a kill flag on values that are also marked as live-in. This
1850   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1851   // callee saved registers.
1852   // Omitting the kill flags is conservatively correct even if the live-in
1853   // is not used after all.
1854   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1855   return getKillRegState(!IsLiveIn);
1856 }
1857 
1858 static bool produceCompactUnwindFrame(MachineFunction &MF) {
1859   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1860   AttributeList Attrs = MF.getFunction().getAttributes();
1861   return Subtarget.isTargetMachO() &&
1862          !(Subtarget.getTargetLowering()->supportSwiftError() &&
1863            Attrs.hasAttrSomewhere(Attribute::SwiftError));
1864 }
1865 
1866 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
1867                                              bool NeedsWinCFI) {
1868   // If we are generating register pairs for a Windows function that requires
1869   // EH support, then pair consecutive registers only.  There are no unwind
1870   // opcodes for saves/restores of non-consectuve register pairs.
1871   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x.
1872   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1873 
1874   // TODO: LR can be paired with any register.  We don't support this yet in
1875   // the MCLayer.  We need to add support for the save_lrpair unwind code.
1876   if (!NeedsWinCFI)
1877     return false;
1878   if (Reg2 == Reg1 + 1)
1879     return false;
1880   return true;
1881 }
1882 
1883 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
1884 /// WindowsCFI requires that only consecutive registers can be paired.
1885 /// LR and FP need to be allocated together when the frame needs to save
1886 /// the frame-record. This means any other register pairing with LR is invalid.
1887 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
1888                                       bool NeedsWinCFI, bool NeedsFrameRecord) {
1889   if (NeedsWinCFI)
1890     return invalidateWindowsRegisterPairing(Reg1, Reg2, true);
1891 
1892   // If we need to store the frame record, don't pair any register
1893   // with LR other than FP.
1894   if (NeedsFrameRecord)
1895     return Reg2 == AArch64::LR;
1896 
1897   return false;
1898 }
1899 
1900 namespace {
1901 
1902 struct RegPairInfo {
1903   unsigned Reg1 = AArch64::NoRegister;
1904   unsigned Reg2 = AArch64::NoRegister;
1905   int FrameIdx;
1906   int Offset;
1907   enum RegType { GPR, FPR64, FPR128, PPR, ZPR } Type;
1908 
1909   RegPairInfo() = default;
1910 
1911   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
1912 
1913   unsigned getScale() const {
1914     switch (Type) {
1915     case PPR:
1916       return 2;
1917     case GPR:
1918     case FPR64:
1919       return 8;
1920     case ZPR:
1921     case FPR128:
1922       return 16;
1923     }
1924     llvm_unreachable("Unsupported type");
1925   }
1926 
1927   bool isScalable() const { return Type == PPR || Type == ZPR; }
1928 };
1929 
1930 } // end anonymous namespace
1931 
1932 static void computeCalleeSaveRegisterPairs(
1933     MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
1934     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
1935     bool &NeedShadowCallStackProlog, bool NeedsFrameRecord) {
1936 
1937   if (CSI.empty())
1938     return;
1939 
1940   bool NeedsWinCFI = needsWinCFI(MF);
1941   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1942   MachineFrameInfo &MFI = MF.getFrameInfo();
1943   CallingConv::ID CC = MF.getFunction().getCallingConv();
1944   unsigned Count = CSI.size();
1945   (void)CC;
1946   // MachO's compact unwind format relies on all registers being stored in
1947   // pairs.
1948   assert((!produceCompactUnwindFrame(MF) ||
1949           CC == CallingConv::PreserveMost ||
1950           (Count & 1) == 0) &&
1951          "Odd number of callee-saved regs to spill!");
1952   int ByteOffset = AFI->getCalleeSavedStackSize();
1953   int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
1954   // On Linux, we will have either one or zero non-paired register.  On Windows
1955   // with CFI, we can have multiple unpaired registers in order to utilize the
1956   // available unwind codes.  This flag assures that the alignment fixup is done
1957   // only once, as intened.
1958   bool FixupDone = false;
1959   for (unsigned i = 0; i < Count; ++i) {
1960     RegPairInfo RPI;
1961     RPI.Reg1 = CSI[i].getReg();
1962 
1963     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
1964       RPI.Type = RegPairInfo::GPR;
1965     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
1966       RPI.Type = RegPairInfo::FPR64;
1967     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
1968       RPI.Type = RegPairInfo::FPR128;
1969     else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
1970       RPI.Type = RegPairInfo::ZPR;
1971     else if (AArch64::PPRRegClass.contains(RPI.Reg1))
1972       RPI.Type = RegPairInfo::PPR;
1973     else
1974       llvm_unreachable("Unsupported register class.");
1975 
1976     // Add the next reg to the pair if it is in the same register class.
1977     if (i + 1 < Count) {
1978       unsigned NextReg = CSI[i + 1].getReg();
1979       switch (RPI.Type) {
1980       case RegPairInfo::GPR:
1981         if (AArch64::GPR64RegClass.contains(NextReg) &&
1982             !invalidateRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI,
1983                                        NeedsFrameRecord))
1984           RPI.Reg2 = NextReg;
1985         break;
1986       case RegPairInfo::FPR64:
1987         if (AArch64::FPR64RegClass.contains(NextReg) &&
1988             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
1989           RPI.Reg2 = NextReg;
1990         break;
1991       case RegPairInfo::FPR128:
1992         if (AArch64::FPR128RegClass.contains(NextReg))
1993           RPI.Reg2 = NextReg;
1994         break;
1995       case RegPairInfo::PPR:
1996       case RegPairInfo::ZPR:
1997         break;
1998       }
1999     }
2000 
2001     // If either of the registers to be saved is the lr register, it means that
2002     // we also need to save lr in the shadow call stack.
2003     if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
2004         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
2005       if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
2006         report_fatal_error("Must reserve x18 to use shadow call stack");
2007       NeedShadowCallStackProlog = true;
2008     }
2009 
2010     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
2011     // list to come in sorted by frame index so that we can issue the store
2012     // pair instructions directly. Assert if we see anything otherwise.
2013     //
2014     // The order of the registers in the list is controlled by
2015     // getCalleeSavedRegs(), so they will always be in-order, as well.
2016     assert((!RPI.isPaired() ||
2017             (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
2018            "Out of order callee saved regs!");
2019 
2020     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
2021             RPI.Reg1 == AArch64::LR) &&
2022            "FrameRecord must be allocated together with LR");
2023 
2024     // MachO's compact unwind format relies on all registers being stored in
2025     // adjacent register pairs.
2026     assert((!produceCompactUnwindFrame(MF) ||
2027             CC == CallingConv::PreserveMost ||
2028             (RPI.isPaired() &&
2029              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
2030               RPI.Reg1 + 1 == RPI.Reg2))) &&
2031            "Callee-save registers not saved as adjacent register pair!");
2032 
2033     RPI.FrameIdx = CSI[i].getFrameIdx();
2034 
2035     int Scale = RPI.getScale();
2036     if (RPI.isScalable())
2037       ScalableByteOffset -= Scale;
2038     else
2039       ByteOffset -= RPI.isPaired() ? 2 * Scale : Scale;
2040 
2041     assert(!(RPI.isScalable() && RPI.isPaired()) &&
2042            "Paired spill/fill instructions don't exist for SVE vectors");
2043 
2044     // Round up size of non-pair to pair size if we need to pad the
2045     // callee-save area to ensure 16-byte alignment.
2046     if (AFI->hasCalleeSaveStackFreeSpace() && !FixupDone &&
2047         !RPI.isScalable() && RPI.Type != RegPairInfo::FPR128 &&
2048         !RPI.isPaired()) {
2049       FixupDone = true;
2050       ByteOffset -= 8;
2051       assert(ByteOffset % 16 == 0);
2052       assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
2053       MFI.setObjectAlignment(RPI.FrameIdx, 16);
2054     }
2055 
2056     int Offset = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2057     assert(Offset % Scale == 0);
2058     RPI.Offset = Offset / Scale;
2059 
2060     assert(((!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
2061             (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
2062            "Offset out of bounds for LDP/STP immediate");
2063 
2064     RegPairs.push_back(RPI);
2065     if (RPI.isPaired())
2066       ++i;
2067   }
2068 }
2069 
2070 bool AArch64FrameLowering::spillCalleeSavedRegisters(
2071     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2072     const std::vector<CalleeSavedInfo> &CSI,
2073     const TargetRegisterInfo *TRI) const {
2074   MachineFunction &MF = *MBB.getParent();
2075   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2076   bool NeedsWinCFI = needsWinCFI(MF);
2077   DebugLoc DL;
2078   SmallVector<RegPairInfo, 8> RegPairs;
2079 
2080   bool NeedShadowCallStackProlog = false;
2081   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
2082                                  NeedShadowCallStackProlog, hasFP(MF));
2083   const MachineRegisterInfo &MRI = MF.getRegInfo();
2084 
2085   if (NeedShadowCallStackProlog) {
2086     // Shadow call stack prolog: str x30, [x18], #8
2087     BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
2088         .addReg(AArch64::X18, RegState::Define)
2089         .addReg(AArch64::LR)
2090         .addReg(AArch64::X18)
2091         .addImm(8)
2092         .setMIFlag(MachineInstr::FrameSetup);
2093 
2094     if (NeedsWinCFI)
2095       BuildMI(MBB, MI, DL, TII.get(AArch64::SEH_Nop))
2096           .setMIFlag(MachineInstr::FrameSetup);
2097 
2098     if (!MF.getFunction().hasFnAttribute(Attribute::NoUnwind)) {
2099       // Emit a CFI instruction that causes 8 to be subtracted from the value of
2100       // x18 when unwinding past this frame.
2101       static const char CFIInst[] = {
2102           dwarf::DW_CFA_val_expression,
2103           18, // register
2104           2,  // length
2105           static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
2106           static_cast<char>(-8) & 0x7f, // addend (sleb128)
2107       };
2108       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
2109           nullptr, StringRef(CFIInst, sizeof(CFIInst))));
2110       BuildMI(MBB, MI, DL, TII.get(AArch64::CFI_INSTRUCTION))
2111           .addCFIIndex(CFIIndex)
2112           .setMIFlag(MachineInstr::FrameSetup);
2113     }
2114 
2115     // This instruction also makes x18 live-in to the entry block.
2116     MBB.addLiveIn(AArch64::X18);
2117   }
2118 
2119   for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
2120        ++RPII) {
2121     RegPairInfo RPI = *RPII;
2122     unsigned Reg1 = RPI.Reg1;
2123     unsigned Reg2 = RPI.Reg2;
2124     unsigned StrOpc;
2125 
2126     // Issue sequence of spills for cs regs.  The first spill may be converted
2127     // to a pre-decrement store later by emitPrologue if the callee-save stack
2128     // area allocation can't be combined with the local stack area allocation.
2129     // For example:
2130     //    stp     x22, x21, [sp, #0]     // addImm(+0)
2131     //    stp     x20, x19, [sp, #16]    // addImm(+2)
2132     //    stp     fp, lr, [sp, #32]      // addImm(+4)
2133     // Rationale: This sequence saves uop updates compared to a sequence of
2134     // pre-increment spills like stp xi,xj,[sp,#-16]!
2135     // Note: Similar rationale and sequence for restores in epilog.
2136     unsigned Size, Align;
2137     switch (RPI.Type) {
2138     case RegPairInfo::GPR:
2139        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
2140        Size = 8;
2141        Align = 8;
2142        break;
2143     case RegPairInfo::FPR64:
2144        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
2145        Size = 8;
2146        Align = 8;
2147        break;
2148     case RegPairInfo::FPR128:
2149        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
2150        Size = 16;
2151        Align = 16;
2152        break;
2153     case RegPairInfo::ZPR:
2154        StrOpc = AArch64::STR_ZXI;
2155        Size = 16;
2156        Align = 16;
2157        break;
2158     case RegPairInfo::PPR:
2159        StrOpc = AArch64::STR_PXI;
2160        Size = 2;
2161        Align = 2;
2162        break;
2163     }
2164     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
2165                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2166                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2167                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2168                dbgs() << ")\n");
2169 
2170     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
2171            "Windows unwdinding requires a consecutive (FP,LR) pair");
2172     // Windows unwind codes require consecutive registers if registers are
2173     // paired.  Make the switch here, so that the code below will save (x,x+1)
2174     // and not (x+1,x).
2175     unsigned FrameIdxReg1 = RPI.FrameIdx;
2176     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2177     if (NeedsWinCFI && RPI.isPaired()) {
2178       std::swap(Reg1, Reg2);
2179       std::swap(FrameIdxReg1, FrameIdxReg2);
2180     }
2181     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
2182     if (!MRI.isReserved(Reg1))
2183       MBB.addLiveIn(Reg1);
2184     if (RPI.isPaired()) {
2185       if (!MRI.isReserved(Reg2))
2186         MBB.addLiveIn(Reg2);
2187       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
2188       MIB.addMemOperand(MF.getMachineMemOperand(
2189           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2190           MachineMemOperand::MOStore, Size, Align));
2191     }
2192     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
2193         .addReg(AArch64::SP)
2194         .addImm(RPI.Offset) // [sp, #offset*scale],
2195                             // where factor*scale is implicit
2196         .setMIFlag(MachineInstr::FrameSetup);
2197     MIB.addMemOperand(MF.getMachineMemOperand(
2198         MachinePointerInfo::getFixedStack(MF,FrameIdxReg1),
2199         MachineMemOperand::MOStore, Size, Align));
2200     if (NeedsWinCFI)
2201       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
2202 
2203     // Update the StackIDs of the SVE stack slots.
2204     MachineFrameInfo &MFI = MF.getFrameInfo();
2205     if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR)
2206       MFI.setStackID(RPI.FrameIdx, TargetStackID::SVEVector);
2207 
2208   }
2209   return true;
2210 }
2211 
2212 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
2213     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2214     std::vector<CalleeSavedInfo> &CSI,
2215     const TargetRegisterInfo *TRI) const {
2216   MachineFunction &MF = *MBB.getParent();
2217   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2218   DebugLoc DL;
2219   SmallVector<RegPairInfo, 8> RegPairs;
2220   bool NeedsWinCFI = needsWinCFI(MF);
2221 
2222   if (MI != MBB.end())
2223     DL = MI->getDebugLoc();
2224 
2225   bool NeedShadowCallStackProlog = false;
2226   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
2227                                  NeedShadowCallStackProlog, hasFP(MF));
2228 
2229   auto EmitMI = [&](const RegPairInfo &RPI) {
2230     unsigned Reg1 = RPI.Reg1;
2231     unsigned Reg2 = RPI.Reg2;
2232 
2233     // Issue sequence of restores for cs regs. The last restore may be converted
2234     // to a post-increment load later by emitEpilogue if the callee-save stack
2235     // area allocation can't be combined with the local stack area allocation.
2236     // For example:
2237     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
2238     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
2239     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
2240     // Note: see comment in spillCalleeSavedRegisters()
2241     unsigned LdrOpc;
2242     unsigned Size, Align;
2243     switch (RPI.Type) {
2244     case RegPairInfo::GPR:
2245        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
2246        Size = 8;
2247        Align = 8;
2248        break;
2249     case RegPairInfo::FPR64:
2250        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
2251        Size = 8;
2252        Align = 8;
2253        break;
2254     case RegPairInfo::FPR128:
2255        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
2256        Size = 16;
2257        Align = 16;
2258        break;
2259     case RegPairInfo::ZPR:
2260        LdrOpc = AArch64::LDR_ZXI;
2261        Size = 16;
2262        Align = 16;
2263        break;
2264     case RegPairInfo::PPR:
2265        LdrOpc = AArch64::LDR_PXI;
2266        Size = 2;
2267        Align = 2;
2268        break;
2269     }
2270     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
2271                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2272                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2273                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2274                dbgs() << ")\n");
2275 
2276     // Windows unwind codes require consecutive registers if registers are
2277     // paired.  Make the switch here, so that the code below will save (x,x+1)
2278     // and not (x+1,x).
2279     unsigned FrameIdxReg1 = RPI.FrameIdx;
2280     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2281     if (NeedsWinCFI && RPI.isPaired()) {
2282       std::swap(Reg1, Reg2);
2283       std::swap(FrameIdxReg1, FrameIdxReg2);
2284     }
2285     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
2286     if (RPI.isPaired()) {
2287       MIB.addReg(Reg2, getDefRegState(true));
2288       MIB.addMemOperand(MF.getMachineMemOperand(
2289           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2290           MachineMemOperand::MOLoad, Size, Align));
2291     }
2292     MIB.addReg(Reg1, getDefRegState(true))
2293         .addReg(AArch64::SP)
2294         .addImm(RPI.Offset) // [sp, #offset*scale]
2295                             // where factor*scale is implicit
2296         .setMIFlag(MachineInstr::FrameDestroy);
2297     MIB.addMemOperand(MF.getMachineMemOperand(
2298         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2299         MachineMemOperand::MOLoad, Size, Align));
2300     if (NeedsWinCFI)
2301       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
2302   };
2303 
2304   // SVE objects are always restored in reverse order.
2305   for (const RegPairInfo &RPI : reverse(RegPairs))
2306     if (RPI.isScalable())
2307       EmitMI(RPI);
2308 
2309   if (ReverseCSRRestoreSeq) {
2310     for (const RegPairInfo &RPI : reverse(RegPairs))
2311       if (!RPI.isScalable())
2312         EmitMI(RPI);
2313   } else
2314     for (const RegPairInfo &RPI : RegPairs)
2315       if (!RPI.isScalable())
2316         EmitMI(RPI);
2317 
2318   if (NeedShadowCallStackProlog) {
2319     // Shadow call stack epilog: ldr x30, [x18, #-8]!
2320     BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
2321         .addReg(AArch64::X18, RegState::Define)
2322         .addReg(AArch64::LR, RegState::Define)
2323         .addReg(AArch64::X18)
2324         .addImm(-8)
2325         .setMIFlag(MachineInstr::FrameDestroy);
2326   }
2327 
2328   return true;
2329 }
2330 
2331 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
2332                                                 BitVector &SavedRegs,
2333                                                 RegScavenger *RS) const {
2334   // All calls are tail calls in GHC calling conv, and functions have no
2335   // prologue/epilogue.
2336   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
2337     return;
2338 
2339   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2340   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
2341       MF.getSubtarget().getRegisterInfo());
2342   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2343   unsigned UnspilledCSGPR = AArch64::NoRegister;
2344   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
2345 
2346   MachineFrameInfo &MFI = MF.getFrameInfo();
2347   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2348 
2349   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
2350                                 ? RegInfo->getBaseRegister()
2351                                 : (unsigned)AArch64::NoRegister;
2352 
2353   unsigned ExtraCSSpill = 0;
2354   // Figure out which callee-saved registers to save/restore.
2355   for (unsigned i = 0; CSRegs[i]; ++i) {
2356     const unsigned Reg = CSRegs[i];
2357 
2358     // Add the base pointer register to SavedRegs if it is callee-save.
2359     if (Reg == BasePointerReg)
2360       SavedRegs.set(Reg);
2361 
2362     bool RegUsed = SavedRegs.test(Reg);
2363     unsigned PairedReg = AArch64::NoRegister;
2364     if (AArch64::GPR64RegClass.contains(Reg) ||
2365         AArch64::FPR64RegClass.contains(Reg) ||
2366         AArch64::FPR128RegClass.contains(Reg))
2367       PairedReg = CSRegs[i ^ 1];
2368 
2369     if (!RegUsed) {
2370       if (AArch64::GPR64RegClass.contains(Reg) &&
2371           !RegInfo->isReservedReg(MF, Reg)) {
2372         UnspilledCSGPR = Reg;
2373         UnspilledCSGPRPaired = PairedReg;
2374       }
2375       continue;
2376     }
2377 
2378     // MachO's compact unwind format relies on all registers being stored in
2379     // pairs.
2380     // FIXME: the usual format is actually better if unwinding isn't needed.
2381     if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister &&
2382         !SavedRegs.test(PairedReg)) {
2383       SavedRegs.set(PairedReg);
2384       if (AArch64::GPR64RegClass.contains(PairedReg) &&
2385           !RegInfo->isReservedReg(MF, PairedReg))
2386         ExtraCSSpill = PairedReg;
2387     }
2388   }
2389 
2390   // Calculates the callee saved stack size.
2391   unsigned CSStackSize = 0;
2392   unsigned SVECSStackSize = 0;
2393   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2394   const MachineRegisterInfo &MRI = MF.getRegInfo();
2395   for (unsigned Reg : SavedRegs.set_bits()) {
2396     auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
2397     if (AArch64::PPRRegClass.contains(Reg) ||
2398         AArch64::ZPRRegClass.contains(Reg))
2399       SVECSStackSize += RegSize;
2400     else
2401       CSStackSize += RegSize;
2402   }
2403 
2404   // Save number of saved regs, so we can easily update CSStackSize later.
2405   unsigned NumSavedRegs = SavedRegs.count();
2406 
2407   // The frame record needs to be created by saving the appropriate registers
2408   unsigned EstimatedStackSize = MFI.estimateStackSize(MF);
2409   if (hasFP(MF) ||
2410       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2411     SavedRegs.set(AArch64::FP);
2412     SavedRegs.set(AArch64::LR);
2413   }
2414 
2415   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
2416              for (unsigned Reg
2417                   : SavedRegs.set_bits()) dbgs()
2418              << ' ' << printReg(Reg, RegInfo);
2419              dbgs() << "\n";);
2420 
2421   // If any callee-saved registers are used, the frame cannot be eliminated.
2422   int64_t SVEStackSize =
2423       alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
2424   bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
2425 
2426   // The CSR spill slots have not been allocated yet, so estimateStackSize
2427   // won't include them.
2428   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2429 
2430   // Conservatively always assume BigStack when there are SVE spills.
2431   bool BigStack = SVEStackSize ||
2432                   (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
2433   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2434     AFI->setHasStackFrame(true);
2435 
2436   // Estimate if we might need to scavenge a register at some point in order
2437   // to materialize a stack offset. If so, either spill one additional
2438   // callee-saved register or reserve a special spill slot to facilitate
2439   // register scavenging. If we already spilled an extra callee-saved register
2440   // above to keep the number of spills even, we don't need to do anything else
2441   // here.
2442   if (BigStack) {
2443     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
2444       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2445                         << " to get a scratch register.\n");
2446       SavedRegs.set(UnspilledCSGPR);
2447       // MachO's compact unwind format relies on all registers being stored in
2448       // pairs, so if we need to spill one extra for BigStack, then we need to
2449       // store the pair.
2450       if (produceCompactUnwindFrame(MF))
2451         SavedRegs.set(UnspilledCSGPRPaired);
2452       ExtraCSSpill = UnspilledCSGPR;
2453     }
2454 
2455     // If we didn't find an extra callee-saved register to spill, create
2456     // an emergency spill slot.
2457     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2458       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2459       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2460       unsigned Size = TRI->getSpillSize(RC);
2461       unsigned Align = TRI->getSpillAlignment(RC);
2462       int FI = MFI.CreateStackObject(Size, Align, false);
2463       RS->addScavengingFrameIndex(FI);
2464       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2465                         << " as the emergency spill slot.\n");
2466     }
2467   }
2468 
2469   // Adding the size of additional 64bit GPR saves.
2470   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2471   unsigned AlignedCSStackSize = alignTo(CSStackSize, 16);
2472   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2473                << EstimatedStackSize + AlignedCSStackSize
2474                << " bytes.\n");
2475 
2476   assert((!MFI.isCalleeSavedInfoValid() ||
2477           AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
2478          "Should not invalidate callee saved info");
2479 
2480   // Round up to register pair alignment to avoid additional SP adjustment
2481   // instructions.
2482   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2483   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2484   AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
2485 }
2486 
2487 bool AArch64FrameLowering::enableStackSlotScavenging(
2488     const MachineFunction &MF) const {
2489   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2490   return AFI->hasCalleeSaveStackFreeSpace();
2491 }
2492 
2493 /// returns true if there are any SVE callee saves.
2494 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
2495                                       int &Min, int &Max) {
2496   Min = std::numeric_limits<int>::max();
2497   Max = std::numeric_limits<int>::min();
2498 
2499   if (!MFI.isCalleeSavedInfoValid())
2500     return false;
2501 
2502   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2503   for (auto &CS : CSI) {
2504     if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
2505         AArch64::PPRRegClass.contains(CS.getReg())) {
2506       assert((Max == std::numeric_limits<int>::min() ||
2507               Max + 1 == CS.getFrameIdx()) &&
2508              "SVE CalleeSaves are not consecutive");
2509 
2510       Min = std::min(Min, CS.getFrameIdx());
2511       Max = std::max(Max, CS.getFrameIdx());
2512     }
2513   }
2514   return Min != std::numeric_limits<int>::max();
2515 }
2516 
2517 // Process all the SVE stack objects and determine offsets for each
2518 // object. If AssignOffsets is true, the offsets get assigned.
2519 // Fills in the first and last callee-saved frame indices into
2520 // Min/MaxCSFrameIndex, respectively.
2521 // Returns the size of the stack.
2522 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
2523                                               int &MinCSFrameIndex,
2524                                               int &MaxCSFrameIndex,
2525                                               bool AssignOffsets) {
2526   // First process all fixed stack objects.
2527   int64_t Offset = 0;
2528   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
2529     if (MFI.getStackID(I) == TargetStackID::SVEVector) {
2530       int64_t FixedOffset = -MFI.getObjectOffset(I);
2531       if (FixedOffset > Offset)
2532         Offset = FixedOffset;
2533     }
2534 
2535   auto Assign = [&MFI](int FI, int64_t Offset) {
2536     LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
2537     MFI.setObjectOffset(FI, Offset);
2538   };
2539 
2540   // Then process all callee saved slots.
2541   if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
2542     // Make sure to align the last callee save slot.
2543     MFI.setObjectAlignment(MaxCSFrameIndex, 16U);
2544 
2545     // Assign offsets to the callee save slots.
2546     for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
2547       Offset += MFI.getObjectSize(I);
2548       Offset = alignTo(Offset, MFI.getObjectAlignment(I));
2549       if (AssignOffsets)
2550         Assign(I, -Offset);
2551     }
2552   }
2553 
2554   // Create a buffer of SVE objects to allocate and sort it.
2555   SmallVector<int, 8> ObjectsToAllocate;
2556   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
2557     unsigned StackID = MFI.getStackID(I);
2558     if (StackID != TargetStackID::SVEVector)
2559       continue;
2560     if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
2561       continue;
2562     if (MFI.isDeadObjectIndex(I))
2563       continue;
2564 
2565     ObjectsToAllocate.push_back(I);
2566   }
2567 
2568   // Allocate all SVE locals and spills
2569   for (unsigned FI : ObjectsToAllocate) {
2570     unsigned Align = MFI.getObjectAlignment(FI);
2571     // FIXME: Given that the length of SVE vectors is not necessarily a power of
2572     // two, we'd need to align every object dynamically at runtime if the
2573     // alignment is larger than 16. This is not yet supported.
2574     if (Align > 16)
2575       report_fatal_error(
2576           "Alignment of scalable vectors > 16 bytes is not yet supported");
2577 
2578     Offset = alignTo(Offset + MFI.getObjectSize(FI), Align);
2579     if (AssignOffsets)
2580       Assign(FI, -Offset);
2581   }
2582 
2583   return Offset;
2584 }
2585 
2586 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
2587     MachineFrameInfo &MFI) const {
2588   int MinCSFrameIndex, MaxCSFrameIndex;
2589   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
2590 }
2591 
2592 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
2593     MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
2594   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
2595                                         true);
2596 }
2597 
2598 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
2599     MachineFunction &MF, RegScavenger *RS) const {
2600   MachineFrameInfo &MFI = MF.getFrameInfo();
2601 
2602   assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
2603          "Upwards growing stack unsupported");
2604 
2605   int MinCSFrameIndex, MaxCSFrameIndex;
2606   int64_t SVEStackSize =
2607       assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
2608 
2609   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2610   AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
2611   AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
2612 
2613   // If this function isn't doing Win64-style C++ EH, we don't need to do
2614   // anything.
2615   if (!MF.hasEHFunclets())
2616     return;
2617   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2618   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
2619 
2620   MachineBasicBlock &MBB = MF.front();
2621   auto MBBI = MBB.begin();
2622   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2623     ++MBBI;
2624 
2625   // Create an UnwindHelp object.
2626   int UnwindHelpFI =
2627       MFI.CreateStackObject(/*size*/8, /*alignment*/16, false);
2628   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
2629   // We need to store -2 into the UnwindHelp object at the start of the
2630   // function.
2631   DebugLoc DL;
2632   RS->enterBasicBlockEnd(MBB);
2633   RS->backward(std::prev(MBBI));
2634   unsigned DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
2635   assert(DstReg && "There must be a free register after frame setup");
2636   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
2637   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
2638       .addReg(DstReg, getKillRegState(true))
2639       .addFrameIndex(UnwindHelpFI)
2640       .addImm(0);
2641 }
2642 
2643 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP before
2644 /// the update.  This is easily retrieved as it is exactly the offset that is set
2645 /// in processFunctionBeforeFrameFinalized.
2646 int AArch64FrameLowering::getFrameIndexReferencePreferSP(
2647     const MachineFunction &MF, int FI, unsigned &FrameReg,
2648     bool IgnoreSPUpdates) const {
2649   const MachineFrameInfo &MFI = MF.getFrameInfo();
2650   LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
2651                     << MFI.getObjectOffset(FI) << "\n");
2652   FrameReg = AArch64::SP;
2653   return MFI.getObjectOffset(FI);
2654 }
2655 
2656 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
2657 /// the parent's frame pointer
2658 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
2659     const MachineFunction &MF) const {
2660   return 0;
2661 }
2662 
2663 /// Funclets only need to account for space for the callee saved registers,
2664 /// as the locals are accounted for in the parent's stack frame.
2665 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
2666     const MachineFunction &MF) const {
2667   // This is the size of the pushed CSRs.
2668   unsigned CSSize =
2669       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
2670   // This is the amount of stack a funclet needs to allocate.
2671   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
2672                  getStackAlignment());
2673 }
2674