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