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