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           assert(!SVEStackSize && "Expected BP to be available");
1823           UseFP = true;
1824         }
1825         // else we can use BP and FP, but the offset from FP won't fit.
1826         // That will make us scavenge registers which we can probably avoid by
1827         // using BP. If it won't fit for BP either, we'll scavenge anyway.
1828       } else if (FPOffset >= 0) {
1829         // Use SP or FP, whichever gives us the best chance of the offset
1830         // being in range for direct access. If the FPOffset is positive,
1831         // that'll always be best, as the SP will be even further away.
1832         UseFP = true;
1833       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
1834         // Funclets access the locals contained in the parent's stack frame
1835         // via the frame pointer, so we have to use the FP in the parent
1836         // function.
1837         (void) Subtarget;
1838         assert(
1839             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
1840             "Funclets should only be present on Win64");
1841         UseFP = true;
1842       } else {
1843         // We have the choice between FP and (SP or BP).
1844         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1845           UseFP = true;
1846       }
1847     }
1848   }
1849 
1850   assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
1851          "In the presence of dynamic stack pointer realignment, "
1852          "non-argument/CSR objects cannot be accessed through the frame pointer");
1853 
1854   if (isSVE) {
1855     int64_t OffsetToSVEArea =
1856         MFI.getStackSize() - AFI->getCalleeSavedStackSize();
1857     StackOffset FPOffset = {ObjectOffset, MVT::nxv1i8};
1858     StackOffset SPOffset = SVEStackSize +
1859                            StackOffset(ObjectOffset, MVT::nxv1i8) +
1860                            StackOffset(OffsetToSVEArea, MVT::i8);
1861     // Always use the FP for SVE spills if available and beneficial.
1862     if (hasFP(MF) &&
1863         (SPOffset.getBytes() ||
1864          FPOffset.getScalableBytes() < SPOffset.getScalableBytes() ||
1865          RegInfo->needsStackRealignment(MF))) {
1866       FrameReg = RegInfo->getFrameRegister(MF);
1867       return FPOffset;
1868     }
1869 
1870     FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
1871                                            : (unsigned)AArch64::SP;
1872     return SPOffset;
1873   }
1874 
1875   StackOffset ScalableOffset = {};
1876   if (UseFP && !(isFixed || isCSR))
1877     ScalableOffset = -SVEStackSize;
1878   if (!UseFP && (isFixed || isCSR))
1879     ScalableOffset = SVEStackSize;
1880 
1881   if (UseFP) {
1882     FrameReg = RegInfo->getFrameRegister(MF);
1883     return StackOffset(FPOffset, MVT::i8) + ScalableOffset;
1884   }
1885 
1886   // Use the base pointer if we have one.
1887   if (RegInfo->hasBasePointer(MF))
1888     FrameReg = RegInfo->getBaseRegister();
1889   else {
1890     assert(!MFI.hasVarSizedObjects() &&
1891            "Can't use SP when we have var sized objects.");
1892     FrameReg = AArch64::SP;
1893     // If we're using the red zone for this function, the SP won't actually
1894     // be adjusted, so the offsets will be negative. They're also all
1895     // within range of the signed 9-bit immediate instructions.
1896     if (canUseRedZone(MF))
1897       Offset -= AFI->getLocalStackSize();
1898   }
1899 
1900   return StackOffset(Offset, MVT::i8) + ScalableOffset;
1901 }
1902 
1903 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
1904   // Do not set a kill flag on values that are also marked as live-in. This
1905   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1906   // callee saved registers.
1907   // Omitting the kill flags is conservatively correct even if the live-in
1908   // is not used after all.
1909   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1910   return getKillRegState(!IsLiveIn);
1911 }
1912 
1913 static bool produceCompactUnwindFrame(MachineFunction &MF) {
1914   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1915   AttributeList Attrs = MF.getFunction().getAttributes();
1916   return Subtarget.isTargetMachO() &&
1917          !(Subtarget.getTargetLowering()->supportSwiftError() &&
1918            Attrs.hasAttrSomewhere(Attribute::SwiftError));
1919 }
1920 
1921 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
1922                                              bool NeedsWinCFI) {
1923   // If we are generating register pairs for a Windows function that requires
1924   // EH support, then pair consecutive registers only.  There are no unwind
1925   // opcodes for saves/restores of non-consectuve register pairs.
1926   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x.
1927   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1928 
1929   // TODO: LR can be paired with any register.  We don't support this yet in
1930   // the MCLayer.  We need to add support for the save_lrpair unwind code.
1931   if (Reg2 == AArch64::FP)
1932     return true;
1933   if (!NeedsWinCFI)
1934     return false;
1935   if (Reg2 == Reg1 + 1)
1936     return false;
1937   return true;
1938 }
1939 
1940 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
1941 /// WindowsCFI requires that only consecutive registers can be paired.
1942 /// LR and FP need to be allocated together when the frame needs to save
1943 /// the frame-record. This means any other register pairing with LR is invalid.
1944 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
1945                                       bool UsesWinAAPCS, bool NeedsWinCFI, bool NeedsFrameRecord) {
1946   if (UsesWinAAPCS)
1947     return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI);
1948 
1949   // If we need to store the frame record, don't pair any register
1950   // with LR other than FP.
1951   if (NeedsFrameRecord)
1952     return Reg2 == AArch64::LR;
1953 
1954   return false;
1955 }
1956 
1957 namespace {
1958 
1959 struct RegPairInfo {
1960   unsigned Reg1 = AArch64::NoRegister;
1961   unsigned Reg2 = AArch64::NoRegister;
1962   int FrameIdx;
1963   int Offset;
1964   enum RegType { GPR, FPR64, FPR128, PPR, ZPR } Type;
1965 
1966   RegPairInfo() = default;
1967 
1968   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
1969 
1970   unsigned getScale() const {
1971     switch (Type) {
1972     case PPR:
1973       return 2;
1974     case GPR:
1975     case FPR64:
1976       return 8;
1977     case ZPR:
1978     case FPR128:
1979       return 16;
1980     }
1981     llvm_unreachable("Unsupported type");
1982   }
1983 
1984   bool isScalable() const { return Type == PPR || Type == ZPR; }
1985 };
1986 
1987 } // end anonymous namespace
1988 
1989 static void computeCalleeSaveRegisterPairs(
1990     MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI,
1991     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
1992     bool &NeedShadowCallStackProlog, bool NeedsFrameRecord) {
1993 
1994   if (CSI.empty())
1995     return;
1996 
1997   bool IsWindows = isTargetWindows(MF);
1998   bool NeedsWinCFI = needsWinCFI(MF);
1999   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2000   MachineFrameInfo &MFI = MF.getFrameInfo();
2001   CallingConv::ID CC = MF.getFunction().getCallingConv();
2002   unsigned Count = CSI.size();
2003   (void)CC;
2004   // MachO's compact unwind format relies on all registers being stored in
2005   // pairs.
2006   assert((!produceCompactUnwindFrame(MF) ||
2007           CC == CallingConv::PreserveMost ||
2008           (Count & 1) == 0) &&
2009          "Odd number of callee-saved regs to spill!");
2010   int ByteOffset = AFI->getCalleeSavedStackSize();
2011   int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
2012   // On Linux, we will have either one or zero non-paired register.  On Windows
2013   // with CFI, we can have multiple unpaired registers in order to utilize the
2014   // available unwind codes.  This flag assures that the alignment fixup is done
2015   // only once, as intened.
2016   bool FixupDone = false;
2017   for (unsigned i = 0; i < Count; ++i) {
2018     RegPairInfo RPI;
2019     RPI.Reg1 = CSI[i].getReg();
2020 
2021     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
2022       RPI.Type = RegPairInfo::GPR;
2023     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
2024       RPI.Type = RegPairInfo::FPR64;
2025     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
2026       RPI.Type = RegPairInfo::FPR128;
2027     else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
2028       RPI.Type = RegPairInfo::ZPR;
2029     else if (AArch64::PPRRegClass.contains(RPI.Reg1))
2030       RPI.Type = RegPairInfo::PPR;
2031     else
2032       llvm_unreachable("Unsupported register class.");
2033 
2034     // Add the next reg to the pair if it is in the same register class.
2035     if (i + 1 < Count) {
2036       unsigned NextReg = CSI[i + 1].getReg();
2037       switch (RPI.Type) {
2038       case RegPairInfo::GPR:
2039         if (AArch64::GPR64RegClass.contains(NextReg) &&
2040             !invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows, NeedsWinCFI,
2041                                        NeedsFrameRecord))
2042           RPI.Reg2 = NextReg;
2043         break;
2044       case RegPairInfo::FPR64:
2045         if (AArch64::FPR64RegClass.contains(NextReg) &&
2046             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
2047           RPI.Reg2 = NextReg;
2048         break;
2049       case RegPairInfo::FPR128:
2050         if (AArch64::FPR128RegClass.contains(NextReg))
2051           RPI.Reg2 = NextReg;
2052         break;
2053       case RegPairInfo::PPR:
2054       case RegPairInfo::ZPR:
2055         break;
2056       }
2057     }
2058 
2059     // If either of the registers to be saved is the lr register, it means that
2060     // we also need to save lr in the shadow call stack.
2061     if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
2062         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
2063       if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
2064         report_fatal_error("Must reserve x18 to use shadow call stack");
2065       NeedShadowCallStackProlog = true;
2066     }
2067 
2068     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
2069     // list to come in sorted by frame index so that we can issue the store
2070     // pair instructions directly. Assert if we see anything otherwise.
2071     //
2072     // The order of the registers in the list is controlled by
2073     // getCalleeSavedRegs(), so they will always be in-order, as well.
2074     assert((!RPI.isPaired() ||
2075             (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
2076            "Out of order callee saved regs!");
2077 
2078     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
2079             RPI.Reg1 == AArch64::LR) &&
2080            "FrameRecord must be allocated together with LR");
2081 
2082     // Windows AAPCS has FP and LR reversed.
2083     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP ||
2084             RPI.Reg2 == AArch64::LR) &&
2085            "FrameRecord must be allocated together with LR");
2086 
2087     // MachO's compact unwind format relies on all registers being stored in
2088     // adjacent register pairs.
2089     assert((!produceCompactUnwindFrame(MF) ||
2090             CC == CallingConv::PreserveMost ||
2091             (RPI.isPaired() &&
2092              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
2093               RPI.Reg1 + 1 == RPI.Reg2))) &&
2094            "Callee-save registers not saved as adjacent register pair!");
2095 
2096     RPI.FrameIdx = CSI[i].getFrameIdx();
2097 
2098     int Scale = RPI.getScale();
2099     if (RPI.isScalable())
2100       ScalableByteOffset -= Scale;
2101     else
2102       ByteOffset -= RPI.isPaired() ? 2 * Scale : Scale;
2103 
2104     assert(!(RPI.isScalable() && RPI.isPaired()) &&
2105            "Paired spill/fill instructions don't exist for SVE vectors");
2106 
2107     // Round up size of non-pair to pair size if we need to pad the
2108     // callee-save area to ensure 16-byte alignment.
2109     if (AFI->hasCalleeSaveStackFreeSpace() && !FixupDone &&
2110         !RPI.isScalable() && RPI.Type != RegPairInfo::FPR128 &&
2111         !RPI.isPaired()) {
2112       FixupDone = true;
2113       ByteOffset -= 8;
2114       assert(ByteOffset % 16 == 0);
2115       assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16));
2116       MFI.setObjectAlignment(RPI.FrameIdx, Align(16));
2117     }
2118 
2119     int Offset = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2120     assert(Offset % Scale == 0);
2121     RPI.Offset = Offset / Scale;
2122 
2123     assert(((!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
2124             (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
2125            "Offset out of bounds for LDP/STP immediate");
2126 
2127     RegPairs.push_back(RPI);
2128     if (RPI.isPaired())
2129       ++i;
2130   }
2131 }
2132 
2133 bool AArch64FrameLowering::spillCalleeSavedRegisters(
2134     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2135     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2136   MachineFunction &MF = *MBB.getParent();
2137   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2138   bool NeedsWinCFI = needsWinCFI(MF);
2139   DebugLoc DL;
2140   SmallVector<RegPairInfo, 8> RegPairs;
2141 
2142   bool NeedShadowCallStackProlog = false;
2143   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
2144                                  NeedShadowCallStackProlog, hasFP(MF));
2145   const MachineRegisterInfo &MRI = MF.getRegInfo();
2146 
2147   if (NeedShadowCallStackProlog) {
2148     // Shadow call stack prolog: str x30, [x18], #8
2149     BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
2150         .addReg(AArch64::X18, RegState::Define)
2151         .addReg(AArch64::LR)
2152         .addReg(AArch64::X18)
2153         .addImm(8)
2154         .setMIFlag(MachineInstr::FrameSetup);
2155 
2156     if (NeedsWinCFI)
2157       BuildMI(MBB, MI, DL, TII.get(AArch64::SEH_Nop))
2158           .setMIFlag(MachineInstr::FrameSetup);
2159 
2160     if (!MF.getFunction().hasFnAttribute(Attribute::NoUnwind)) {
2161       // Emit a CFI instruction that causes 8 to be subtracted from the value of
2162       // x18 when unwinding past this frame.
2163       static const char CFIInst[] = {
2164           dwarf::DW_CFA_val_expression,
2165           18, // register
2166           2,  // length
2167           static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
2168           static_cast<char>(-8) & 0x7f, // addend (sleb128)
2169       };
2170       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
2171           nullptr, StringRef(CFIInst, sizeof(CFIInst))));
2172       BuildMI(MBB, MI, DL, TII.get(AArch64::CFI_INSTRUCTION))
2173           .addCFIIndex(CFIIndex)
2174           .setMIFlag(MachineInstr::FrameSetup);
2175     }
2176 
2177     // This instruction also makes x18 live-in to the entry block.
2178     MBB.addLiveIn(AArch64::X18);
2179   }
2180 
2181   for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
2182        ++RPII) {
2183     RegPairInfo RPI = *RPII;
2184     unsigned Reg1 = RPI.Reg1;
2185     unsigned Reg2 = RPI.Reg2;
2186     unsigned StrOpc;
2187 
2188     // Issue sequence of spills for cs regs.  The first spill may be converted
2189     // to a pre-decrement store later by emitPrologue if the callee-save stack
2190     // area allocation can't be combined with the local stack area allocation.
2191     // For example:
2192     //    stp     x22, x21, [sp, #0]     // addImm(+0)
2193     //    stp     x20, x19, [sp, #16]    // addImm(+2)
2194     //    stp     fp, lr, [sp, #32]      // addImm(+4)
2195     // Rationale: This sequence saves uop updates compared to a sequence of
2196     // pre-increment spills like stp xi,xj,[sp,#-16]!
2197     // Note: Similar rationale and sequence for restores in epilog.
2198     unsigned Size;
2199     Align Alignment;
2200     switch (RPI.Type) {
2201     case RegPairInfo::GPR:
2202        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
2203        Size = 8;
2204        Alignment = Align(8);
2205        break;
2206     case RegPairInfo::FPR64:
2207        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
2208        Size = 8;
2209        Alignment = Align(8);
2210        break;
2211     case RegPairInfo::FPR128:
2212        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
2213        Size = 16;
2214        Alignment = Align(16);
2215        break;
2216     case RegPairInfo::ZPR:
2217        StrOpc = AArch64::STR_ZXI;
2218        Size = 16;
2219        Alignment = Align(16);
2220        break;
2221     case RegPairInfo::PPR:
2222        StrOpc = AArch64::STR_PXI;
2223        Size = 2;
2224        Alignment = Align(2);
2225        break;
2226     }
2227     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
2228                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2229                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2230                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2231                dbgs() << ")\n");
2232 
2233     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
2234            "Windows unwdinding requires a consecutive (FP,LR) pair");
2235     // Windows unwind codes require consecutive registers if registers are
2236     // paired.  Make the switch here, so that the code below will save (x,x+1)
2237     // and not (x+1,x).
2238     unsigned FrameIdxReg1 = RPI.FrameIdx;
2239     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2240     if (NeedsWinCFI && RPI.isPaired()) {
2241       std::swap(Reg1, Reg2);
2242       std::swap(FrameIdxReg1, FrameIdxReg2);
2243     }
2244     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
2245     if (!MRI.isReserved(Reg1))
2246       MBB.addLiveIn(Reg1);
2247     if (RPI.isPaired()) {
2248       if (!MRI.isReserved(Reg2))
2249         MBB.addLiveIn(Reg2);
2250       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
2251       MIB.addMemOperand(MF.getMachineMemOperand(
2252           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2253           MachineMemOperand::MOStore, Size, Alignment));
2254     }
2255     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
2256         .addReg(AArch64::SP)
2257         .addImm(RPI.Offset) // [sp, #offset*scale],
2258                             // where factor*scale is implicit
2259         .setMIFlag(MachineInstr::FrameSetup);
2260     MIB.addMemOperand(MF.getMachineMemOperand(
2261         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2262         MachineMemOperand::MOStore, Size, Alignment));
2263     if (NeedsWinCFI)
2264       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
2265 
2266     // Update the StackIDs of the SVE stack slots.
2267     MachineFrameInfo &MFI = MF.getFrameInfo();
2268     if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR)
2269       MFI.setStackID(RPI.FrameIdx, TargetStackID::SVEVector);
2270 
2271   }
2272   return true;
2273 }
2274 
2275 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
2276     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2277     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2278   MachineFunction &MF = *MBB.getParent();
2279   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2280   DebugLoc DL;
2281   SmallVector<RegPairInfo, 8> RegPairs;
2282   bool NeedsWinCFI = needsWinCFI(MF);
2283 
2284   if (MI != MBB.end())
2285     DL = MI->getDebugLoc();
2286 
2287   bool NeedShadowCallStackProlog = false;
2288   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
2289                                  NeedShadowCallStackProlog, hasFP(MF));
2290 
2291   auto EmitMI = [&](const RegPairInfo &RPI) {
2292     unsigned Reg1 = RPI.Reg1;
2293     unsigned Reg2 = RPI.Reg2;
2294 
2295     // Issue sequence of restores for cs regs. The last restore may be converted
2296     // to a post-increment load later by emitEpilogue if the callee-save stack
2297     // area allocation can't be combined with the local stack area allocation.
2298     // For example:
2299     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
2300     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
2301     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
2302     // Note: see comment in spillCalleeSavedRegisters()
2303     unsigned LdrOpc;
2304     unsigned Size;
2305     Align Alignment;
2306     switch (RPI.Type) {
2307     case RegPairInfo::GPR:
2308        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
2309        Size = 8;
2310        Alignment = Align(8);
2311        break;
2312     case RegPairInfo::FPR64:
2313        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
2314        Size = 8;
2315        Alignment = Align(8);
2316        break;
2317     case RegPairInfo::FPR128:
2318        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
2319        Size = 16;
2320        Alignment = Align(16);
2321        break;
2322     case RegPairInfo::ZPR:
2323        LdrOpc = AArch64::LDR_ZXI;
2324        Size = 16;
2325        Alignment = Align(16);
2326        break;
2327     case RegPairInfo::PPR:
2328        LdrOpc = AArch64::LDR_PXI;
2329        Size = 2;
2330        Alignment = Align(2);
2331        break;
2332     }
2333     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
2334                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2335                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2336                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2337                dbgs() << ")\n");
2338 
2339     // Windows unwind codes require consecutive registers if registers are
2340     // paired.  Make the switch here, so that the code below will save (x,x+1)
2341     // and not (x+1,x).
2342     unsigned FrameIdxReg1 = RPI.FrameIdx;
2343     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2344     if (NeedsWinCFI && RPI.isPaired()) {
2345       std::swap(Reg1, Reg2);
2346       std::swap(FrameIdxReg1, FrameIdxReg2);
2347     }
2348     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
2349     if (RPI.isPaired()) {
2350       MIB.addReg(Reg2, getDefRegState(true));
2351       MIB.addMemOperand(MF.getMachineMemOperand(
2352           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2353           MachineMemOperand::MOLoad, Size, Alignment));
2354     }
2355     MIB.addReg(Reg1, getDefRegState(true))
2356         .addReg(AArch64::SP)
2357         .addImm(RPI.Offset) // [sp, #offset*scale]
2358                             // where factor*scale is implicit
2359         .setMIFlag(MachineInstr::FrameDestroy);
2360     MIB.addMemOperand(MF.getMachineMemOperand(
2361         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2362         MachineMemOperand::MOLoad, Size, Alignment));
2363     if (NeedsWinCFI)
2364       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
2365   };
2366 
2367   // SVE objects are always restored in reverse order.
2368   for (const RegPairInfo &RPI : reverse(RegPairs))
2369     if (RPI.isScalable())
2370       EmitMI(RPI);
2371 
2372   if (ReverseCSRRestoreSeq) {
2373     for (const RegPairInfo &RPI : reverse(RegPairs))
2374       if (!RPI.isScalable())
2375         EmitMI(RPI);
2376   } else
2377     for (const RegPairInfo &RPI : RegPairs)
2378       if (!RPI.isScalable())
2379         EmitMI(RPI);
2380 
2381   if (NeedShadowCallStackProlog) {
2382     // Shadow call stack epilog: ldr x30, [x18, #-8]!
2383     BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
2384         .addReg(AArch64::X18, RegState::Define)
2385         .addReg(AArch64::LR, RegState::Define)
2386         .addReg(AArch64::X18)
2387         .addImm(-8)
2388         .setMIFlag(MachineInstr::FrameDestroy);
2389   }
2390 
2391   return true;
2392 }
2393 
2394 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
2395                                                 BitVector &SavedRegs,
2396                                                 RegScavenger *RS) const {
2397   // All calls are tail calls in GHC calling conv, and functions have no
2398   // prologue/epilogue.
2399   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
2400     return;
2401 
2402   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2403   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
2404       MF.getSubtarget().getRegisterInfo());
2405   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2406   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2407   unsigned UnspilledCSGPR = AArch64::NoRegister;
2408   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
2409 
2410   MachineFrameInfo &MFI = MF.getFrameInfo();
2411   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2412 
2413   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
2414                                 ? RegInfo->getBaseRegister()
2415                                 : (unsigned)AArch64::NoRegister;
2416 
2417   unsigned ExtraCSSpill = 0;
2418   // Figure out which callee-saved registers to save/restore.
2419   for (unsigned i = 0; CSRegs[i]; ++i) {
2420     const unsigned Reg = CSRegs[i];
2421 
2422     // Add the base pointer register to SavedRegs if it is callee-save.
2423     if (Reg == BasePointerReg)
2424       SavedRegs.set(Reg);
2425 
2426     bool RegUsed = SavedRegs.test(Reg);
2427     unsigned PairedReg = AArch64::NoRegister;
2428     if (AArch64::GPR64RegClass.contains(Reg) ||
2429         AArch64::FPR64RegClass.contains(Reg) ||
2430         AArch64::FPR128RegClass.contains(Reg))
2431       PairedReg = CSRegs[i ^ 1];
2432 
2433     if (!RegUsed) {
2434       if (AArch64::GPR64RegClass.contains(Reg) &&
2435           !RegInfo->isReservedReg(MF, Reg)) {
2436         UnspilledCSGPR = Reg;
2437         UnspilledCSGPRPaired = PairedReg;
2438       }
2439       continue;
2440     }
2441 
2442     // MachO's compact unwind format relies on all registers being stored in
2443     // pairs.
2444     // FIXME: the usual format is actually better if unwinding isn't needed.
2445     if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister &&
2446         !SavedRegs.test(PairedReg)) {
2447       SavedRegs.set(PairedReg);
2448       if (AArch64::GPR64RegClass.contains(PairedReg) &&
2449           !RegInfo->isReservedReg(MF, PairedReg))
2450         ExtraCSSpill = PairedReg;
2451     }
2452   }
2453 
2454   if (MF.getFunction().getCallingConv() == CallingConv::Win64 &&
2455       !Subtarget.isTargetWindows()) {
2456     // For Windows calling convention on a non-windows OS, where X18 is treated
2457     // as reserved, back up X18 when entering non-windows code (marked with the
2458     // Windows calling convention) and restore when returning regardless of
2459     // whether the individual function uses it - it might call other functions
2460     // that clobber it.
2461     SavedRegs.set(AArch64::X18);
2462   }
2463 
2464   // Calculates the callee saved stack size.
2465   unsigned CSStackSize = 0;
2466   unsigned SVECSStackSize = 0;
2467   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2468   const MachineRegisterInfo &MRI = MF.getRegInfo();
2469   for (unsigned Reg : SavedRegs.set_bits()) {
2470     auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
2471     if (AArch64::PPRRegClass.contains(Reg) ||
2472         AArch64::ZPRRegClass.contains(Reg))
2473       SVECSStackSize += RegSize;
2474     else
2475       CSStackSize += RegSize;
2476   }
2477 
2478   // Save number of saved regs, so we can easily update CSStackSize later.
2479   unsigned NumSavedRegs = SavedRegs.count();
2480 
2481   // The frame record needs to be created by saving the appropriate registers
2482   uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
2483   if (hasFP(MF) ||
2484       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2485     SavedRegs.set(AArch64::FP);
2486     SavedRegs.set(AArch64::LR);
2487   }
2488 
2489   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
2490              for (unsigned Reg
2491                   : SavedRegs.set_bits()) dbgs()
2492              << ' ' << printReg(Reg, RegInfo);
2493              dbgs() << "\n";);
2494 
2495   // If any callee-saved registers are used, the frame cannot be eliminated.
2496   int64_t SVEStackSize =
2497       alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
2498   bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
2499 
2500   // The CSR spill slots have not been allocated yet, so estimateStackSize
2501   // won't include them.
2502   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2503 
2504   // Conservatively always assume BigStack when there are SVE spills.
2505   bool BigStack = SVEStackSize ||
2506                   (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
2507   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2508     AFI->setHasStackFrame(true);
2509 
2510   // Estimate if we might need to scavenge a register at some point in order
2511   // to materialize a stack offset. If so, either spill one additional
2512   // callee-saved register or reserve a special spill slot to facilitate
2513   // register scavenging. If we already spilled an extra callee-saved register
2514   // above to keep the number of spills even, we don't need to do anything else
2515   // here.
2516   if (BigStack) {
2517     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
2518       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2519                         << " to get a scratch register.\n");
2520       SavedRegs.set(UnspilledCSGPR);
2521       // MachO's compact unwind format relies on all registers being stored in
2522       // pairs, so if we need to spill one extra for BigStack, then we need to
2523       // store the pair.
2524       if (produceCompactUnwindFrame(MF))
2525         SavedRegs.set(UnspilledCSGPRPaired);
2526       ExtraCSSpill = UnspilledCSGPR;
2527     }
2528 
2529     // If we didn't find an extra callee-saved register to spill, create
2530     // an emergency spill slot.
2531     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2532       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2533       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2534       unsigned Size = TRI->getSpillSize(RC);
2535       Align Alignment = TRI->getSpillAlign(RC);
2536       int FI = MFI.CreateStackObject(Size, Alignment, false);
2537       RS->addScavengingFrameIndex(FI);
2538       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2539                         << " as the emergency spill slot.\n");
2540     }
2541   }
2542 
2543   // Adding the size of additional 64bit GPR saves.
2544   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2545   uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
2546   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2547                << EstimatedStackSize + AlignedCSStackSize
2548                << " bytes.\n");
2549 
2550   assert((!MFI.isCalleeSavedInfoValid() ||
2551           AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
2552          "Should not invalidate callee saved info");
2553 
2554   // Round up to register pair alignment to avoid additional SP adjustment
2555   // instructions.
2556   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2557   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2558   AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
2559 }
2560 
2561 bool AArch64FrameLowering::enableStackSlotScavenging(
2562     const MachineFunction &MF) const {
2563   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2564   return AFI->hasCalleeSaveStackFreeSpace();
2565 }
2566 
2567 /// returns true if there are any SVE callee saves.
2568 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
2569                                       int &Min, int &Max) {
2570   Min = std::numeric_limits<int>::max();
2571   Max = std::numeric_limits<int>::min();
2572 
2573   if (!MFI.isCalleeSavedInfoValid())
2574     return false;
2575 
2576   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2577   for (auto &CS : CSI) {
2578     if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
2579         AArch64::PPRRegClass.contains(CS.getReg())) {
2580       assert((Max == std::numeric_limits<int>::min() ||
2581               Max + 1 == CS.getFrameIdx()) &&
2582              "SVE CalleeSaves are not consecutive");
2583 
2584       Min = std::min(Min, CS.getFrameIdx());
2585       Max = std::max(Max, CS.getFrameIdx());
2586     }
2587   }
2588   return Min != std::numeric_limits<int>::max();
2589 }
2590 
2591 // Process all the SVE stack objects and determine offsets for each
2592 // object. If AssignOffsets is true, the offsets get assigned.
2593 // Fills in the first and last callee-saved frame indices into
2594 // Min/MaxCSFrameIndex, respectively.
2595 // Returns the size of the stack.
2596 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
2597                                               int &MinCSFrameIndex,
2598                                               int &MaxCSFrameIndex,
2599                                               bool AssignOffsets) {
2600   // First process all fixed stack objects.
2601   int64_t Offset = 0;
2602   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
2603     if (MFI.getStackID(I) == TargetStackID::SVEVector) {
2604       int64_t FixedOffset = -MFI.getObjectOffset(I);
2605       if (FixedOffset > Offset)
2606         Offset = FixedOffset;
2607     }
2608 
2609   auto Assign = [&MFI](int FI, int64_t Offset) {
2610     LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
2611     MFI.setObjectOffset(FI, Offset);
2612   };
2613 
2614   // Then process all callee saved slots.
2615   if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
2616     // Make sure to align the last callee save slot.
2617     MFI.setObjectAlignment(MaxCSFrameIndex, Align(16));
2618 
2619     // Assign offsets to the callee save slots.
2620     for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
2621       Offset += MFI.getObjectSize(I);
2622       Offset = alignTo(Offset, MFI.getObjectAlign(I));
2623       if (AssignOffsets)
2624         Assign(I, -Offset);
2625     }
2626   }
2627 
2628   // Create a buffer of SVE objects to allocate and sort it.
2629   SmallVector<int, 8> ObjectsToAllocate;
2630   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
2631     unsigned StackID = MFI.getStackID(I);
2632     if (StackID != TargetStackID::SVEVector)
2633       continue;
2634     if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
2635       continue;
2636     if (MFI.isDeadObjectIndex(I))
2637       continue;
2638 
2639     ObjectsToAllocate.push_back(I);
2640   }
2641 
2642   // Allocate all SVE locals and spills
2643   for (unsigned FI : ObjectsToAllocate) {
2644     Align Alignment = MFI.getObjectAlign(FI);
2645     // FIXME: Given that the length of SVE vectors is not necessarily a power of
2646     // two, we'd need to align every object dynamically at runtime if the
2647     // alignment is larger than 16. This is not yet supported.
2648     if (Alignment > Align(16))
2649       report_fatal_error(
2650           "Alignment of scalable vectors > 16 bytes is not yet supported");
2651 
2652     Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment);
2653     if (AssignOffsets)
2654       Assign(FI, -Offset);
2655   }
2656 
2657   return Offset;
2658 }
2659 
2660 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
2661     MachineFrameInfo &MFI) const {
2662   int MinCSFrameIndex, MaxCSFrameIndex;
2663   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
2664 }
2665 
2666 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
2667     MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
2668   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
2669                                         true);
2670 }
2671 
2672 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
2673     MachineFunction &MF, RegScavenger *RS) const {
2674   MachineFrameInfo &MFI = MF.getFrameInfo();
2675 
2676   assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
2677          "Upwards growing stack unsupported");
2678 
2679   int MinCSFrameIndex, MaxCSFrameIndex;
2680   int64_t SVEStackSize =
2681       assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
2682 
2683   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2684   AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
2685   AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
2686 
2687   // If this function isn't doing Win64-style C++ EH, we don't need to do
2688   // anything.
2689   if (!MF.hasEHFunclets())
2690     return;
2691   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2692   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
2693 
2694   MachineBasicBlock &MBB = MF.front();
2695   auto MBBI = MBB.begin();
2696   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2697     ++MBBI;
2698 
2699   // Create an UnwindHelp object.
2700   // The UnwindHelp object is allocated at the start of the fixed object area
2701   int64_t FixedObject =
2702       getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false);
2703   int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8,
2704                                            /*SPOffset*/ -FixedObject,
2705                                            /*IsImmutable=*/false);
2706   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
2707 
2708   // We need to store -2 into the UnwindHelp object at the start of the
2709   // function.
2710   DebugLoc DL;
2711   RS->enterBasicBlockEnd(MBB);
2712   RS->backward(std::prev(MBBI));
2713   unsigned DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
2714   assert(DstReg && "There must be a free register after frame setup");
2715   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
2716   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
2717       .addReg(DstReg, getKillRegState(true))
2718       .addFrameIndex(UnwindHelpFI)
2719       .addImm(0);
2720 }
2721 
2722 namespace {
2723 struct TagStoreInstr {
2724   MachineInstr *MI;
2725   int64_t Offset, Size;
2726   explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)
2727       : MI(MI), Offset(Offset), Size(Size) {}
2728 };
2729 
2730 class TagStoreEdit {
2731   MachineFunction *MF;
2732   MachineBasicBlock *MBB;
2733   MachineRegisterInfo *MRI;
2734   // Tag store instructions that are being replaced.
2735   SmallVector<TagStoreInstr, 8> TagStores;
2736   // Combined memref arguments of the above instructions.
2737   SmallVector<MachineMemOperand *, 8> CombinedMemRefs;
2738 
2739   // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
2740   // FrameRegOffset + Size) with the address tag of SP.
2741   Register FrameReg;
2742   StackOffset FrameRegOffset;
2743   int64_t Size;
2744   // If not None, move FrameReg to (FrameReg + FrameRegUpdate) at the end.
2745   Optional<int64_t> FrameRegUpdate;
2746   // MIFlags for any FrameReg updating instructions.
2747   unsigned FrameRegUpdateFlags;
2748 
2749   // Use zeroing instruction variants.
2750   bool ZeroData;
2751   DebugLoc DL;
2752 
2753   void emitUnrolled(MachineBasicBlock::iterator InsertI);
2754   void emitLoop(MachineBasicBlock::iterator InsertI);
2755 
2756 public:
2757   TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)
2758       : MBB(MBB), ZeroData(ZeroData) {
2759     MF = MBB->getParent();
2760     MRI = &MF->getRegInfo();
2761   }
2762   // Add an instruction to be replaced. Instructions must be added in the
2763   // ascending order of Offset, and have to be adjacent.
2764   void addInstruction(TagStoreInstr I) {
2765     assert((TagStores.empty() ||
2766             TagStores.back().Offset + TagStores.back().Size == I.Offset) &&
2767            "Non-adjacent tag store instructions.");
2768     TagStores.push_back(I);
2769   }
2770   void clear() { TagStores.clear(); }
2771   // Emit equivalent code at the given location, and erase the current set of
2772   // instructions. May skip if the replacement is not profitable. May invalidate
2773   // the input iterator and replace it with a valid one.
2774   void emitCode(MachineBasicBlock::iterator &InsertI,
2775                 const AArch64FrameLowering *TFI, bool IsLast);
2776 };
2777 
2778 void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {
2779   const AArch64InstrInfo *TII =
2780       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
2781 
2782   const int64_t kMinOffset = -256 * 16;
2783   const int64_t kMaxOffset = 255 * 16;
2784 
2785   Register BaseReg = FrameReg;
2786   int64_t BaseRegOffsetBytes = FrameRegOffset.getBytes();
2787   if (BaseRegOffsetBytes < kMinOffset ||
2788       BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset) {
2789     Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
2790     emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,
2791                     {BaseRegOffsetBytes, MVT::i8}, TII);
2792     BaseReg = ScratchReg;
2793     BaseRegOffsetBytes = 0;
2794   }
2795 
2796   MachineInstr *LastI = nullptr;
2797   while (Size) {
2798     int64_t InstrSize = (Size > 16) ? 32 : 16;
2799     unsigned Opcode =
2800         InstrSize == 16
2801             ? (ZeroData ? AArch64::STZGOffset : AArch64::STGOffset)
2802             : (ZeroData ? AArch64::STZ2GOffset : AArch64::ST2GOffset);
2803     MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))
2804                           .addReg(AArch64::SP)
2805                           .addReg(BaseReg)
2806                           .addImm(BaseRegOffsetBytes / 16)
2807                           .setMemRefs(CombinedMemRefs);
2808     // A store to [BaseReg, #0] should go last for an opportunity to fold the
2809     // final SP adjustment in the epilogue.
2810     if (BaseRegOffsetBytes == 0)
2811       LastI = I;
2812     BaseRegOffsetBytes += InstrSize;
2813     Size -= InstrSize;
2814   }
2815 
2816   if (LastI)
2817     MBB->splice(InsertI, MBB, LastI);
2818 }
2819 
2820 void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {
2821   const AArch64InstrInfo *TII =
2822       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
2823 
2824   Register BaseReg = FrameRegUpdate
2825                          ? FrameReg
2826                          : MRI->createVirtualRegister(&AArch64::GPR64RegClass);
2827   Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
2828 
2829   emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);
2830 
2831   int64_t LoopSize = Size;
2832   // If the loop size is not a multiple of 32, split off one 16-byte store at
2833   // the end to fold BaseReg update into.
2834   if (FrameRegUpdate && *FrameRegUpdate)
2835     LoopSize -= LoopSize % 32;
2836   MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,
2837                                 TII->get(ZeroData ? AArch64::STZGloop_wback
2838                                                   : AArch64::STGloop_wback))
2839                             .addDef(SizeReg)
2840                             .addDef(BaseReg)
2841                             .addImm(LoopSize)
2842                             .addReg(BaseReg)
2843                             .setMemRefs(CombinedMemRefs);
2844   if (FrameRegUpdate)
2845     LoopI->setFlags(FrameRegUpdateFlags);
2846 
2847   int64_t ExtraBaseRegUpdate =
2848       FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getBytes() - Size) : 0;
2849   if (LoopSize < Size) {
2850     assert(FrameRegUpdate);
2851     assert(Size - LoopSize == 16);
2852     // Tag 16 more bytes at BaseReg and update BaseReg.
2853     BuildMI(*MBB, InsertI, DL,
2854             TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))
2855         .addDef(BaseReg)
2856         .addReg(BaseReg)
2857         .addReg(BaseReg)
2858         .addImm(1 + ExtraBaseRegUpdate / 16)
2859         .setMemRefs(CombinedMemRefs)
2860         .setMIFlags(FrameRegUpdateFlags);
2861   } else if (ExtraBaseRegUpdate) {
2862     // Update BaseReg.
2863     BuildMI(
2864         *MBB, InsertI, DL,
2865         TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))
2866         .addDef(BaseReg)
2867         .addReg(BaseReg)
2868         .addImm(std::abs(ExtraBaseRegUpdate))
2869         .addImm(0)
2870         .setMIFlags(FrameRegUpdateFlags);
2871   }
2872 }
2873 
2874 // Check if *II is a register update that can be merged into STGloop that ends
2875 // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
2876 // end of the loop.
2877 bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,
2878                        int64_t Size, int64_t *TotalOffset) {
2879   MachineInstr &MI = *II;
2880   if ((MI.getOpcode() == AArch64::ADDXri ||
2881        MI.getOpcode() == AArch64::SUBXri) &&
2882       MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {
2883     unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());
2884     int64_t Offset = MI.getOperand(2).getImm() << Shift;
2885     if (MI.getOpcode() == AArch64::SUBXri)
2886       Offset = -Offset;
2887     int64_t AbsPostOffset = std::abs(Offset - Size);
2888     const int64_t kMaxOffset =
2889         0xFFF; // Max encoding for unshifted ADDXri / SUBXri
2890     if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) {
2891       *TotalOffset = Offset;
2892       return true;
2893     }
2894   }
2895   return false;
2896 }
2897 
2898 void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,
2899                   SmallVectorImpl<MachineMemOperand *> &MemRefs) {
2900   MemRefs.clear();
2901   for (auto &TS : TSE) {
2902     MachineInstr *MI = TS.MI;
2903     // An instruction without memory operands may access anything. Be
2904     // conservative and return an empty list.
2905     if (MI->memoperands_empty()) {
2906       MemRefs.clear();
2907       return;
2908     }
2909     MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());
2910   }
2911 }
2912 
2913 void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,
2914                             const AArch64FrameLowering *TFI, bool IsLast) {
2915   if (TagStores.empty())
2916     return;
2917   TagStoreInstr &FirstTagStore = TagStores[0];
2918   TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];
2919   Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;
2920   DL = TagStores[0].MI->getDebugLoc();
2921 
2922   Register Reg;
2923   FrameRegOffset = TFI->resolveFrameOffsetReference(
2924       *MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg,
2925       /*PreferFP=*/false, /*ForSimm=*/true);
2926   FrameReg = Reg;
2927   FrameRegUpdate = None;
2928 
2929   mergeMemRefs(TagStores, CombinedMemRefs);
2930 
2931   LLVM_DEBUG(dbgs() << "Replacing adjacent STG instructions:\n";
2932              for (const auto &Instr
2933                   : TagStores) { dbgs() << "  " << *Instr.MI; });
2934 
2935   // Size threshold where a loop becomes shorter than a linear sequence of
2936   // tagging instructions.
2937   const int kSetTagLoopThreshold = 176;
2938   if (Size < kSetTagLoopThreshold) {
2939     if (TagStores.size() < 2)
2940       return;
2941     emitUnrolled(InsertI);
2942   } else {
2943     MachineInstr *UpdateInstr = nullptr;
2944     int64_t TotalOffset;
2945     if (IsLast) {
2946       // See if we can merge base register update into the STGloop.
2947       // This is done in AArch64LoadStoreOptimizer for "normal" stores,
2948       // but STGloop is way too unusual for that, and also it only
2949       // realistically happens in function epilogue. Also, STGloop is expanded
2950       // before that pass.
2951       if (InsertI != MBB->end() &&
2952           canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getBytes() + Size,
2953                             &TotalOffset)) {
2954         UpdateInstr = &*InsertI++;
2955         LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n  "
2956                           << *UpdateInstr);
2957       }
2958     }
2959 
2960     if (!UpdateInstr && TagStores.size() < 2)
2961       return;
2962 
2963     if (UpdateInstr) {
2964       FrameRegUpdate = TotalOffset;
2965       FrameRegUpdateFlags = UpdateInstr->getFlags();
2966     }
2967     emitLoop(InsertI);
2968     if (UpdateInstr)
2969       UpdateInstr->eraseFromParent();
2970   }
2971 
2972   for (auto &TS : TagStores)
2973     TS.MI->eraseFromParent();
2974 }
2975 
2976 bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,
2977                                         int64_t &Size, bool &ZeroData) {
2978   MachineFunction &MF = *MI.getParent()->getParent();
2979   const MachineFrameInfo &MFI = MF.getFrameInfo();
2980 
2981   unsigned Opcode = MI.getOpcode();
2982   ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGOffset ||
2983               Opcode == AArch64::STZ2GOffset);
2984 
2985   if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {
2986     if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())
2987       return false;
2988     if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())
2989       return false;
2990     Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());
2991     Size = MI.getOperand(2).getImm();
2992     return true;
2993   }
2994 
2995   if (Opcode == AArch64::STGOffset || Opcode == AArch64::STZGOffset)
2996     Size = 16;
2997   else if (Opcode == AArch64::ST2GOffset || Opcode == AArch64::STZ2GOffset)
2998     Size = 32;
2999   else
3000     return false;
3001 
3002   if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())
3003     return false;
3004 
3005   Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +
3006            16 * MI.getOperand(2).getImm();
3007   return true;
3008 }
3009 
3010 // Detect a run of memory tagging instructions for adjacent stack frame slots,
3011 // and replace them with a shorter instruction sequence:
3012 // * replace STG + STG with ST2G
3013 // * replace STGloop + STGloop with STGloop
3014 // This code needs to run when stack slot offsets are already known, but before
3015 // FrameIndex operands in STG instructions are eliminated.
3016 MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II,
3017                                                 const AArch64FrameLowering *TFI,
3018                                                 RegScavenger *RS) {
3019   bool FirstZeroData;
3020   int64_t Size, Offset;
3021   MachineInstr &MI = *II;
3022   MachineBasicBlock *MBB = MI.getParent();
3023   MachineBasicBlock::iterator NextI = ++II;
3024   if (&MI == &MBB->instr_back())
3025     return II;
3026   if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))
3027     return II;
3028 
3029   SmallVector<TagStoreInstr, 4> Instrs;
3030   Instrs.emplace_back(&MI, Offset, Size);
3031 
3032   constexpr int kScanLimit = 10;
3033   int Count = 0;
3034   for (MachineBasicBlock::iterator E = MBB->end();
3035        NextI != E && Count < kScanLimit; ++NextI) {
3036     MachineInstr &MI = *NextI;
3037     bool ZeroData;
3038     int64_t Size, Offset;
3039     // Collect instructions that update memory tags with a FrameIndex operand
3040     // and (when applicable) constant size, and whose output registers are dead
3041     // (the latter is almost always the case in practice). Since these
3042     // instructions effectively have no inputs or outputs, we are free to skip
3043     // any non-aliasing instructions in between without tracking used registers.
3044     if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {
3045       if (ZeroData != FirstZeroData)
3046         break;
3047       Instrs.emplace_back(&MI, Offset, Size);
3048       continue;
3049     }
3050 
3051     // Only count non-transient, non-tagging instructions toward the scan
3052     // limit.
3053     if (!MI.isTransient())
3054       ++Count;
3055 
3056     // Just in case, stop before the epilogue code starts.
3057     if (MI.getFlag(MachineInstr::FrameSetup) ||
3058         MI.getFlag(MachineInstr::FrameDestroy))
3059       break;
3060 
3061     // Reject anything that may alias the collected instructions.
3062     if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects())
3063       break;
3064   }
3065 
3066   // New code will be inserted after the last tagging instruction we've found.
3067   MachineBasicBlock::iterator InsertI = Instrs.back().MI;
3068   InsertI++;
3069 
3070   llvm::stable_sort(Instrs,
3071                     [](const TagStoreInstr &Left, const TagStoreInstr &Right) {
3072                       return Left.Offset < Right.Offset;
3073                     });
3074 
3075   // Make sure that we don't have any overlapping stores.
3076   int64_t CurOffset = Instrs[0].Offset;
3077   for (auto &Instr : Instrs) {
3078     if (CurOffset > Instr.Offset)
3079       return NextI;
3080     CurOffset = Instr.Offset + Instr.Size;
3081   }
3082 
3083   // Find contiguous runs of tagged memory and emit shorter instruction
3084   // sequencies for them when possible.
3085   TagStoreEdit TSE(MBB, FirstZeroData);
3086   Optional<int64_t> EndOffset;
3087   for (auto &Instr : Instrs) {
3088     if (EndOffset && *EndOffset != Instr.Offset) {
3089       // Found a gap.
3090       TSE.emitCode(InsertI, TFI, /*IsLast = */ false);
3091       TSE.clear();
3092     }
3093 
3094     TSE.addInstruction(Instr);
3095     EndOffset = Instr.Offset + Instr.Size;
3096   }
3097 
3098   TSE.emitCode(InsertI, TFI, /*IsLast = */ true);
3099 
3100   return InsertI;
3101 }
3102 } // namespace
3103 
3104 void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(
3105     MachineFunction &MF, RegScavenger *RS = nullptr) const {
3106   if (StackTaggingMergeSetTag)
3107     for (auto &BB : MF)
3108       for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();)
3109         II = tryMergeAdjacentSTG(II, this, RS);
3110 }
3111 
3112 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
3113 /// before the update.  This is easily retrieved as it is exactly the offset
3114 /// that is set in processFunctionBeforeFrameFinalized.
3115 int AArch64FrameLowering::getFrameIndexReferencePreferSP(
3116     const MachineFunction &MF, int FI, Register &FrameReg,
3117     bool IgnoreSPUpdates) const {
3118   const MachineFrameInfo &MFI = MF.getFrameInfo();
3119   if (IgnoreSPUpdates) {
3120     LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
3121                       << MFI.getObjectOffset(FI) << "\n");
3122     FrameReg = AArch64::SP;
3123     return MFI.getObjectOffset(FI);
3124   }
3125 
3126   return getFrameIndexReference(MF, FI, FrameReg);
3127 }
3128 
3129 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
3130 /// the parent's frame pointer
3131 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
3132     const MachineFunction &MF) const {
3133   return 0;
3134 }
3135 
3136 /// Funclets only need to account for space for the callee saved registers,
3137 /// as the locals are accounted for in the parent's stack frame.
3138 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
3139     const MachineFunction &MF) const {
3140   // This is the size of the pushed CSRs.
3141   unsigned CSSize =
3142       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
3143   // This is the amount of stack a funclet needs to allocate.
3144   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
3145                  getStackAlign());
3146 }
3147