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