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 // | prev_lr                           |    | (frame record first)
51 // | prev_fp                           | <--'
52 // | async context if needed           |
53 // | (a.k.a. "frame record")           |
54 // |-----------------------------------| <- fp(=x29)
55 // |                                   |
56 // | callee-saved fp/simd/SVE regs     |
57 // |                                   |
58 // |-----------------------------------|
59 // |                                   |
60 // |        SVE stack objects          |
61 // |                                   |
62 // |-----------------------------------|
63 // |.empty.space.to.make.part.below....|
64 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
65 // |.the.standard.16-byte.alignment....|  compile time; if present)
66 // |-----------------------------------|
67 // |                                   |
68 // | local variables of fixed size     |
69 // | including spill slots             |
70 // |-----------------------------------| <- bp(not defined by ABI,
71 // |.variable-sized.local.variables....|       LLVM chooses X19)
72 // |.(VLAs)............................| (size of this area is unknown at
73 // |...................................|  compile time)
74 // |-----------------------------------| <- sp
75 // |                                   | Lower address
76 //
77 //
78 // To access the data in a frame, at-compile time, a constant offset must be
79 // computable from one of the pointers (fp, bp, sp) to access it. The size
80 // of the areas with a dotted background cannot be computed at compile-time
81 // if they are present, making it required to have all three of fp, bp and
82 // sp to be set up to be able to access all contents in the frame areas,
83 // assuming all of the frame areas are non-empty.
84 //
85 // For most functions, some of the frame areas are empty. For those functions,
86 // it may not be necessary to set up fp or bp:
87 // * A base pointer is definitely needed when there are both VLAs and local
88 //   variables with more-than-default alignment requirements.
89 // * A frame pointer is definitely needed when there are local variables with
90 //   more-than-default alignment requirements.
91 //
92 // For Darwin platforms the frame-record (fp, lr) is stored at the top of the
93 // callee-saved area, since the unwind encoding does not allow for encoding
94 // this dynamically and existing tools depend on this layout. For other
95 // platforms, the frame-record is stored at the bottom of the (gpr) callee-saved
96 // area to allow SVE stack objects (allocated directly below the callee-saves,
97 // if available) to be accessed directly from the framepointer.
98 // The SVE spill/fill instructions have VL-scaled addressing modes such
99 // as:
100 //    ldr z8, [fp, #-7 mul vl]
101 // For SVE the size of the vector length (VL) is not known at compile-time, so
102 // '#-7 mul vl' is an offset that can only be evaluated at runtime. With this
103 // layout, we don't need to add an unscaled offset to the framepointer before
104 // accessing the SVE object in the frame.
105 //
106 // In some cases when a base pointer is not strictly needed, it is generated
107 // anyway when offsets from the frame pointer to access local variables become
108 // so large that the offset can't be encoded in the immediate fields of loads
109 // or stores.
110 //
111 // Outgoing function arguments must be at the bottom of the stack frame when
112 // calling another function. If we do not have variable-sized stack objects, we
113 // can allocate a "reserved call frame" area at the bottom of the local
114 // variable area, large enough for all outgoing calls. If we do have VLAs, then
115 // the stack pointer must be decremented and incremented around each call to
116 // make space for the arguments below the VLAs.
117 //
118 // FIXME: also explain the redzone concept.
119 //
120 // An example of the prologue:
121 //
122 //     .globl __foo
123 //     .align 2
124 //  __foo:
125 // Ltmp0:
126 //     .cfi_startproc
127 //     .cfi_personality 155, ___gxx_personality_v0
128 // Leh_func_begin:
129 //     .cfi_lsda 16, Lexception33
130 //
131 //     stp  xa,bx, [sp, -#offset]!
132 //     ...
133 //     stp  x28, x27, [sp, #offset-32]
134 //     stp  fp, lr, [sp, #offset-16]
135 //     add  fp, sp, #offset - 16
136 //     sub  sp, sp, #1360
137 //
138 // The Stack:
139 //       +-------------------------------------------+
140 // 10000 | ........ | ........ | ........ | ........ |
141 // 10004 | ........ | ........ | ........ | ........ |
142 //       +-------------------------------------------+
143 // 10008 | ........ | ........ | ........ | ........ |
144 // 1000c | ........ | ........ | ........ | ........ |
145 //       +===========================================+
146 // 10010 |                X28 Register               |
147 // 10014 |                X28 Register               |
148 //       +-------------------------------------------+
149 // 10018 |                X27 Register               |
150 // 1001c |                X27 Register               |
151 //       +===========================================+
152 // 10020 |                Frame Pointer              |
153 // 10024 |                Frame Pointer              |
154 //       +-------------------------------------------+
155 // 10028 |                Link Register              |
156 // 1002c |                Link Register              |
157 //       +===========================================+
158 // 10030 | ........ | ........ | ........ | ........ |
159 // 10034 | ........ | ........ | ........ | ........ |
160 //       +-------------------------------------------+
161 // 10038 | ........ | ........ | ........ | ........ |
162 // 1003c | ........ | ........ | ........ | ........ |
163 //       +-------------------------------------------+
164 //
165 //     [sp] = 10030        ::    >>initial value<<
166 //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
167 //     fp = sp == 10020    ::  mov fp, sp
168 //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
169 //     sp == 10010         ::    >>final value<<
170 //
171 // The frame pointer (w29) points to address 10020. If we use an offset of
172 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
173 // for w27, and -32 for w28:
174 //
175 //  Ltmp1:
176 //     .cfi_def_cfa w29, 16
177 //  Ltmp2:
178 //     .cfi_offset w30, -8
179 //  Ltmp3:
180 //     .cfi_offset w29, -16
181 //  Ltmp4:
182 //     .cfi_offset w27, -24
183 //  Ltmp5:
184 //     .cfi_offset w28, -32
185 //
186 //===----------------------------------------------------------------------===//
187 
188 #include "AArch64FrameLowering.h"
189 #include "AArch64InstrInfo.h"
190 #include "AArch64MachineFunctionInfo.h"
191 #include "AArch64RegisterInfo.h"
192 #include "AArch64Subtarget.h"
193 #include "AArch64TargetMachine.h"
194 #include "MCTargetDesc/AArch64AddressingModes.h"
195 #include "llvm/ADT/ScopeExit.h"
196 #include "llvm/ADT/SmallVector.h"
197 #include "llvm/ADT/Statistic.h"
198 #include "llvm/CodeGen/LivePhysRegs.h"
199 #include "llvm/CodeGen/MachineBasicBlock.h"
200 #include "llvm/CodeGen/MachineFrameInfo.h"
201 #include "llvm/CodeGen/MachineFunction.h"
202 #include "llvm/CodeGen/MachineInstr.h"
203 #include "llvm/CodeGen/MachineInstrBuilder.h"
204 #include "llvm/CodeGen/MachineMemOperand.h"
205 #include "llvm/CodeGen/MachineModuleInfo.h"
206 #include "llvm/CodeGen/MachineOperand.h"
207 #include "llvm/CodeGen/MachineRegisterInfo.h"
208 #include "llvm/CodeGen/RegisterScavenging.h"
209 #include "llvm/CodeGen/TargetInstrInfo.h"
210 #include "llvm/CodeGen/TargetRegisterInfo.h"
211 #include "llvm/CodeGen/TargetSubtargetInfo.h"
212 #include "llvm/CodeGen/WinEHFuncInfo.h"
213 #include "llvm/IR/Attributes.h"
214 #include "llvm/IR/CallingConv.h"
215 #include "llvm/IR/DataLayout.h"
216 #include "llvm/IR/DebugLoc.h"
217 #include "llvm/IR/Function.h"
218 #include "llvm/MC/MCAsmInfo.h"
219 #include "llvm/MC/MCDwarf.h"
220 #include "llvm/Support/CommandLine.h"
221 #include "llvm/Support/Debug.h"
222 #include "llvm/Support/ErrorHandling.h"
223 #include "llvm/Support/MathExtras.h"
224 #include "llvm/Support/raw_ostream.h"
225 #include "llvm/Target/TargetMachine.h"
226 #include "llvm/Target/TargetOptions.h"
227 #include <cassert>
228 #include <cstdint>
229 #include <iterator>
230 #include <vector>
231 
232 using namespace llvm;
233 
234 #define DEBUG_TYPE "frame-info"
235 
236 static cl::opt<bool> EnableRedZone("aarch64-redzone",
237                                    cl::desc("enable use of redzone on AArch64"),
238                                    cl::init(false), cl::Hidden);
239 
240 static cl::opt<bool>
241     ReverseCSRRestoreSeq("reverse-csr-restore-seq",
242                          cl::desc("reverse the CSR restore sequence"),
243                          cl::init(false), cl::Hidden);
244 
245 static cl::opt<bool> StackTaggingMergeSetTag(
246     "stack-tagging-merge-settag",
247     cl::desc("merge settag instruction in function epilog"), cl::init(true),
248     cl::Hidden);
249 
250 static cl::opt<bool> OrderFrameObjects("aarch64-order-frame-objects",
251                                        cl::desc("sort stack allocations"),
252                                        cl::init(true), cl::Hidden);
253 
254 cl::opt<bool> EnableHomogeneousPrologEpilog(
255     "homogeneous-prolog-epilog", cl::Hidden,
256     cl::desc("Emit homogeneous prologue and epilogue for the size "
257              "optimization (default = off)"));
258 
259 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
260 
261 /// Returns how much of the incoming argument stack area (in bytes) we should
262 /// clean up in an epilogue. For the C calling convention this will be 0, for
263 /// guaranteed tail call conventions it can be positive (a normal return or a
264 /// tail call to a function that uses less stack space for arguments) or
265 /// negative (for a tail call to a function that needs more stack space than us
266 /// for arguments).
267 static int64_t getArgumentStackToRestore(MachineFunction &MF,
268                                          MachineBasicBlock &MBB) {
269   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
270   bool IsTailCallReturn = false;
271   if (MBB.end() != MBBI) {
272     unsigned RetOpcode = MBBI->getOpcode();
273     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
274                        RetOpcode == AArch64::TCRETURNri ||
275                        RetOpcode == AArch64::TCRETURNriBTI;
276   }
277   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
278 
279   int64_t ArgumentPopSize = 0;
280   if (IsTailCallReturn) {
281     MachineOperand &StackAdjust = MBBI->getOperand(1);
282 
283     // For a tail-call in a callee-pops-arguments environment, some or all of
284     // the stack may actually be in use for the call's arguments, this is
285     // calculated during LowerCall and consumed here...
286     ArgumentPopSize = StackAdjust.getImm();
287   } else {
288     // ... otherwise the amount to pop is *all* of the argument space,
289     // conveniently stored in the MachineFunctionInfo by
290     // LowerFormalArguments. This will, of course, be zero for the C calling
291     // convention.
292     ArgumentPopSize = AFI->getArgumentStackToRestore();
293   }
294 
295   return ArgumentPopSize;
296 }
297 
298 static bool produceCompactUnwindFrame(MachineFunction &MF);
299 static bool needsWinCFI(const MachineFunction &MF);
300 static StackOffset getSVEStackSize(const MachineFunction &MF);
301 static bool needsShadowCallStackPrologueEpilogue(MachineFunction &MF);
302 
303 /// Returns true if a homogeneous prolog or epilog code can be emitted
304 /// for the size optimization. If possible, a frame helper call is injected.
305 /// When Exit block is given, this check is for epilog.
306 bool AArch64FrameLowering::homogeneousPrologEpilog(
307     MachineFunction &MF, MachineBasicBlock *Exit) const {
308   if (!MF.getFunction().hasMinSize())
309     return false;
310   if (!EnableHomogeneousPrologEpilog)
311     return false;
312   if (ReverseCSRRestoreSeq)
313     return false;
314   if (EnableRedZone)
315     return false;
316 
317   // TODO: Window is supported yet.
318   if (needsWinCFI(MF))
319     return false;
320   // TODO: SVE is not supported yet.
321   if (getSVEStackSize(MF))
322     return false;
323 
324   // Bail on stack adjustment needed on return for simplicity.
325   const MachineFrameInfo &MFI = MF.getFrameInfo();
326   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
327   if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF))
328     return false;
329   if (Exit && getArgumentStackToRestore(MF, *Exit))
330     return false;
331 
332   return true;
333 }
334 
335 /// Returns true if CSRs should be paired.
336 bool AArch64FrameLowering::producePairRegisters(MachineFunction &MF) const {
337   return produceCompactUnwindFrame(MF) || homogeneousPrologEpilog(MF);
338 }
339 
340 /// This is the biggest offset to the stack pointer we can encode in aarch64
341 /// instructions (without using a separate calculation and a temp register).
342 /// Note that the exception here are vector stores/loads which cannot encode any
343 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
344 static const unsigned DefaultSafeSPDisplacement = 255;
345 
346 /// Look at each instruction that references stack frames and return the stack
347 /// size limit beyond which some of these instructions will require a scratch
348 /// register during their expansion later.
349 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
350   // FIXME: For now, just conservatively guestimate based on unscaled indexing
351   // range. We'll end up allocating an unnecessary spill slot a lot, but
352   // realistically that's not a big deal at this stage of the game.
353   for (MachineBasicBlock &MBB : MF) {
354     for (MachineInstr &MI : MBB) {
355       if (MI.isDebugInstr() || MI.isPseudo() ||
356           MI.getOpcode() == AArch64::ADDXri ||
357           MI.getOpcode() == AArch64::ADDSXri)
358         continue;
359 
360       for (const MachineOperand &MO : MI.operands()) {
361         if (!MO.isFI())
362           continue;
363 
364         StackOffset Offset;
365         if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
366             AArch64FrameOffsetCannotUpdate)
367           return 0;
368       }
369     }
370   }
371   return DefaultSafeSPDisplacement;
372 }
373 
374 TargetStackID::Value
375 AArch64FrameLowering::getStackIDForScalableVectors() const {
376   return TargetStackID::ScalableVector;
377 }
378 
379 /// Returns the size of the fixed object area (allocated next to sp on entry)
380 /// On Win64 this may include a var args area and an UnwindHelp object for EH.
381 static unsigned getFixedObjectSize(const MachineFunction &MF,
382                                    const AArch64FunctionInfo *AFI, bool IsWin64,
383                                    bool IsFunclet) {
384   if (!IsWin64 || IsFunclet) {
385     return AFI->getTailCallReservedStack();
386   } else {
387     if (AFI->getTailCallReservedStack() != 0)
388       report_fatal_error("cannot generate ABI-changing tail call for Win64");
389     // Var args are stored here in the primary function.
390     const unsigned VarArgsArea = AFI->getVarArgsGPRSize();
391     // To support EH funclets we allocate an UnwindHelp object
392     const unsigned UnwindHelpObject = (MF.hasEHFunclets() ? 8 : 0);
393     return alignTo(VarArgsArea + UnwindHelpObject, 16);
394   }
395 }
396 
397 /// Returns the size of the entire SVE stackframe (calleesaves + spills).
398 static StackOffset getSVEStackSize(const MachineFunction &MF) {
399   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
400   return StackOffset::getScalable((int64_t)AFI->getStackSizeSVE());
401 }
402 
403 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
404   if (!EnableRedZone)
405     return false;
406 
407   // Don't use the red zone if the function explicitly asks us not to.
408   // This is typically used for kernel code.
409   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
410   const unsigned RedZoneSize =
411       Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
412   if (!RedZoneSize)
413     return false;
414 
415   const MachineFrameInfo &MFI = MF.getFrameInfo();
416   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
417   uint64_t NumBytes = AFI->getLocalStackSize();
418 
419   return !(MFI.hasCalls() || hasFP(MF) || NumBytes > RedZoneSize ||
420            getSVEStackSize(MF));
421 }
422 
423 /// hasFP - Return true if the specified function should have a dedicated frame
424 /// pointer register.
425 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
426   const MachineFrameInfo &MFI = MF.getFrameInfo();
427   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
428   // Win64 EH requires a frame pointer if funclets are present, as the locals
429   // are accessed off the frame pointer in both the parent function and the
430   // funclets.
431   if (MF.hasEHFunclets())
432     return true;
433   // Retain behavior of always omitting the FP for leaf functions when possible.
434   if (MF.getTarget().Options.DisableFramePointerElim(MF))
435     return true;
436   if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
437       MFI.hasStackMap() || MFI.hasPatchPoint() ||
438       RegInfo->hasStackRealignment(MF))
439     return true;
440   // With large callframes around we may need to use FP to access the scavenging
441   // emergency spillslot.
442   //
443   // Unfortunately some calls to hasFP() like machine verifier ->
444   // getReservedReg() -> hasFP in the middle of global isel are too early
445   // to know the max call frame size. Hopefully conservatively returning "true"
446   // in those cases is fine.
447   // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
448   if (!MFI.isMaxCallFrameSizeComputed() ||
449       MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
450     return true;
451 
452   return false;
453 }
454 
455 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
456 /// not required, we reserve argument space for call sites in the function
457 /// immediately on entry to the current function.  This eliminates the need for
458 /// add/sub sp brackets around call sites.  Returns true if the call frame is
459 /// included as part of the stack frame.
460 bool
461 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
462   return !MF.getFrameInfo().hasVarSizedObjects();
463 }
464 
465 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
466     MachineFunction &MF, MachineBasicBlock &MBB,
467     MachineBasicBlock::iterator I) const {
468   const AArch64InstrInfo *TII =
469       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
470   DebugLoc DL = I->getDebugLoc();
471   unsigned Opc = I->getOpcode();
472   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
473   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
474 
475   if (!hasReservedCallFrame(MF)) {
476     int64_t Amount = I->getOperand(0).getImm();
477     Amount = alignTo(Amount, getStackAlign());
478     if (!IsDestroy)
479       Amount = -Amount;
480 
481     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
482     // doesn't have to pop anything), then the first operand will be zero too so
483     // this adjustment is a no-op.
484     if (CalleePopAmount == 0) {
485       // FIXME: in-function stack adjustment for calls is limited to 24-bits
486       // because there's no guaranteed temporary register available.
487       //
488       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
489       // 1) For offset <= 12-bit, we use LSL #0
490       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
491       // LSL #0, and the other uses LSL #12.
492       //
493       // Most call frames will be allocated at the start of a function so
494       // this is OK, but it is a limitation that needs dealing with.
495       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
496       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
497                       StackOffset::getFixed(Amount), TII);
498     }
499   } else if (CalleePopAmount != 0) {
500     // If the calling convention demands that the callee pops arguments from the
501     // stack, we want to add it back if we have a reserved call frame.
502     assert(CalleePopAmount < 0xffffff && "call frame too large");
503     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
504                     StackOffset::getFixed(-(int64_t)CalleePopAmount), TII);
505   }
506   return MBB.erase(I);
507 }
508 
509 void AArch64FrameLowering::emitCalleeSavedGPRLocations(
510     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
511   MachineFunction &MF = *MBB.getParent();
512   MachineFrameInfo &MFI = MF.getFrameInfo();
513 
514   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
515   if (CSI.empty())
516     return;
517 
518   const TargetSubtargetInfo &STI = MF.getSubtarget();
519   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
520   const TargetInstrInfo &TII = *STI.getInstrInfo();
521   DebugLoc DL = MBB.findDebugLoc(MBBI);
522 
523   for (const auto &Info : CSI) {
524     if (MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector)
525       continue;
526 
527     assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");
528     unsigned DwarfReg = TRI.getDwarfRegNum(Info.getReg(), true);
529 
530     int64_t Offset =
531         MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
532     unsigned CFIIndex = MF.addFrameInst(
533         MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
534     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
535         .addCFIIndex(CFIIndex)
536         .setMIFlags(MachineInstr::FrameSetup);
537   }
538 }
539 
540 void AArch64FrameLowering::emitCalleeSavedSVELocations(
541     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
542   MachineFunction &MF = *MBB.getParent();
543   MachineFrameInfo &MFI = MF.getFrameInfo();
544 
545   // Add callee saved registers to move list.
546   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
547   if (CSI.empty())
548     return;
549 
550   const TargetSubtargetInfo &STI = MF.getSubtarget();
551   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
552   const TargetInstrInfo &TII = *STI.getInstrInfo();
553   DebugLoc DL = MBB.findDebugLoc(MBBI);
554   AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
555 
556   for (const auto &Info : CSI) {
557     if (!(MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))
558       continue;
559 
560     // Not all unwinders may know about SVE registers, so assume the lowest
561     // common demoninator.
562     assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");
563     unsigned Reg = Info.getReg();
564     if (!static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))
565       continue;
566 
567     StackOffset Offset =
568         StackOffset::getScalable(MFI.getObjectOffset(Info.getFrameIdx())) -
569         StackOffset::getFixed(AFI.getCalleeSavedStackSize(MFI));
570 
571     unsigned CFIIndex = MF.addFrameInst(createCFAOffset(TRI, Reg, Offset));
572     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
573         .addCFIIndex(CFIIndex)
574         .setMIFlags(MachineInstr::FrameSetup);
575   }
576 }
577 
578 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
579     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
580   emitCalleeSavedGPRLocations(MBB, MBBI);
581   emitCalleeSavedSVELocations(MBB, MBBI);
582 }
583 
584 static void insertCFISameValue(const MCInstrDesc &Desc, MachineFunction &MF,
585                                MachineBasicBlock &MBB,
586                                MachineBasicBlock::iterator InsertPt,
587                                unsigned DwarfReg) {
588   unsigned CFIIndex =
589       MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, DwarfReg));
590   BuildMI(MBB, InsertPt, DebugLoc(), Desc).addCFIIndex(CFIIndex);
591 }
592 
593 void AArch64FrameLowering::resetCFIToInitialState(
594     MachineBasicBlock &MBB) const {
595 
596   MachineFunction &MF = *MBB.getParent();
597   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
598   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
599   const auto &TRI =
600       static_cast<const AArch64RegisterInfo &>(*Subtarget.getRegisterInfo());
601   const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();
602 
603   const MCInstrDesc &CFIDesc = TII.get(TargetOpcode::CFI_INSTRUCTION);
604   DebugLoc DL;
605 
606   // Reset the CFA to `SP + 0`.
607   MachineBasicBlock::iterator InsertPt = MBB.begin();
608   unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
609       nullptr, TRI.getDwarfRegNum(AArch64::SP, true), 0));
610   BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);
611 
612   // Flip the RA sign state.
613   if (MFI.shouldSignReturnAddress()) {
614     CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
615     BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);
616   }
617 
618   // Shadow call stack uses X18, reset it.
619   if (needsShadowCallStackPrologueEpilogue(MF))
620     insertCFISameValue(CFIDesc, MF, MBB, InsertPt,
621                        TRI.getDwarfRegNum(AArch64::X18, true));
622 
623   // Emit .cfi_same_value for callee-saved registers.
624   const std::vector<CalleeSavedInfo> &CSI =
625       MF.getFrameInfo().getCalleeSavedInfo();
626   for (const auto &Info : CSI) {
627     unsigned Reg = Info.getReg();
628     if (!TRI.regNeedsCFI(Reg, Reg))
629       continue;
630     insertCFISameValue(CFIDesc, MF, MBB, InsertPt,
631                        TRI.getDwarfRegNum(Reg, true));
632   }
633 }
634 
635 static void emitCalleeSavedRestores(MachineBasicBlock &MBB,
636                                     MachineBasicBlock::iterator MBBI,
637                                     bool SVE) {
638   MachineFunction &MF = *MBB.getParent();
639   MachineFrameInfo &MFI = MF.getFrameInfo();
640 
641   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
642   if (CSI.empty())
643     return;
644 
645   const TargetSubtargetInfo &STI = MF.getSubtarget();
646   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
647   const TargetInstrInfo &TII = *STI.getInstrInfo();
648   DebugLoc DL = MBB.findDebugLoc(MBBI);
649 
650   for (const auto &Info : CSI) {
651     if (SVE !=
652         (MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))
653       continue;
654 
655     unsigned Reg = Info.getReg();
656     if (SVE &&
657         !static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))
658       continue;
659 
660     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(
661         nullptr, TRI.getDwarfRegNum(Info.getReg(), true)));
662     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
663         .addCFIIndex(CFIIndex)
664         .setMIFlags(MachineInstr::FrameDestroy);
665   }
666 }
667 
668 void AArch64FrameLowering::emitCalleeSavedGPRRestores(
669     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
670   emitCalleeSavedRestores(MBB, MBBI, false);
671 }
672 
673 void AArch64FrameLowering::emitCalleeSavedSVERestores(
674     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
675   emitCalleeSavedRestores(MBB, MBBI, true);
676 }
677 
678 static MCRegister getRegisterOrZero(MCRegister Reg, bool HasSVE) {
679   switch (Reg.id()) {
680   default:
681     // The called routine is expected to preserve r19-r28
682     // r29 and r30 are used as frame pointer and link register resp.
683     return 0;
684 
685     // GPRs
686 #define CASE(n)                                                                \
687   case AArch64::W##n:                                                          \
688   case AArch64::X##n:                                                          \
689     return AArch64::X##n
690   CASE(0);
691   CASE(1);
692   CASE(2);
693   CASE(3);
694   CASE(4);
695   CASE(5);
696   CASE(6);
697   CASE(7);
698   CASE(8);
699   CASE(9);
700   CASE(10);
701   CASE(11);
702   CASE(12);
703   CASE(13);
704   CASE(14);
705   CASE(15);
706   CASE(16);
707   CASE(17);
708   CASE(18);
709 #undef CASE
710 
711     // FPRs
712 #define CASE(n)                                                                \
713   case AArch64::B##n:                                                          \
714   case AArch64::H##n:                                                          \
715   case AArch64::S##n:                                                          \
716   case AArch64::D##n:                                                          \
717   case AArch64::Q##n:                                                          \
718     return HasSVE ? AArch64::Z##n : AArch64::Q##n
719   CASE(0);
720   CASE(1);
721   CASE(2);
722   CASE(3);
723   CASE(4);
724   CASE(5);
725   CASE(6);
726   CASE(7);
727   CASE(8);
728   CASE(9);
729   CASE(10);
730   CASE(11);
731   CASE(12);
732   CASE(13);
733   CASE(14);
734   CASE(15);
735   CASE(16);
736   CASE(17);
737   CASE(18);
738   CASE(19);
739   CASE(20);
740   CASE(21);
741   CASE(22);
742   CASE(23);
743   CASE(24);
744   CASE(25);
745   CASE(26);
746   CASE(27);
747   CASE(28);
748   CASE(29);
749   CASE(30);
750   CASE(31);
751 #undef CASE
752   }
753 }
754 
755 void AArch64FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
756                                                 MachineBasicBlock &MBB) const {
757   // Insertion point.
758   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
759 
760   // Fake a debug loc.
761   DebugLoc DL;
762   if (MBBI != MBB.end())
763     DL = MBBI->getDebugLoc();
764 
765   const MachineFunction &MF = *MBB.getParent();
766   const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
767   const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
768 
769   BitVector GPRsToZero(TRI.getNumRegs());
770   BitVector FPRsToZero(TRI.getNumRegs());
771   bool HasSVE = STI.hasSVE();
772   for (MCRegister Reg : RegsToZero.set_bits()) {
773     if (TRI.isGeneralPurposeRegister(MF, Reg)) {
774       // For GPRs, we only care to clear out the 64-bit register.
775       if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
776         GPRsToZero.set(XReg);
777     } else if (AArch64::FPR128RegClass.contains(Reg) ||
778                AArch64::FPR64RegClass.contains(Reg) ||
779                AArch64::FPR32RegClass.contains(Reg) ||
780                AArch64::FPR16RegClass.contains(Reg) ||
781                AArch64::FPR8RegClass.contains(Reg)) {
782       // For FPRs,
783       if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
784         FPRsToZero.set(XReg);
785     }
786   }
787 
788   const AArch64InstrInfo &TII = *STI.getInstrInfo();
789 
790   // Zero out GPRs.
791   for (MCRegister Reg : GPRsToZero.set_bits())
792     BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), Reg).addImm(0);
793 
794   // Zero out FP/vector registers.
795   for (MCRegister Reg : FPRsToZero.set_bits())
796     if (HasSVE)
797       BuildMI(MBB, MBBI, DL, TII.get(AArch64::DUP_ZI_D), Reg)
798         .addImm(0)
799         .addImm(0);
800     else
801       BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVIv2d_ns), Reg).addImm(0);
802 
803   if (HasSVE) {
804     for (MCRegister PReg :
805          {AArch64::P0, AArch64::P1, AArch64::P2, AArch64::P3, AArch64::P4,
806           AArch64::P5, AArch64::P6, AArch64::P7, AArch64::P8, AArch64::P9,
807           AArch64::P10, AArch64::P11, AArch64::P12, AArch64::P13, AArch64::P14,
808           AArch64::P15}) {
809       if (RegsToZero[PReg])
810         BuildMI(MBB, MBBI, DL, TII.get(AArch64::PFALSE), PReg);
811     }
812   }
813 }
814 
815 // Find a scratch register that we can use at the start of the prologue to
816 // re-align the stack pointer.  We avoid using callee-save registers since they
817 // may appear to be free when this is called from canUseAsPrologue (during
818 // shrink wrapping), but then no longer be free when this is called from
819 // emitPrologue.
820 //
821 // FIXME: This is a bit conservative, since in the above case we could use one
822 // of the callee-save registers as a scratch temp to re-align the stack pointer,
823 // but we would then have to make sure that we were in fact saving at least one
824 // callee-save register in the prologue, which is additional complexity that
825 // doesn't seem worth the benefit.
826 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
827   MachineFunction *MF = MBB->getParent();
828 
829   // If MBB is an entry block, use X9 as the scratch register
830   if (&MF->front() == MBB)
831     return AArch64::X9;
832 
833   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
834   const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
835   LivePhysRegs LiveRegs(TRI);
836   LiveRegs.addLiveIns(*MBB);
837 
838   // Mark callee saved registers as used so we will not choose them.
839   const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
840   for (unsigned i = 0; CSRegs[i]; ++i)
841     LiveRegs.addReg(CSRegs[i]);
842 
843   // Prefer X9 since it was historically used for the prologue scratch reg.
844   const MachineRegisterInfo &MRI = MF->getRegInfo();
845   if (LiveRegs.available(MRI, AArch64::X9))
846     return AArch64::X9;
847 
848   for (unsigned Reg : AArch64::GPR64RegClass) {
849     if (LiveRegs.available(MRI, Reg))
850       return Reg;
851   }
852   return AArch64::NoRegister;
853 }
854 
855 bool AArch64FrameLowering::canUseAsPrologue(
856     const MachineBasicBlock &MBB) const {
857   const MachineFunction *MF = MBB.getParent();
858   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
859   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
860   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
861 
862   // Don't need a scratch register if we're not going to re-align the stack.
863   if (!RegInfo->hasStackRealignment(*MF))
864     return true;
865   // Otherwise, we can use any block as long as it has a scratch register
866   // available.
867   return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
868 }
869 
870 static bool windowsRequiresStackProbe(MachineFunction &MF,
871                                       uint64_t StackSizeInBytes) {
872   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
873   if (!Subtarget.isTargetWindows())
874     return false;
875   const Function &F = MF.getFunction();
876   // TODO: When implementing stack protectors, take that into account
877   // for the probe threshold.
878   unsigned StackProbeSize = 4096;
879   if (F.hasFnAttribute("stack-probe-size"))
880     F.getFnAttribute("stack-probe-size")
881         .getValueAsString()
882         .getAsInteger(0, StackProbeSize);
883   return (StackSizeInBytes >= StackProbeSize) &&
884          !F.hasFnAttribute("no-stack-arg-probe");
885 }
886 
887 static bool needsWinCFI(const MachineFunction &MF) {
888   const Function &F = MF.getFunction();
889   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
890          F.needsUnwindTableEntry();
891 }
892 
893 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
894     MachineFunction &MF, uint64_t StackBumpBytes) const {
895   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
896   const MachineFrameInfo &MFI = MF.getFrameInfo();
897   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
898   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
899   if (homogeneousPrologEpilog(MF))
900     return false;
901 
902   if (AFI->getLocalStackSize() == 0)
903     return false;
904 
905   // For WinCFI, if optimizing for size, prefer to not combine the stack bump
906   // (to force a stp with predecrement) to match the packed unwind format,
907   // provided that there actually are any callee saved registers to merge the
908   // decrement with.
909   // This is potentially marginally slower, but allows using the packed
910   // unwind format for functions that both have a local area and callee saved
911   // registers. Using the packed unwind format notably reduces the size of
912   // the unwind info.
913   if (needsWinCFI(MF) && AFI->getCalleeSavedStackSize() > 0 &&
914       MF.getFunction().hasOptSize())
915     return false;
916 
917   // 512 is the maximum immediate for stp/ldp that will be used for
918   // callee-save save/restores
919   if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
920     return false;
921 
922   if (MFI.hasVarSizedObjects())
923     return false;
924 
925   if (RegInfo->hasStackRealignment(MF))
926     return false;
927 
928   // This isn't strictly necessary, but it simplifies things a bit since the
929   // current RedZone handling code assumes the SP is adjusted by the
930   // callee-save save/restore code.
931   if (canUseRedZone(MF))
932     return false;
933 
934   // When there is an SVE area on the stack, always allocate the
935   // callee-saves and spills/locals separately.
936   if (getSVEStackSize(MF))
937     return false;
938 
939   return true;
940 }
941 
942 bool AArch64FrameLowering::shouldCombineCSRLocalStackBumpInEpilogue(
943     MachineBasicBlock &MBB, unsigned StackBumpBytes) const {
944   if (!shouldCombineCSRLocalStackBump(*MBB.getParent(), StackBumpBytes))
945     return false;
946 
947   if (MBB.empty())
948     return true;
949 
950   // Disable combined SP bump if the last instruction is an MTE tag store. It
951   // is almost always better to merge SP adjustment into those instructions.
952   MachineBasicBlock::iterator LastI = MBB.getFirstTerminator();
953   MachineBasicBlock::iterator Begin = MBB.begin();
954   while (LastI != Begin) {
955     --LastI;
956     if (LastI->isTransient())
957       continue;
958     if (!LastI->getFlag(MachineInstr::FrameDestroy))
959       break;
960   }
961   switch (LastI->getOpcode()) {
962   case AArch64::STGloop:
963   case AArch64::STZGloop:
964   case AArch64::STGOffset:
965   case AArch64::STZGOffset:
966   case AArch64::ST2GOffset:
967   case AArch64::STZ2GOffset:
968     return false;
969   default:
970     return true;
971   }
972   llvm_unreachable("unreachable");
973 }
974 
975 // Given a load or a store instruction, generate an appropriate unwinding SEH
976 // code on Windows.
977 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,
978                                              const TargetInstrInfo &TII,
979                                              MachineInstr::MIFlag Flag) {
980   unsigned Opc = MBBI->getOpcode();
981   MachineBasicBlock *MBB = MBBI->getParent();
982   MachineFunction &MF = *MBB->getParent();
983   DebugLoc DL = MBBI->getDebugLoc();
984   unsigned ImmIdx = MBBI->getNumOperands() - 1;
985   int Imm = MBBI->getOperand(ImmIdx).getImm();
986   MachineInstrBuilder MIB;
987   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
988   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
989 
990   switch (Opc) {
991   default:
992     llvm_unreachable("No SEH Opcode for this instruction");
993   case AArch64::LDPDpost:
994     Imm = -Imm;
995     LLVM_FALLTHROUGH;
996   case AArch64::STPDpre: {
997     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
998     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
999     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
1000               .addImm(Reg0)
1001               .addImm(Reg1)
1002               .addImm(Imm * 8)
1003               .setMIFlag(Flag);
1004     break;
1005   }
1006   case AArch64::LDPXpost:
1007     Imm = -Imm;
1008     LLVM_FALLTHROUGH;
1009   case AArch64::STPXpre: {
1010     Register Reg0 = MBBI->getOperand(1).getReg();
1011     Register Reg1 = MBBI->getOperand(2).getReg();
1012     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
1013       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
1014                 .addImm(Imm * 8)
1015                 .setMIFlag(Flag);
1016     else
1017       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
1018                 .addImm(RegInfo->getSEHRegNum(Reg0))
1019                 .addImm(RegInfo->getSEHRegNum(Reg1))
1020                 .addImm(Imm * 8)
1021                 .setMIFlag(Flag);
1022     break;
1023   }
1024   case AArch64::LDRDpost:
1025     Imm = -Imm;
1026     LLVM_FALLTHROUGH;
1027   case AArch64::STRDpre: {
1028     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1029     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
1030               .addImm(Reg)
1031               .addImm(Imm)
1032               .setMIFlag(Flag);
1033     break;
1034   }
1035   case AArch64::LDRXpost:
1036     Imm = -Imm;
1037     LLVM_FALLTHROUGH;
1038   case AArch64::STRXpre: {
1039     unsigned Reg =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1040     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
1041               .addImm(Reg)
1042               .addImm(Imm)
1043               .setMIFlag(Flag);
1044     break;
1045   }
1046   case AArch64::STPDi:
1047   case AArch64::LDPDi: {
1048     unsigned Reg0 =  RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1049     unsigned Reg1 =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1050     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
1051               .addImm(Reg0)
1052               .addImm(Reg1)
1053               .addImm(Imm * 8)
1054               .setMIFlag(Flag);
1055     break;
1056   }
1057   case AArch64::STPXi:
1058   case AArch64::LDPXi: {
1059     Register Reg0 = MBBI->getOperand(0).getReg();
1060     Register Reg1 = MBBI->getOperand(1).getReg();
1061     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
1062       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
1063                 .addImm(Imm * 8)
1064                 .setMIFlag(Flag);
1065     else
1066       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
1067                 .addImm(RegInfo->getSEHRegNum(Reg0))
1068                 .addImm(RegInfo->getSEHRegNum(Reg1))
1069                 .addImm(Imm * 8)
1070                 .setMIFlag(Flag);
1071     break;
1072   }
1073   case AArch64::STRXui:
1074   case AArch64::LDRXui: {
1075     int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1076     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
1077               .addImm(Reg)
1078               .addImm(Imm * 8)
1079               .setMIFlag(Flag);
1080     break;
1081   }
1082   case AArch64::STRDui:
1083   case AArch64::LDRDui: {
1084     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1085     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
1086               .addImm(Reg)
1087               .addImm(Imm * 8)
1088               .setMIFlag(Flag);
1089     break;
1090   }
1091   }
1092   auto I = MBB->insertAfter(MBBI, MIB);
1093   return I;
1094 }
1095 
1096 // Fix up the SEH opcode associated with the save/restore instruction.
1097 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,
1098                            unsigned LocalStackSize) {
1099   MachineOperand *ImmOpnd = nullptr;
1100   unsigned ImmIdx = MBBI->getNumOperands() - 1;
1101   switch (MBBI->getOpcode()) {
1102   default:
1103     llvm_unreachable("Fix the offset in the SEH instruction");
1104   case AArch64::SEH_SaveFPLR:
1105   case AArch64::SEH_SaveRegP:
1106   case AArch64::SEH_SaveReg:
1107   case AArch64::SEH_SaveFRegP:
1108   case AArch64::SEH_SaveFReg:
1109     ImmOpnd = &MBBI->getOperand(ImmIdx);
1110     break;
1111   }
1112   if (ImmOpnd)
1113     ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);
1114 }
1115 
1116 // Convert callee-save register save/restore instruction to do stack pointer
1117 // decrement/increment to allocate/deallocate the callee-save stack area by
1118 // converting store/load to use pre/post increment version.
1119 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
1120     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
1121     const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,
1122     bool NeedsWinCFI, bool *HasWinCFI, bool EmitCFI,
1123     MachineInstr::MIFlag FrameFlag = MachineInstr::FrameSetup,
1124     int CFAOffset = 0) {
1125   unsigned NewOpc;
1126   switch (MBBI->getOpcode()) {
1127   default:
1128     llvm_unreachable("Unexpected callee-save save/restore opcode!");
1129   case AArch64::STPXi:
1130     NewOpc = AArch64::STPXpre;
1131     break;
1132   case AArch64::STPDi:
1133     NewOpc = AArch64::STPDpre;
1134     break;
1135   case AArch64::STPQi:
1136     NewOpc = AArch64::STPQpre;
1137     break;
1138   case AArch64::STRXui:
1139     NewOpc = AArch64::STRXpre;
1140     break;
1141   case AArch64::STRDui:
1142     NewOpc = AArch64::STRDpre;
1143     break;
1144   case AArch64::STRQui:
1145     NewOpc = AArch64::STRQpre;
1146     break;
1147   case AArch64::LDPXi:
1148     NewOpc = AArch64::LDPXpost;
1149     break;
1150   case AArch64::LDPDi:
1151     NewOpc = AArch64::LDPDpost;
1152     break;
1153   case AArch64::LDPQi:
1154     NewOpc = AArch64::LDPQpost;
1155     break;
1156   case AArch64::LDRXui:
1157     NewOpc = AArch64::LDRXpost;
1158     break;
1159   case AArch64::LDRDui:
1160     NewOpc = AArch64::LDRDpost;
1161     break;
1162   case AArch64::LDRQui:
1163     NewOpc = AArch64::LDRQpost;
1164     break;
1165   }
1166   // Get rid of the SEH code associated with the old instruction.
1167   if (NeedsWinCFI) {
1168     auto SEH = std::next(MBBI);
1169     if (AArch64InstrInfo::isSEHInstruction(*SEH))
1170       SEH->eraseFromParent();
1171   }
1172 
1173   TypeSize Scale = TypeSize::Fixed(1);
1174   unsigned Width;
1175   int64_t MinOffset, MaxOffset;
1176   bool Success = static_cast<const AArch64InstrInfo *>(TII)->getMemOpInfo(
1177       NewOpc, Scale, Width, MinOffset, MaxOffset);
1178   (void)Success;
1179   assert(Success && "unknown load/store opcode");
1180 
1181   // If the first store isn't right where we want SP then we can't fold the
1182   // update in so create a normal arithmetic instruction instead.
1183   MachineFunction &MF = *MBB.getParent();
1184   if (MBBI->getOperand(MBBI->getNumOperands() - 1).getImm() != 0 ||
1185       CSStackSizeInc < MinOffset || CSStackSizeInc > MaxOffset) {
1186     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1187                     StackOffset::getFixed(CSStackSizeInc), TII, FrameFlag,
1188                     false, false, nullptr, EmitCFI,
1189                     StackOffset::getFixed(CFAOffset));
1190 
1191     return std::prev(MBBI);
1192   }
1193 
1194   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1195   MIB.addReg(AArch64::SP, RegState::Define);
1196 
1197   // Copy all operands other than the immediate offset.
1198   unsigned OpndIdx = 0;
1199   for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
1200        ++OpndIdx)
1201     MIB.add(MBBI->getOperand(OpndIdx));
1202 
1203   assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
1204          "Unexpected immediate offset in first/last callee-save save/restore "
1205          "instruction!");
1206   assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
1207          "Unexpected base register in callee-save save/restore instruction!");
1208   assert(CSStackSizeInc % Scale == 0);
1209   MIB.addImm(CSStackSizeInc / (int)Scale);
1210 
1211   MIB.setMIFlags(MBBI->getFlags());
1212   MIB.setMemRefs(MBBI->memoperands());
1213 
1214   // Generate a new SEH code that corresponds to the new instruction.
1215   if (NeedsWinCFI) {
1216     *HasWinCFI = true;
1217     InsertSEH(*MIB, *TII, FrameFlag);
1218   }
1219 
1220   if (EmitCFI) {
1221     unsigned CFIIndex = MF.addFrameInst(
1222         MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset - CSStackSizeInc));
1223     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1224         .addCFIIndex(CFIIndex)
1225         .setMIFlags(FrameFlag);
1226   }
1227 
1228   return std::prev(MBB.erase(MBBI));
1229 }
1230 
1231 // Fixup callee-save register save/restore instructions to take into account
1232 // combined SP bump by adding the local stack size to the stack offsets.
1233 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
1234                                               uint64_t LocalStackSize,
1235                                               bool NeedsWinCFI,
1236                                               bool *HasWinCFI) {
1237   if (AArch64InstrInfo::isSEHInstruction(MI))
1238     return;
1239 
1240   unsigned Opc = MI.getOpcode();
1241   unsigned Scale;
1242   switch (Opc) {
1243   case AArch64::STPXi:
1244   case AArch64::STRXui:
1245   case AArch64::STPDi:
1246   case AArch64::STRDui:
1247   case AArch64::LDPXi:
1248   case AArch64::LDRXui:
1249   case AArch64::LDPDi:
1250   case AArch64::LDRDui:
1251     Scale = 8;
1252     break;
1253   case AArch64::STPQi:
1254   case AArch64::STRQui:
1255   case AArch64::LDPQi:
1256   case AArch64::LDRQui:
1257     Scale = 16;
1258     break;
1259   default:
1260     llvm_unreachable("Unexpected callee-save save/restore opcode!");
1261   }
1262 
1263   unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
1264   assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
1265          "Unexpected base register in callee-save save/restore instruction!");
1266   // Last operand is immediate offset that needs fixing.
1267   MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
1268   // All generated opcodes have scaled offsets.
1269   assert(LocalStackSize % Scale == 0);
1270   OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
1271 
1272   if (NeedsWinCFI) {
1273     *HasWinCFI = true;
1274     auto MBBI = std::next(MachineBasicBlock::iterator(MI));
1275     assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");
1276     assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&
1277            "Expecting a SEH instruction");
1278     fixupSEHOpcode(MBBI, LocalStackSize);
1279   }
1280 }
1281 
1282 static bool isTargetWindows(const MachineFunction &MF) {
1283   return MF.getSubtarget<AArch64Subtarget>().isTargetWindows();
1284 }
1285 
1286 // Convenience function to determine whether I is an SVE callee save.
1287 static bool IsSVECalleeSave(MachineBasicBlock::iterator I) {
1288   switch (I->getOpcode()) {
1289   default:
1290     return false;
1291   case AArch64::STR_ZXI:
1292   case AArch64::STR_PXI:
1293   case AArch64::LDR_ZXI:
1294   case AArch64::LDR_PXI:
1295     return I->getFlag(MachineInstr::FrameSetup) ||
1296            I->getFlag(MachineInstr::FrameDestroy);
1297   }
1298 }
1299 
1300 static bool needsShadowCallStackPrologueEpilogue(MachineFunction &MF) {
1301   if (!(llvm::any_of(
1302             MF.getFrameInfo().getCalleeSavedInfo(),
1303             [](const auto &Info) { return Info.getReg() == AArch64::LR; }) &&
1304         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)))
1305     return false;
1306 
1307   if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
1308     report_fatal_error("Must reserve x18 to use shadow call stack");
1309 
1310   return true;
1311 }
1312 
1313 static void emitShadowCallStackPrologue(const TargetInstrInfo &TII,
1314                                         MachineFunction &MF,
1315                                         MachineBasicBlock &MBB,
1316                                         MachineBasicBlock::iterator MBBI,
1317                                         const DebugLoc &DL, bool NeedsWinCFI,
1318                                         bool NeedsUnwindInfo) {
1319   // Shadow call stack prolog: str x30, [x18], #8
1320   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXpost))
1321       .addReg(AArch64::X18, RegState::Define)
1322       .addReg(AArch64::LR)
1323       .addReg(AArch64::X18)
1324       .addImm(8)
1325       .setMIFlag(MachineInstr::FrameSetup);
1326 
1327   // This instruction also makes x18 live-in to the entry block.
1328   MBB.addLiveIn(AArch64::X18);
1329 
1330   if (NeedsWinCFI)
1331     BuildMI(MBB, MBBI, DL, TII.get(AArch64::SEH_Nop))
1332         .setMIFlag(MachineInstr::FrameSetup);
1333 
1334   if (NeedsUnwindInfo) {
1335     // Emit a CFI instruction that causes 8 to be subtracted from the value of
1336     // x18 when unwinding past this frame.
1337     static const char CFIInst[] = {
1338         dwarf::DW_CFA_val_expression,
1339         18, // register
1340         2,  // length
1341         static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
1342         static_cast<char>(-8) & 0x7f, // addend (sleb128)
1343     };
1344     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
1345         nullptr, StringRef(CFIInst, sizeof(CFIInst))));
1346     BuildMI(MBB, MBBI, DL, TII.get(AArch64::CFI_INSTRUCTION))
1347         .addCFIIndex(CFIIndex)
1348         .setMIFlag(MachineInstr::FrameSetup);
1349   }
1350 }
1351 
1352 static void emitShadowCallStackEpilogue(const TargetInstrInfo &TII,
1353                                         MachineFunction &MF,
1354                                         MachineBasicBlock &MBB,
1355                                         MachineBasicBlock::iterator MBBI,
1356                                         const DebugLoc &DL) {
1357   // Shadow call stack epilog: ldr x30, [x18, #-8]!
1358   BuildMI(MBB, MBBI, DL, TII.get(AArch64::LDRXpre))
1359       .addReg(AArch64::X18, RegState::Define)
1360       .addReg(AArch64::LR, RegState::Define)
1361       .addReg(AArch64::X18)
1362       .addImm(-8)
1363       .setMIFlag(MachineInstr::FrameDestroy);
1364 
1365   if (MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo()) {
1366     unsigned CFIIndex =
1367         MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, 18));
1368     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1369         .addCFIIndex(CFIIndex)
1370         .setMIFlags(MachineInstr::FrameDestroy);
1371   }
1372 }
1373 
1374 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
1375                                         MachineBasicBlock &MBB) const {
1376   MachineBasicBlock::iterator MBBI = MBB.begin();
1377   const MachineFrameInfo &MFI = MF.getFrameInfo();
1378   const Function &F = MF.getFunction();
1379   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1380   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1381   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1382   MachineModuleInfo &MMI = MF.getMMI();
1383   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1384   bool EmitCFI = AFI->needsDwarfUnwindInfo();
1385   bool HasFP = hasFP(MF);
1386   bool NeedsWinCFI = needsWinCFI(MF);
1387   bool HasWinCFI = false;
1388   auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); });
1389 
1390   bool IsFunclet = MBB.isEHFuncletEntry();
1391 
1392   // At this point, we're going to decide whether or not the function uses a
1393   // redzone. In most cases, the function doesn't have a redzone so let's
1394   // assume that's false and set it to true in the case that there's a redzone.
1395   AFI->setHasRedZone(false);
1396 
1397   // Debug location must be unknown since the first debug location is used
1398   // to determine the end of the prologue.
1399   DebugLoc DL;
1400 
1401   const auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();
1402   if (needsShadowCallStackPrologueEpilogue(MF))
1403     emitShadowCallStackPrologue(*TII, MF, MBB, MBBI, DL, NeedsWinCFI,
1404                                 MFnI.needsDwarfUnwindInfo());
1405 
1406   if (MFnI.shouldSignReturnAddress()) {
1407     unsigned PACI;
1408     if (MFnI.shouldSignWithBKey()) {
1409       BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
1410           .setMIFlag(MachineInstr::FrameSetup);
1411       PACI = Subtarget.hasPAuth() ? AArch64::PACIB : AArch64::PACIBSP;
1412     } else {
1413       PACI = Subtarget.hasPAuth() ? AArch64::PACIA : AArch64::PACIASP;
1414     }
1415 
1416     auto MI = BuildMI(MBB, MBBI, DL, TII->get(PACI));
1417     if (Subtarget.hasPAuth())
1418       MI.addReg(AArch64::LR, RegState::Define)
1419           .addReg(AArch64::LR)
1420           .addReg(AArch64::SP, RegState::InternalRead);
1421     MI.setMIFlag(MachineInstr::FrameSetup);
1422     if (EmitCFI) {
1423       unsigned CFIIndex =
1424           MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
1425       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1426           .addCFIIndex(CFIIndex)
1427           .setMIFlags(MachineInstr::FrameSetup);
1428     }
1429   }
1430 
1431   // We signal the presence of a Swift extended frame to external tools by
1432   // storing FP with 0b0001 in bits 63:60. In normal userland operation a simple
1433   // ORR is sufficient, it is assumed a Swift kernel would initialize the TBI
1434   // bits so that is still true.
1435   if (HasFP && AFI->hasSwiftAsyncContext()) {
1436     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
1437     case SwiftAsyncFramePointerMode::DeploymentBased:
1438       if (Subtarget.swiftAsyncContextIsDynamicallySet()) {
1439         // The special symbol below is absolute and has a *value* that can be
1440         // combined with the frame pointer to signal an extended frame.
1441         BuildMI(MBB, MBBI, DL, TII->get(AArch64::LOADgot), AArch64::X16)
1442             .addExternalSymbol("swift_async_extendedFramePointerFlags",
1443                                AArch64II::MO_GOT);
1444         BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::FP)
1445             .addUse(AArch64::FP)
1446             .addUse(AArch64::X16)
1447             .addImm(Subtarget.isTargetILP32() ? 32 : 0);
1448         break;
1449       }
1450       LLVM_FALLTHROUGH;
1451 
1452     case SwiftAsyncFramePointerMode::Always:
1453       // ORR x29, x29, #0x1000_0000_0000_0000
1454       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXri), AArch64::FP)
1455           .addUse(AArch64::FP)
1456           .addImm(0x1100)
1457           .setMIFlag(MachineInstr::FrameSetup);
1458       break;
1459 
1460     case SwiftAsyncFramePointerMode::Never:
1461       break;
1462     }
1463   }
1464 
1465   // All calls are tail calls in GHC calling conv, and functions have no
1466   // prologue/epilogue.
1467   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1468     return;
1469 
1470   // Set tagged base pointer to the requested stack slot.
1471   // Ideally it should match SP value after prologue.
1472   Optional<int> TBPI = AFI->getTaggedBasePointerIndex();
1473   if (TBPI)
1474     AFI->setTaggedBasePointerOffset(-MFI.getObjectOffset(*TBPI));
1475   else
1476     AFI->setTaggedBasePointerOffset(MFI.getStackSize());
1477 
1478   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1479 
1480   // getStackSize() includes all the locals in its size calculation. We don't
1481   // include these locals when computing the stack size of a funclet, as they
1482   // are allocated in the parent's stack frame and accessed via the frame
1483   // pointer from the funclet.  We only save the callee saved registers in the
1484   // funclet, which are really the callee saved registers of the parent
1485   // function, including the funclet.
1486   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
1487                                : MFI.getStackSize();
1488   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
1489     assert(!HasFP && "unexpected function without stack frame but with FP");
1490     assert(!SVEStackSize &&
1491            "unexpected function without stack frame but with SVE objects");
1492     // All of the stack allocation is for locals.
1493     AFI->setLocalStackSize(NumBytes);
1494     if (!NumBytes)
1495       return;
1496     // REDZONE: If the stack size is less than 128 bytes, we don't need
1497     // to actually allocate.
1498     if (canUseRedZone(MF)) {
1499       AFI->setHasRedZone(true);
1500       ++NumRedZoneFunctions;
1501     } else {
1502       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1503                       StackOffset::getFixed(-NumBytes), TII,
1504                       MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
1505       if (EmitCFI) {
1506         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
1507         MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
1508           // Encode the stack size of the leaf function.
1509         unsigned CFIIndex = MF.addFrameInst(
1510             MCCFIInstruction::cfiDefCfaOffset(FrameLabel, NumBytes));
1511         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1512             .addCFIIndex(CFIIndex)
1513             .setMIFlags(MachineInstr::FrameSetup);
1514       }
1515     }
1516 
1517     if (NeedsWinCFI) {
1518       HasWinCFI = true;
1519       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1520           .setMIFlag(MachineInstr::FrameSetup);
1521     }
1522 
1523     return;
1524   }
1525 
1526   bool IsWin64 =
1527       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1528   unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
1529 
1530   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1531   // All of the remaining stack allocations are for locals.
1532   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1533   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1534   bool HomPrologEpilog = homogeneousPrologEpilog(MF);
1535   if (CombineSPBump) {
1536     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
1537     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1538                     StackOffset::getFixed(-NumBytes), TII,
1539                     MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI,
1540                     EmitCFI);
1541     NumBytes = 0;
1542   } else if (HomPrologEpilog) {
1543     // Stack has been already adjusted.
1544     NumBytes -= PrologueSaveSize;
1545   } else if (PrologueSaveSize != 0) {
1546     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
1547         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI,
1548         EmitCFI);
1549     NumBytes -= PrologueSaveSize;
1550   }
1551   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1552 
1553   // Move past the saves of the callee-saved registers, fixing up the offsets
1554   // and pre-inc if we decided to combine the callee-save and local stack
1555   // pointer bump above.
1556   MachineBasicBlock::iterator End = MBB.end();
1557   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) &&
1558          !IsSVECalleeSave(MBBI)) {
1559     if (CombineSPBump)
1560       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
1561                                         NeedsWinCFI, &HasWinCFI);
1562     ++MBBI;
1563   }
1564 
1565   // For funclets the FP belongs to the containing function.
1566   if (!IsFunclet && HasFP) {
1567     // Only set up FP if we actually need to.
1568     int64_t FPOffset = AFI->getCalleeSaveBaseToFrameRecordOffset();
1569 
1570     if (CombineSPBump)
1571       FPOffset += AFI->getLocalStackSize();
1572 
1573     if (AFI->hasSwiftAsyncContext()) {
1574       // Before we update the live FP we have to ensure there's a valid (or
1575       // null) asynchronous context in its slot just before FP in the frame
1576       // record, so store it now.
1577       const auto &Attrs = MF.getFunction().getAttributes();
1578       bool HaveInitialContext = Attrs.hasAttrSomewhere(Attribute::SwiftAsync);
1579       if (HaveInitialContext)
1580         MBB.addLiveIn(AArch64::X22);
1581       BuildMI(MBB, MBBI, DL, TII->get(AArch64::StoreSwiftAsyncContext))
1582           .addUse(HaveInitialContext ? AArch64::X22 : AArch64::XZR)
1583           .addUse(AArch64::SP)
1584           .addImm(FPOffset - 8)
1585           .setMIFlags(MachineInstr::FrameSetup);
1586     }
1587 
1588     if (HomPrologEpilog) {
1589       auto Prolog = MBBI;
1590       --Prolog;
1591       assert(Prolog->getOpcode() == AArch64::HOM_Prolog);
1592       Prolog->addOperand(MachineOperand::CreateImm(FPOffset));
1593     } else {
1594       // Issue    sub fp, sp, FPOffset or
1595       //          mov fp,sp          when FPOffset is zero.
1596       // Note: All stores of callee-saved registers are marked as "FrameSetup".
1597       // This code marks the instruction(s) that set the FP also.
1598       emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP,
1599                       StackOffset::getFixed(FPOffset), TII,
1600                       MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
1601     }
1602     if (EmitCFI) {
1603       // Define the current CFA rule to use the provided FP.
1604       const int OffsetToFirstCalleeSaveFromFP =
1605           AFI->getCalleeSaveBaseToFrameRecordOffset() -
1606           AFI->getCalleeSavedStackSize();
1607       Register FramePtr = RegInfo->getFrameRegister(MF);
1608       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
1609       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
1610           nullptr, Reg, FixedObject - OffsetToFirstCalleeSaveFromFP));
1611       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1612           .addCFIIndex(CFIIndex)
1613           .setMIFlags(MachineInstr::FrameSetup);
1614     }
1615   }
1616 
1617   // Now emit the moves for whatever callee saved regs we have (including FP,
1618   // LR if those are saved). Frame instructions for SVE register are emitted
1619   // later, after the instruction which actually save SVE regs.
1620   if (EmitCFI)
1621     emitCalleeSavedGPRLocations(MBB, MBBI);
1622 
1623   if (windowsRequiresStackProbe(MF, NumBytes)) {
1624     uint64_t NumWords = NumBytes >> 4;
1625     if (NeedsWinCFI) {
1626       HasWinCFI = true;
1627       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
1628       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
1629       // This is at most two instructions, MOVZ follwed by MOVK.
1630       // TODO: Fix to use multiple stack alloc unwind codes for stacks
1631       // exceeding 256MB in size.
1632       if (NumBytes >= (1 << 28))
1633         report_fatal_error("Stack size cannot exceed 256MB for stack "
1634                             "unwinding purposes");
1635 
1636       uint32_t LowNumWords = NumWords & 0xFFFF;
1637       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
1638             .addImm(LowNumWords)
1639             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1640             .setMIFlag(MachineInstr::FrameSetup);
1641       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1642             .setMIFlag(MachineInstr::FrameSetup);
1643       if ((NumWords & 0xFFFF0000) != 0) {
1644           BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
1645               .addReg(AArch64::X15)
1646               .addImm((NumWords & 0xFFFF0000) >> 16) // High half
1647               .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
1648               .setMIFlag(MachineInstr::FrameSetup);
1649           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1650             .setMIFlag(MachineInstr::FrameSetup);
1651       }
1652     } else {
1653       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
1654           .addImm(NumWords)
1655           .setMIFlags(MachineInstr::FrameSetup);
1656     }
1657 
1658     switch (MF.getTarget().getCodeModel()) {
1659     case CodeModel::Tiny:
1660     case CodeModel::Small:
1661     case CodeModel::Medium:
1662     case CodeModel::Kernel:
1663       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
1664           .addExternalSymbol("__chkstk")
1665           .addReg(AArch64::X15, RegState::Implicit)
1666           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1667           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1668           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1669           .setMIFlags(MachineInstr::FrameSetup);
1670       if (NeedsWinCFI) {
1671         HasWinCFI = true;
1672         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1673             .setMIFlag(MachineInstr::FrameSetup);
1674       }
1675       break;
1676     case CodeModel::Large:
1677       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
1678           .addReg(AArch64::X16, RegState::Define)
1679           .addExternalSymbol("__chkstk")
1680           .addExternalSymbol("__chkstk")
1681           .setMIFlags(MachineInstr::FrameSetup);
1682       if (NeedsWinCFI) {
1683         HasWinCFI = true;
1684         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1685             .setMIFlag(MachineInstr::FrameSetup);
1686       }
1687 
1688       BuildMI(MBB, MBBI, DL, TII->get(getBLRCallOpcode(MF)))
1689           .addReg(AArch64::X16, RegState::Kill)
1690           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
1691           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1692           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1693           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1694           .setMIFlags(MachineInstr::FrameSetup);
1695       if (NeedsWinCFI) {
1696         HasWinCFI = true;
1697         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1698             .setMIFlag(MachineInstr::FrameSetup);
1699       }
1700       break;
1701     }
1702 
1703     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
1704         .addReg(AArch64::SP, RegState::Kill)
1705         .addReg(AArch64::X15, RegState::Kill)
1706         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
1707         .setMIFlags(MachineInstr::FrameSetup);
1708     if (NeedsWinCFI) {
1709       HasWinCFI = true;
1710       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1711           .addImm(NumBytes)
1712           .setMIFlag(MachineInstr::FrameSetup);
1713     }
1714     NumBytes = 0;
1715   }
1716 
1717   StackOffset AllocateBefore = SVEStackSize, AllocateAfter = {};
1718   MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;
1719 
1720   // Process the SVE callee-saves to determine what space needs to be
1721   // allocated.
1722   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
1723     // Find callee save instructions in frame.
1724     CalleeSavesBegin = MBBI;
1725     assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");
1726     while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())
1727       ++MBBI;
1728     CalleeSavesEnd = MBBI;
1729 
1730     AllocateBefore = StackOffset::getScalable(CalleeSavedSize);
1731     AllocateAfter = SVEStackSize - AllocateBefore;
1732   }
1733 
1734   // Allocate space for the callee saves (if any).
1735   emitFrameOffset(
1736       MBB, CalleeSavesBegin, DL, AArch64::SP, AArch64::SP, -AllocateBefore, TII,
1737       MachineInstr::FrameSetup, false, false, nullptr,
1738       EmitCFI && !HasFP && AllocateBefore,
1739       StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes));
1740 
1741   if (EmitCFI)
1742     emitCalleeSavedSVELocations(MBB, CalleeSavesEnd);
1743 
1744   // Finally allocate remaining SVE stack space.
1745   emitFrameOffset(MBB, CalleeSavesEnd, DL, AArch64::SP, AArch64::SP,
1746                   -AllocateAfter, TII, MachineInstr::FrameSetup, false, false,
1747                   nullptr, EmitCFI && !HasFP && AllocateAfter,
1748                   AllocateBefore + StackOffset::getFixed(
1749                                        (int64_t)MFI.getStackSize() - NumBytes));
1750 
1751   // Allocate space for the rest of the frame.
1752   if (NumBytes) {
1753     // Alignment is required for the parent frame, not the funclet
1754     const bool NeedsRealignment =
1755         !IsFunclet && RegInfo->hasStackRealignment(MF);
1756     unsigned scratchSPReg = AArch64::SP;
1757 
1758     if (NeedsRealignment) {
1759       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
1760       assert(scratchSPReg != AArch64::NoRegister);
1761     }
1762 
1763     // If we're a leaf function, try using the red zone.
1764     if (!canUseRedZone(MF)) {
1765       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1766       // the correct value here, as NumBytes also includes padding bytes,
1767       // which shouldn't be counted here.
1768       emitFrameOffset(
1769           MBB, MBBI, DL, scratchSPReg, AArch64::SP,
1770           StackOffset::getFixed(-NumBytes), TII, MachineInstr::FrameSetup,
1771           false, NeedsWinCFI, &HasWinCFI, EmitCFI && !HasFP,
1772           SVEStackSize +
1773               StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes));
1774     }
1775     if (NeedsRealignment) {
1776       const unsigned NrBitsToZero = Log2(MFI.getMaxAlign());
1777       assert(NrBitsToZero > 1);
1778       assert(scratchSPReg != AArch64::SP);
1779 
1780       // SUB X9, SP, NumBytes
1781       //   -- X9 is temporary register, so shouldn't contain any live data here,
1782       //   -- free to use. This is already produced by emitFrameOffset above.
1783       // AND SP, X9, 0b11111...0000
1784       // The logical immediates have a non-trivial encoding. The following
1785       // formula computes the encoded immediate with all ones but
1786       // NrBitsToZero zero bits as least significant bits.
1787       uint32_t andMaskEncoded = (1 << 12)                         // = N
1788                                 | ((64 - NrBitsToZero) << 6)      // immr
1789                                 | ((64 - NrBitsToZero - 1) << 0); // imms
1790 
1791       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1792           .addReg(scratchSPReg, RegState::Kill)
1793           .addImm(andMaskEncoded);
1794       AFI->setStackRealigned(true);
1795       if (NeedsWinCFI) {
1796         HasWinCFI = true;
1797         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1798             .addImm(NumBytes & andMaskEncoded)
1799             .setMIFlag(MachineInstr::FrameSetup);
1800       }
1801     }
1802   }
1803 
1804   // If we need a base pointer, set it up here. It's whatever the value of the
1805   // stack pointer is at this point. Any variable size objects will be allocated
1806   // after this, so we can still use the base pointer to reference locals.
1807   //
1808   // FIXME: Clarify FrameSetup flags here.
1809   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1810   // needed.
1811   // For funclets the BP belongs to the containing function.
1812   if (!IsFunclet && RegInfo->hasBasePointer(MF)) {
1813     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
1814                      false);
1815     if (NeedsWinCFI) {
1816       HasWinCFI = true;
1817       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1818           .setMIFlag(MachineInstr::FrameSetup);
1819     }
1820   }
1821 
1822   // The very last FrameSetup instruction indicates the end of prologue. Emit a
1823   // SEH opcode indicating the prologue end.
1824   if (NeedsWinCFI && HasWinCFI) {
1825     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1826         .setMIFlag(MachineInstr::FrameSetup);
1827   }
1828 
1829   // SEH funclets are passed the frame pointer in X1.  If the parent
1830   // function uses the base register, then the base register is used
1831   // directly, and is not retrieved from X1.
1832   if (IsFunclet && F.hasPersonalityFn()) {
1833     EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());
1834     if (isAsynchronousEHPersonality(Per)) {
1835       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)
1836           .addReg(AArch64::X1)
1837           .setMIFlag(MachineInstr::FrameSetup);
1838       MBB.addLiveIn(AArch64::X1);
1839     }
1840   }
1841 }
1842 
1843 static void InsertReturnAddressAuth(MachineFunction &MF,
1844                                     MachineBasicBlock &MBB) {
1845   const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();
1846   if (!MFI.shouldSignReturnAddress())
1847     return;
1848   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1849   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1850 
1851   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1852   DebugLoc DL;
1853   if (MBBI != MBB.end())
1854     DL = MBBI->getDebugLoc();
1855 
1856   // The AUTIASP instruction assembles to a hint instruction before v8.3a so
1857   // this instruction can safely used for any v8a architecture.
1858   // From v8.3a onwards there are optimised authenticate LR and return
1859   // instructions, namely RETA{A,B}, that can be used instead. In this case the
1860   // DW_CFA_AARCH64_negate_ra_state can't be emitted.
1861   if (Subtarget.hasPAuth() && MBBI != MBB.end() &&
1862       MBBI->getOpcode() == AArch64::RET_ReallyLR) {
1863     BuildMI(MBB, MBBI, DL,
1864             TII->get(MFI.shouldSignWithBKey() ? AArch64::RETAB : AArch64::RETAA))
1865         .copyImplicitOps(*MBBI);
1866     MBB.erase(MBBI);
1867   } else {
1868     BuildMI(
1869         MBB, MBBI, DL,
1870         TII->get(MFI.shouldSignWithBKey() ? AArch64::AUTIBSP : AArch64::AUTIASP))
1871         .setMIFlag(MachineInstr::FrameDestroy);
1872 
1873     unsigned CFIIndex =
1874         MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
1875     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1876         .addCFIIndex(CFIIndex)
1877         .setMIFlags(MachineInstr::FrameDestroy);
1878   }
1879 }
1880 
1881 static bool isFuncletReturnInstr(const MachineInstr &MI) {
1882   switch (MI.getOpcode()) {
1883   default:
1884     return false;
1885   case AArch64::CATCHRET:
1886   case AArch64::CLEANUPRET:
1887     return true;
1888   }
1889 }
1890 
1891 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
1892                                         MachineBasicBlock &MBB) const {
1893   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1894   MachineFrameInfo &MFI = MF.getFrameInfo();
1895   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1896   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1897   DebugLoc DL;
1898   bool NeedsWinCFI = needsWinCFI(MF);
1899   bool EmitCFI = MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo();
1900   bool HasWinCFI = false;
1901   bool IsFunclet = false;
1902   auto WinCFI = make_scope_exit([&]() { assert(HasWinCFI == MF.hasWinCFI()); });
1903 
1904   if (MBB.end() != MBBI) {
1905     DL = MBBI->getDebugLoc();
1906     IsFunclet = isFuncletReturnInstr(*MBBI);
1907   }
1908 
1909   auto FinishingTouches = make_scope_exit([&]() {
1910     InsertReturnAddressAuth(MF, MBB);
1911     if (needsShadowCallStackPrologueEpilogue(MF))
1912       emitShadowCallStackEpilogue(*TII, MF, MBB, MBB.getFirstTerminator(), DL);
1913     if (EmitCFI)
1914       emitCalleeSavedGPRRestores(MBB, MBB.getFirstTerminator());
1915   });
1916 
1917   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
1918                                : MFI.getStackSize();
1919   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1920 
1921   // All calls are tail calls in GHC calling conv, and functions have no
1922   // prologue/epilogue.
1923   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1924     return;
1925 
1926   // How much of the stack used by incoming arguments this function is expected
1927   // to restore in this particular epilogue.
1928   int64_t ArgumentStackToRestore = getArgumentStackToRestore(MF, MBB);
1929   bool IsWin64 =
1930       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1931   unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
1932 
1933   int64_t AfterCSRPopSize = ArgumentStackToRestore;
1934   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1935   // We cannot rely on the local stack size set in emitPrologue if the function
1936   // has funclets, as funclets have different local stack size requirements, and
1937   // the current value set in emitPrologue may be that of the containing
1938   // function.
1939   if (MF.hasEHFunclets())
1940     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1941   if (homogeneousPrologEpilog(MF, &MBB)) {
1942     assert(!NeedsWinCFI);
1943     auto LastPopI = MBB.getFirstTerminator();
1944     if (LastPopI != MBB.begin()) {
1945       auto HomogeneousEpilog = std::prev(LastPopI);
1946       if (HomogeneousEpilog->getOpcode() == AArch64::HOM_Epilog)
1947         LastPopI = HomogeneousEpilog;
1948     }
1949 
1950     // Adjust local stack
1951     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1952                     StackOffset::getFixed(AFI->getLocalStackSize()), TII,
1953                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
1954 
1955     // SP has been already adjusted while restoring callee save regs.
1956     // We've bailed-out the case with adjusting SP for arguments.
1957     assert(AfterCSRPopSize == 0);
1958     return;
1959   }
1960   bool CombineSPBump = shouldCombineCSRLocalStackBumpInEpilogue(MBB, NumBytes);
1961   // Assume we can't combine the last pop with the sp restore.
1962 
1963   bool CombineAfterCSRBump = false;
1964   if (!CombineSPBump && PrologueSaveSize != 0) {
1965     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
1966     while (Pop->getOpcode() == TargetOpcode::CFI_INSTRUCTION ||
1967            AArch64InstrInfo::isSEHInstruction(*Pop))
1968       Pop = std::prev(Pop);
1969     // Converting the last ldp to a post-index ldp is valid only if the last
1970     // ldp's offset is 0.
1971     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
1972     // If the offset is 0 and the AfterCSR pop is not actually trying to
1973     // allocate more stack for arguments (in space that an untimely interrupt
1974     // may clobber), convert it to a post-index ldp.
1975     if (OffsetOp.getImm() == 0 && AfterCSRPopSize >= 0) {
1976       convertCalleeSaveRestoreToSPPrePostIncDec(
1977           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, EmitCFI,
1978           MachineInstr::FrameDestroy, PrologueSaveSize);
1979     } else {
1980       // If not, make sure to emit an add after the last ldp.
1981       // We're doing this by transfering the size to be restored from the
1982       // adjustment *before* the CSR pops to the adjustment *after* the CSR
1983       // pops.
1984       AfterCSRPopSize += PrologueSaveSize;
1985       CombineAfterCSRBump = true;
1986     }
1987   }
1988 
1989   // Move past the restores of the callee-saved registers.
1990   // If we plan on combining the sp bump of the local stack size and the callee
1991   // save stack size, we might need to adjust the CSR save and restore offsets.
1992   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
1993   MachineBasicBlock::iterator Begin = MBB.begin();
1994   while (LastPopI != Begin) {
1995     --LastPopI;
1996     if (!LastPopI->getFlag(MachineInstr::FrameDestroy) ||
1997         IsSVECalleeSave(LastPopI)) {
1998       ++LastPopI;
1999       break;
2000     } else if (CombineSPBump)
2001       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
2002                                         NeedsWinCFI, &HasWinCFI);
2003   }
2004 
2005   if (MF.hasWinCFI()) {
2006     // If the prologue didn't contain any SEH opcodes and didn't set the
2007     // MF.hasWinCFI() flag, assume the epilogue won't either, and skip the
2008     // EpilogStart - to avoid generating CFI for functions that don't need it.
2009     // (And as we didn't generate any prologue at all, it would be asymmetrical
2010     // to the epilogue.) By the end of the function, we assert that
2011     // HasWinCFI is equal to MF.hasWinCFI(), to verify this assumption.
2012     HasWinCFI = true;
2013     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
2014         .setMIFlag(MachineInstr::FrameDestroy);
2015   }
2016 
2017   if (hasFP(MF) && AFI->hasSwiftAsyncContext()) {
2018     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
2019     case SwiftAsyncFramePointerMode::DeploymentBased:
2020       // Avoid the reload as it is GOT relative, and instead fall back to the
2021       // hardcoded value below.  This allows a mismatch between the OS and
2022       // application without immediately terminating on the difference.
2023       LLVM_FALLTHROUGH;
2024     case SwiftAsyncFramePointerMode::Always:
2025       // We need to reset FP to its untagged state on return. Bit 60 is
2026       // currently used to show the presence of an extended frame.
2027 
2028       // BIC x29, x29, #0x1000_0000_0000_0000
2029       BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::ANDXri),
2030               AArch64::FP)
2031           .addUse(AArch64::FP)
2032           .addImm(0x10fe)
2033           .setMIFlag(MachineInstr::FrameDestroy);
2034       break;
2035 
2036     case SwiftAsyncFramePointerMode::Never:
2037       break;
2038     }
2039   }
2040 
2041   const StackOffset &SVEStackSize = getSVEStackSize(MF);
2042 
2043   // If there is a single SP update, insert it before the ret and we're done.
2044   if (CombineSPBump) {
2045     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
2046 
2047     // When we are about to restore the CSRs, the CFA register is SP again.
2048     if (EmitCFI && hasFP(MF)) {
2049       const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();
2050       unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
2051       unsigned CFIIndex =
2052           MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, NumBytes));
2053       BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2054           .addCFIIndex(CFIIndex)
2055           .setMIFlags(MachineInstr::FrameDestroy);
2056     }
2057 
2058     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
2059                     StackOffset::getFixed(NumBytes + (int64_t)AfterCSRPopSize),
2060                     TII, MachineInstr::FrameDestroy, false, NeedsWinCFI,
2061                     &HasWinCFI, EmitCFI, StackOffset::getFixed(NumBytes));
2062     if (HasWinCFI)
2063       BuildMI(MBB, MBB.getFirstTerminator(), DL,
2064               TII->get(AArch64::SEH_EpilogEnd))
2065           .setMIFlag(MachineInstr::FrameDestroy);
2066     return;
2067   }
2068 
2069   NumBytes -= PrologueSaveSize;
2070   assert(NumBytes >= 0 && "Negative stack allocation size!?");
2071 
2072   // Process the SVE callee-saves to determine what space needs to be
2073   // deallocated.
2074   StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize;
2075   MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI;
2076   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
2077     RestoreBegin = std::prev(RestoreEnd);
2078     while (RestoreBegin != MBB.begin() &&
2079            IsSVECalleeSave(std::prev(RestoreBegin)))
2080       --RestoreBegin;
2081 
2082     assert(IsSVECalleeSave(RestoreBegin) &&
2083            IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction");
2084 
2085     StackOffset CalleeSavedSizeAsOffset =
2086         StackOffset::getScalable(CalleeSavedSize);
2087     DeallocateBefore = SVEStackSize - CalleeSavedSizeAsOffset;
2088     DeallocateAfter = CalleeSavedSizeAsOffset;
2089   }
2090 
2091   // Deallocate the SVE area.
2092   if (SVEStackSize) {
2093     // If we have stack realignment or variable sized objects on the stack,
2094     // restore the stack pointer from the frame pointer prior to SVE CSR
2095     // restoration.
2096     if (AFI->isStackRealigned() || MFI.hasVarSizedObjects()) {
2097       if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
2098         // Set SP to start of SVE callee-save area from which they can
2099         // be reloaded. The code below will deallocate the stack space
2100         // space by moving FP -> SP.
2101         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP,
2102                         StackOffset::getScalable(-CalleeSavedSize), TII,
2103                         MachineInstr::FrameDestroy);
2104       }
2105     } else {
2106       if (AFI->getSVECalleeSavedStackSize()) {
2107         // Deallocate the non-SVE locals first before we can deallocate (and
2108         // restore callee saves) from the SVE area.
2109         emitFrameOffset(
2110             MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
2111             StackOffset::getFixed(NumBytes), TII, MachineInstr::FrameDestroy,
2112             false, false, nullptr, EmitCFI && !hasFP(MF),
2113             SVEStackSize + StackOffset::getFixed(NumBytes + PrologueSaveSize));
2114         NumBytes = 0;
2115       }
2116 
2117       emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
2118                       DeallocateBefore, TII, MachineInstr::FrameDestroy, false,
2119                       false, nullptr, EmitCFI && !hasFP(MF),
2120                       SVEStackSize +
2121                           StackOffset::getFixed(NumBytes + PrologueSaveSize));
2122 
2123       emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP,
2124                       DeallocateAfter, TII, MachineInstr::FrameDestroy, false,
2125                       false, nullptr, EmitCFI && !hasFP(MF),
2126                       DeallocateAfter +
2127                           StackOffset::getFixed(NumBytes + PrologueSaveSize));
2128     }
2129     if (EmitCFI)
2130       emitCalleeSavedSVERestores(MBB, RestoreEnd);
2131   }
2132 
2133   if (!hasFP(MF)) {
2134     bool RedZone = canUseRedZone(MF);
2135     // If this was a redzone leaf function, we don't need to restore the
2136     // stack pointer (but we may need to pop stack args for fastcc).
2137     if (RedZone && AfterCSRPopSize == 0)
2138       return;
2139 
2140     // Pop the local variables off the stack. If there are no callee-saved
2141     // registers, it means we are actually positioned at the terminator and can
2142     // combine stack increment for the locals and the stack increment for
2143     // callee-popped arguments into (possibly) a single instruction and be done.
2144     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
2145     int64_t StackRestoreBytes = RedZone ? 0 : NumBytes;
2146     if (NoCalleeSaveRestore)
2147       StackRestoreBytes += AfterCSRPopSize;
2148 
2149     emitFrameOffset(
2150         MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
2151         StackOffset::getFixed(StackRestoreBytes), TII,
2152         MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI, EmitCFI,
2153         StackOffset::getFixed((RedZone ? 0 : NumBytes) + PrologueSaveSize));
2154 
2155     // If we were able to combine the local stack pop with the argument pop,
2156     // then we're done.
2157     if (NoCalleeSaveRestore || AfterCSRPopSize == 0) {
2158       if (HasWinCFI) {
2159         BuildMI(MBB, MBB.getFirstTerminator(), DL,
2160                 TII->get(AArch64::SEH_EpilogEnd))
2161             .setMIFlag(MachineInstr::FrameDestroy);
2162       }
2163       return;
2164     }
2165 
2166     NumBytes = 0;
2167   }
2168 
2169   // Restore the original stack pointer.
2170   // FIXME: Rather than doing the math here, we should instead just use
2171   // non-post-indexed loads for the restores if we aren't actually going to
2172   // be able to save any instructions.
2173   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) {
2174     emitFrameOffset(
2175         MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
2176         StackOffset::getFixed(-AFI->getCalleeSaveBaseToFrameRecordOffset()),
2177         TII, MachineInstr::FrameDestroy, false, NeedsWinCFI);
2178   } else if (NumBytes)
2179     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
2180                     StackOffset::getFixed(NumBytes), TII,
2181                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
2182 
2183   // When we are about to restore the CSRs, the CFA register is SP again.
2184   if (EmitCFI && hasFP(MF)) {
2185     const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();
2186     unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
2187     unsigned CFIIndex = MF.addFrameInst(
2188         MCCFIInstruction::cfiDefCfa(nullptr, Reg, PrologueSaveSize));
2189     BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2190         .addCFIIndex(CFIIndex)
2191         .setMIFlags(MachineInstr::FrameDestroy);
2192   }
2193 
2194   // This must be placed after the callee-save restore code because that code
2195   // assumes the SP is at the same location as it was after the callee-save save
2196   // code in the prologue.
2197   if (AfterCSRPopSize) {
2198     assert(AfterCSRPopSize > 0 && "attempting to reallocate arg stack that an "
2199                                   "interrupt may have clobbered");
2200 
2201     emitFrameOffset(
2202         MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
2203         StackOffset::getFixed(AfterCSRPopSize), TII, MachineInstr::FrameDestroy,
2204         false, NeedsWinCFI, &HasWinCFI, EmitCFI,
2205         StackOffset::getFixed(CombineAfterCSRBump ? PrologueSaveSize : 0));
2206   }
2207   if (HasWinCFI)
2208     BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::SEH_EpilogEnd))
2209         .setMIFlag(MachineInstr::FrameDestroy);
2210 }
2211 
2212 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
2213 /// debug info.  It's the same as what we use for resolving the code-gen
2214 /// references for now.  FIXME: This can go wrong when references are
2215 /// SP-relative and simple call frames aren't used.
2216 StackOffset
2217 AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
2218                                              Register &FrameReg) const {
2219   return resolveFrameIndexReference(
2220       MF, FI, FrameReg,
2221       /*PreferFP=*/
2222       MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress),
2223       /*ForSimm=*/false);
2224 }
2225 
2226 StackOffset
2227 AArch64FrameLowering::getNonLocalFrameIndexReference(const MachineFunction &MF,
2228                                                      int FI) const {
2229   return StackOffset::getFixed(getSEHFrameIndexOffset(MF, FI));
2230 }
2231 
2232 static StackOffset getFPOffset(const MachineFunction &MF,
2233                                int64_t ObjectOffset) {
2234   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2235   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2236   bool IsWin64 =
2237       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
2238   unsigned FixedObject =
2239       getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet=*/false);
2240   int64_t CalleeSaveSize = AFI->getCalleeSavedStackSize(MF.getFrameInfo());
2241   int64_t FPAdjust =
2242       CalleeSaveSize - AFI->getCalleeSaveBaseToFrameRecordOffset();
2243   return StackOffset::getFixed(ObjectOffset + FixedObject + FPAdjust);
2244 }
2245 
2246 static StackOffset getStackOffset(const MachineFunction &MF,
2247                                   int64_t ObjectOffset) {
2248   const auto &MFI = MF.getFrameInfo();
2249   return StackOffset::getFixed(ObjectOffset + (int64_t)MFI.getStackSize());
2250 }
2251 
2252   // TODO: This function currently does not work for scalable vectors.
2253 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,
2254                                                  int FI) const {
2255   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
2256       MF.getSubtarget().getRegisterInfo());
2257   int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);
2258   return RegInfo->getLocalAddressRegister(MF) == AArch64::FP
2259              ? getFPOffset(MF, ObjectOffset).getFixed()
2260              : getStackOffset(MF, ObjectOffset).getFixed();
2261 }
2262 
2263 StackOffset AArch64FrameLowering::resolveFrameIndexReference(
2264     const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP,
2265     bool ForSimm) const {
2266   const auto &MFI = MF.getFrameInfo();
2267   int64_t ObjectOffset = MFI.getObjectOffset(FI);
2268   bool isFixed = MFI.isFixedObjectIndex(FI);
2269   bool isSVE = MFI.getStackID(FI) == TargetStackID::ScalableVector;
2270   return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg,
2271                                      PreferFP, ForSimm);
2272 }
2273 
2274 StackOffset AArch64FrameLowering::resolveFrameOffsetReference(
2275     const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, bool isSVE,
2276     Register &FrameReg, bool PreferFP, bool ForSimm) const {
2277   const auto &MFI = MF.getFrameInfo();
2278   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
2279       MF.getSubtarget().getRegisterInfo());
2280   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2281   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2282 
2283   int64_t FPOffset = getFPOffset(MF, ObjectOffset).getFixed();
2284   int64_t Offset = getStackOffset(MF, ObjectOffset).getFixed();
2285   bool isCSR =
2286       !isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
2287 
2288   const StackOffset &SVEStackSize = getSVEStackSize(MF);
2289 
2290   // Use frame pointer to reference fixed objects. Use it for locals if
2291   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
2292   // reliable as a base). Make sure useFPForScavengingIndex() does the
2293   // right thing for the emergency spill slot.
2294   bool UseFP = false;
2295   if (AFI->hasStackFrame() && !isSVE) {
2296     // We shouldn't prefer using the FP to access fixed-sized stack objects when
2297     // there are scalable (SVE) objects in between the FP and the fixed-sized
2298     // objects.
2299     PreferFP &= !SVEStackSize;
2300 
2301     // Note: Keeping the following as multiple 'if' statements rather than
2302     // merging to a single expression for readability.
2303     //
2304     // Argument access should always use the FP.
2305     if (isFixed) {
2306       UseFP = hasFP(MF);
2307     } else if (isCSR && RegInfo->hasStackRealignment(MF)) {
2308       // References to the CSR area must use FP if we're re-aligning the stack
2309       // since the dynamically-sized alignment padding is between the SP/BP and
2310       // the CSR area.
2311       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
2312       UseFP = true;
2313     } else if (hasFP(MF) && !RegInfo->hasStackRealignment(MF)) {
2314       // If the FPOffset is negative and we're producing a signed immediate, we
2315       // have to keep in mind that the available offset range for negative
2316       // offsets is smaller than for positive ones. If an offset is available
2317       // via the FP and the SP, use whichever is closest.
2318       bool FPOffsetFits = !ForSimm || FPOffset >= -256;
2319       PreferFP |= Offset > -FPOffset && !SVEStackSize;
2320 
2321       if (MFI.hasVarSizedObjects()) {
2322         // If we have variable sized objects, we can use either FP or BP, as the
2323         // SP offset is unknown. We can use the base pointer if we have one and
2324         // FP is not preferred. If not, we're stuck with using FP.
2325         bool CanUseBP = RegInfo->hasBasePointer(MF);
2326         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
2327           UseFP = PreferFP;
2328         else if (!CanUseBP) // Can't use BP. Forced to use FP.
2329           UseFP = true;
2330         // else we can use BP and FP, but the offset from FP won't fit.
2331         // That will make us scavenge registers which we can probably avoid by
2332         // using BP. If it won't fit for BP either, we'll scavenge anyway.
2333       } else if (FPOffset >= 0) {
2334         // Use SP or FP, whichever gives us the best chance of the offset
2335         // being in range for direct access. If the FPOffset is positive,
2336         // that'll always be best, as the SP will be even further away.
2337         UseFP = true;
2338       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
2339         // Funclets access the locals contained in the parent's stack frame
2340         // via the frame pointer, so we have to use the FP in the parent
2341         // function.
2342         (void) Subtarget;
2343         assert(
2344             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
2345             "Funclets should only be present on Win64");
2346         UseFP = true;
2347       } else {
2348         // We have the choice between FP and (SP or BP).
2349         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
2350           UseFP = true;
2351       }
2352     }
2353   }
2354 
2355   assert(
2356       ((isFixed || isCSR) || !RegInfo->hasStackRealignment(MF) || !UseFP) &&
2357       "In the presence of dynamic stack pointer realignment, "
2358       "non-argument/CSR objects cannot be accessed through the frame pointer");
2359 
2360   if (isSVE) {
2361     StackOffset FPOffset =
2362         StackOffset::get(-AFI->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset);
2363     StackOffset SPOffset =
2364         SVEStackSize +
2365         StackOffset::get(MFI.getStackSize() - AFI->getCalleeSavedStackSize(),
2366                          ObjectOffset);
2367     // Always use the FP for SVE spills if available and beneficial.
2368     if (hasFP(MF) && (SPOffset.getFixed() ||
2369                       FPOffset.getScalable() < SPOffset.getScalable() ||
2370                       RegInfo->hasStackRealignment(MF))) {
2371       FrameReg = RegInfo->getFrameRegister(MF);
2372       return FPOffset;
2373     }
2374 
2375     FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
2376                                            : (unsigned)AArch64::SP;
2377     return SPOffset;
2378   }
2379 
2380   StackOffset ScalableOffset = {};
2381   if (UseFP && !(isFixed || isCSR))
2382     ScalableOffset = -SVEStackSize;
2383   if (!UseFP && (isFixed || isCSR))
2384     ScalableOffset = SVEStackSize;
2385 
2386   if (UseFP) {
2387     FrameReg = RegInfo->getFrameRegister(MF);
2388     return StackOffset::getFixed(FPOffset) + ScalableOffset;
2389   }
2390 
2391   // Use the base pointer if we have one.
2392   if (RegInfo->hasBasePointer(MF))
2393     FrameReg = RegInfo->getBaseRegister();
2394   else {
2395     assert(!MFI.hasVarSizedObjects() &&
2396            "Can't use SP when we have var sized objects.");
2397     FrameReg = AArch64::SP;
2398     // If we're using the red zone for this function, the SP won't actually
2399     // be adjusted, so the offsets will be negative. They're also all
2400     // within range of the signed 9-bit immediate instructions.
2401     if (canUseRedZone(MF))
2402       Offset -= AFI->getLocalStackSize();
2403   }
2404 
2405   return StackOffset::getFixed(Offset) + ScalableOffset;
2406 }
2407 
2408 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
2409   // Do not set a kill flag on values that are also marked as live-in. This
2410   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
2411   // callee saved registers.
2412   // Omitting the kill flags is conservatively correct even if the live-in
2413   // is not used after all.
2414   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
2415   return getKillRegState(!IsLiveIn);
2416 }
2417 
2418 static bool produceCompactUnwindFrame(MachineFunction &MF) {
2419   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2420   AttributeList Attrs = MF.getFunction().getAttributes();
2421   return Subtarget.isTargetMachO() &&
2422          !(Subtarget.getTargetLowering()->supportSwiftError() &&
2423            Attrs.hasAttrSomewhere(Attribute::SwiftError)) &&
2424          MF.getFunction().getCallingConv() != CallingConv::SwiftTail;
2425 }
2426 
2427 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
2428                                              bool NeedsWinCFI, bool IsFirst) {
2429   // If we are generating register pairs for a Windows function that requires
2430   // EH support, then pair consecutive registers only.  There are no unwind
2431   // opcodes for saves/restores of non-consectuve register pairs.
2432   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x,
2433   // save_lrpair.
2434   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
2435 
2436   if (Reg2 == AArch64::FP)
2437     return true;
2438   if (!NeedsWinCFI)
2439     return false;
2440   if (Reg2 == Reg1 + 1)
2441     return false;
2442   // If pairing a GPR with LR, the pair can be described by the save_lrpair
2443   // opcode. If this is the first register pair, it would end up with a
2444   // predecrement, but there's no save_lrpair_x opcode, so we can only do this
2445   // if LR is paired with something else than the first register.
2446   // The save_lrpair opcode requires the first register to be an odd one.
2447   if (Reg1 >= AArch64::X19 && Reg1 <= AArch64::X27 &&
2448       (Reg1 - AArch64::X19) % 2 == 0 && Reg2 == AArch64::LR && !IsFirst)
2449     return false;
2450   return true;
2451 }
2452 
2453 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
2454 /// WindowsCFI requires that only consecutive registers can be paired.
2455 /// LR and FP need to be allocated together when the frame needs to save
2456 /// the frame-record. This means any other register pairing with LR is invalid.
2457 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
2458                                       bool UsesWinAAPCS, bool NeedsWinCFI,
2459                                       bool NeedsFrameRecord, bool IsFirst) {
2460   if (UsesWinAAPCS)
2461     return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI, IsFirst);
2462 
2463   // If we need to store the frame record, don't pair any register
2464   // with LR other than FP.
2465   if (NeedsFrameRecord)
2466     return Reg2 == AArch64::LR;
2467 
2468   return false;
2469 }
2470 
2471 namespace {
2472 
2473 struct RegPairInfo {
2474   unsigned Reg1 = AArch64::NoRegister;
2475   unsigned Reg2 = AArch64::NoRegister;
2476   int FrameIdx;
2477   int Offset;
2478   enum RegType { GPR, FPR64, FPR128, PPR, ZPR } Type;
2479 
2480   RegPairInfo() = default;
2481 
2482   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
2483 
2484   unsigned getScale() const {
2485     switch (Type) {
2486     case PPR:
2487       return 2;
2488     case GPR:
2489     case FPR64:
2490       return 8;
2491     case ZPR:
2492     case FPR128:
2493       return 16;
2494     }
2495     llvm_unreachable("Unsupported type");
2496   }
2497 
2498   bool isScalable() const { return Type == PPR || Type == ZPR; }
2499 };
2500 
2501 } // end anonymous namespace
2502 
2503 static void computeCalleeSaveRegisterPairs(
2504     MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI,
2505     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
2506     bool NeedsFrameRecord) {
2507 
2508   if (CSI.empty())
2509     return;
2510 
2511   bool IsWindows = isTargetWindows(MF);
2512   bool NeedsWinCFI = needsWinCFI(MF);
2513   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2514   MachineFrameInfo &MFI = MF.getFrameInfo();
2515   CallingConv::ID CC = MF.getFunction().getCallingConv();
2516   unsigned Count = CSI.size();
2517   (void)CC;
2518   // MachO's compact unwind format relies on all registers being stored in
2519   // pairs.
2520   assert((!produceCompactUnwindFrame(MF) ||
2521           CC == CallingConv::PreserveMost || CC == CallingConv::CXX_FAST_TLS ||
2522           (Count & 1) == 0) &&
2523          "Odd number of callee-saved regs to spill!");
2524   int ByteOffset = AFI->getCalleeSavedStackSize();
2525   int StackFillDir = -1;
2526   int RegInc = 1;
2527   unsigned FirstReg = 0;
2528   if (NeedsWinCFI) {
2529     // For WinCFI, fill the stack from the bottom up.
2530     ByteOffset = 0;
2531     StackFillDir = 1;
2532     // As the CSI array is reversed to match PrologEpilogInserter, iterate
2533     // backwards, to pair up registers starting from lower numbered registers.
2534     RegInc = -1;
2535     FirstReg = Count - 1;
2536   }
2537   int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
2538   bool NeedGapToAlignStack = AFI->hasCalleeSaveStackFreeSpace();
2539 
2540   // When iterating backwards, the loop condition relies on unsigned wraparound.
2541   for (unsigned i = FirstReg; i < Count; i += RegInc) {
2542     RegPairInfo RPI;
2543     RPI.Reg1 = CSI[i].getReg();
2544 
2545     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
2546       RPI.Type = RegPairInfo::GPR;
2547     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
2548       RPI.Type = RegPairInfo::FPR64;
2549     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
2550       RPI.Type = RegPairInfo::FPR128;
2551     else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
2552       RPI.Type = RegPairInfo::ZPR;
2553     else if (AArch64::PPRRegClass.contains(RPI.Reg1))
2554       RPI.Type = RegPairInfo::PPR;
2555     else
2556       llvm_unreachable("Unsupported register class.");
2557 
2558     // Add the next reg to the pair if it is in the same register class.
2559     if (unsigned(i + RegInc) < Count) {
2560       Register NextReg = CSI[i + RegInc].getReg();
2561       bool IsFirst = i == FirstReg;
2562       switch (RPI.Type) {
2563       case RegPairInfo::GPR:
2564         if (AArch64::GPR64RegClass.contains(NextReg) &&
2565             !invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows,
2566                                        NeedsWinCFI, NeedsFrameRecord, IsFirst))
2567           RPI.Reg2 = NextReg;
2568         break;
2569       case RegPairInfo::FPR64:
2570         if (AArch64::FPR64RegClass.contains(NextReg) &&
2571             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI,
2572                                               IsFirst))
2573           RPI.Reg2 = NextReg;
2574         break;
2575       case RegPairInfo::FPR128:
2576         if (AArch64::FPR128RegClass.contains(NextReg))
2577           RPI.Reg2 = NextReg;
2578         break;
2579       case RegPairInfo::PPR:
2580       case RegPairInfo::ZPR:
2581         break;
2582       }
2583     }
2584 
2585     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
2586     // list to come in sorted by frame index so that we can issue the store
2587     // pair instructions directly. Assert if we see anything otherwise.
2588     //
2589     // The order of the registers in the list is controlled by
2590     // getCalleeSavedRegs(), so they will always be in-order, as well.
2591     assert((!RPI.isPaired() ||
2592             (CSI[i].getFrameIdx() + RegInc == CSI[i + RegInc].getFrameIdx())) &&
2593            "Out of order callee saved regs!");
2594 
2595     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
2596             RPI.Reg1 == AArch64::LR) &&
2597            "FrameRecord must be allocated together with LR");
2598 
2599     // Windows AAPCS has FP and LR reversed.
2600     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP ||
2601             RPI.Reg2 == AArch64::LR) &&
2602            "FrameRecord must be allocated together with LR");
2603 
2604     // MachO's compact unwind format relies on all registers being stored in
2605     // adjacent register pairs.
2606     assert((!produceCompactUnwindFrame(MF) ||
2607             CC == CallingConv::PreserveMost || CC == CallingConv::CXX_FAST_TLS ||
2608             (RPI.isPaired() &&
2609              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
2610               RPI.Reg1 + 1 == RPI.Reg2))) &&
2611            "Callee-save registers not saved as adjacent register pair!");
2612 
2613     RPI.FrameIdx = CSI[i].getFrameIdx();
2614     if (NeedsWinCFI &&
2615         RPI.isPaired()) // RPI.FrameIdx must be the lower index of the pair
2616       RPI.FrameIdx = CSI[i + RegInc].getFrameIdx();
2617 
2618     int Scale = RPI.getScale();
2619 
2620     int OffsetPre = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2621     assert(OffsetPre % Scale == 0);
2622 
2623     if (RPI.isScalable())
2624       ScalableByteOffset += StackFillDir * Scale;
2625     else
2626       ByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale);
2627 
2628     // Swift's async context is directly before FP, so allocate an extra
2629     // 8 bytes for it.
2630     if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
2631         RPI.Reg2 == AArch64::FP)
2632       ByteOffset += StackFillDir * 8;
2633 
2634     assert(!(RPI.isScalable() && RPI.isPaired()) &&
2635            "Paired spill/fill instructions don't exist for SVE vectors");
2636 
2637     // Round up size of non-pair to pair size if we need to pad the
2638     // callee-save area to ensure 16-byte alignment.
2639     if (NeedGapToAlignStack && !NeedsWinCFI &&
2640         !RPI.isScalable() && RPI.Type != RegPairInfo::FPR128 &&
2641         !RPI.isPaired() && ByteOffset % 16 != 0) {
2642       ByteOffset += 8 * StackFillDir;
2643       assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16));
2644       // A stack frame with a gap looks like this, bottom up:
2645       // d9, d8. x21, gap, x20, x19.
2646       // Set extra alignment on the x21 object to create the gap above it.
2647       MFI.setObjectAlignment(RPI.FrameIdx, Align(16));
2648       NeedGapToAlignStack = false;
2649     }
2650 
2651     int OffsetPost = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2652     assert(OffsetPost % Scale == 0);
2653     // If filling top down (default), we want the offset after incrementing it.
2654     // If fillibg bootom up (WinCFI) we need the original offset.
2655     int Offset = NeedsWinCFI ? OffsetPre : OffsetPost;
2656 
2657     // The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the
2658     // Swift context can directly precede FP.
2659     if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
2660         RPI.Reg2 == AArch64::FP)
2661       Offset += 8;
2662     RPI.Offset = Offset / Scale;
2663 
2664     assert(((!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
2665             (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
2666            "Offset out of bounds for LDP/STP immediate");
2667 
2668     // Save the offset to frame record so that the FP register can point to the
2669     // innermost frame record (spilled FP and LR registers).
2670     if (NeedsFrameRecord && ((!IsWindows && RPI.Reg1 == AArch64::LR &&
2671                               RPI.Reg2 == AArch64::FP) ||
2672                              (IsWindows && RPI.Reg1 == AArch64::FP &&
2673                               RPI.Reg2 == AArch64::LR)))
2674       AFI->setCalleeSaveBaseToFrameRecordOffset(Offset);
2675 
2676     RegPairs.push_back(RPI);
2677     if (RPI.isPaired())
2678       i += RegInc;
2679   }
2680   if (NeedsWinCFI) {
2681     // If we need an alignment gap in the stack, align the topmost stack
2682     // object. A stack frame with a gap looks like this, bottom up:
2683     // x19, d8. d9, gap.
2684     // Set extra alignment on the topmost stack object (the first element in
2685     // CSI, which goes top down), to create the gap above it.
2686     if (AFI->hasCalleeSaveStackFreeSpace())
2687       MFI.setObjectAlignment(CSI[0].getFrameIdx(), Align(16));
2688     // We iterated bottom up over the registers; flip RegPairs back to top
2689     // down order.
2690     std::reverse(RegPairs.begin(), RegPairs.end());
2691   }
2692 }
2693 
2694 bool AArch64FrameLowering::spillCalleeSavedRegisters(
2695     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2696     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2697   MachineFunction &MF = *MBB.getParent();
2698   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2699   bool NeedsWinCFI = needsWinCFI(MF);
2700   DebugLoc DL;
2701   SmallVector<RegPairInfo, 8> RegPairs;
2702 
2703   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
2704 
2705   const MachineRegisterInfo &MRI = MF.getRegInfo();
2706   if (homogeneousPrologEpilog(MF)) {
2707     auto MIB = BuildMI(MBB, MI, DL, TII.get(AArch64::HOM_Prolog))
2708                    .setMIFlag(MachineInstr::FrameSetup);
2709 
2710     for (auto &RPI : RegPairs) {
2711       MIB.addReg(RPI.Reg1);
2712       MIB.addReg(RPI.Reg2);
2713 
2714       // Update register live in.
2715       if (!MRI.isReserved(RPI.Reg1))
2716         MBB.addLiveIn(RPI.Reg1);
2717       if (!MRI.isReserved(RPI.Reg2))
2718         MBB.addLiveIn(RPI.Reg2);
2719     }
2720     return true;
2721   }
2722   for (const RegPairInfo &RPI : llvm::reverse(RegPairs)) {
2723     unsigned Reg1 = RPI.Reg1;
2724     unsigned Reg2 = RPI.Reg2;
2725     unsigned StrOpc;
2726 
2727     // Issue sequence of spills for cs regs.  The first spill may be converted
2728     // to a pre-decrement store later by emitPrologue if the callee-save stack
2729     // area allocation can't be combined with the local stack area allocation.
2730     // For example:
2731     //    stp     x22, x21, [sp, #0]     // addImm(+0)
2732     //    stp     x20, x19, [sp, #16]    // addImm(+2)
2733     //    stp     fp, lr, [sp, #32]      // addImm(+4)
2734     // Rationale: This sequence saves uop updates compared to a sequence of
2735     // pre-increment spills like stp xi,xj,[sp,#-16]!
2736     // Note: Similar rationale and sequence for restores in epilog.
2737     unsigned Size;
2738     Align Alignment;
2739     switch (RPI.Type) {
2740     case RegPairInfo::GPR:
2741        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
2742        Size = 8;
2743        Alignment = Align(8);
2744        break;
2745     case RegPairInfo::FPR64:
2746        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
2747        Size = 8;
2748        Alignment = Align(8);
2749        break;
2750     case RegPairInfo::FPR128:
2751        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
2752        Size = 16;
2753        Alignment = Align(16);
2754        break;
2755     case RegPairInfo::ZPR:
2756        StrOpc = AArch64::STR_ZXI;
2757        Size = 16;
2758        Alignment = Align(16);
2759        break;
2760     case RegPairInfo::PPR:
2761        StrOpc = AArch64::STR_PXI;
2762        Size = 2;
2763        Alignment = Align(2);
2764        break;
2765     }
2766     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
2767                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2768                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2769                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2770                dbgs() << ")\n");
2771 
2772     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
2773            "Windows unwdinding requires a consecutive (FP,LR) pair");
2774     // Windows unwind codes require consecutive registers if registers are
2775     // paired.  Make the switch here, so that the code below will save (x,x+1)
2776     // and not (x+1,x).
2777     unsigned FrameIdxReg1 = RPI.FrameIdx;
2778     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2779     if (NeedsWinCFI && RPI.isPaired()) {
2780       std::swap(Reg1, Reg2);
2781       std::swap(FrameIdxReg1, FrameIdxReg2);
2782     }
2783     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
2784     if (!MRI.isReserved(Reg1))
2785       MBB.addLiveIn(Reg1);
2786     if (RPI.isPaired()) {
2787       if (!MRI.isReserved(Reg2))
2788         MBB.addLiveIn(Reg2);
2789       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
2790       MIB.addMemOperand(MF.getMachineMemOperand(
2791           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2792           MachineMemOperand::MOStore, Size, Alignment));
2793     }
2794     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
2795         .addReg(AArch64::SP)
2796         .addImm(RPI.Offset) // [sp, #offset*scale],
2797                             // where factor*scale is implicit
2798         .setMIFlag(MachineInstr::FrameSetup);
2799     MIB.addMemOperand(MF.getMachineMemOperand(
2800         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2801         MachineMemOperand::MOStore, Size, Alignment));
2802     if (NeedsWinCFI)
2803       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
2804 
2805     // Update the StackIDs of the SVE stack slots.
2806     MachineFrameInfo &MFI = MF.getFrameInfo();
2807     if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR)
2808       MFI.setStackID(RPI.FrameIdx, TargetStackID::ScalableVector);
2809 
2810   }
2811   return true;
2812 }
2813 
2814 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
2815     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
2816     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2817   MachineFunction &MF = *MBB.getParent();
2818   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2819   DebugLoc DL;
2820   SmallVector<RegPairInfo, 8> RegPairs;
2821   bool NeedsWinCFI = needsWinCFI(MF);
2822 
2823   if (MBBI != MBB.end())
2824     DL = MBBI->getDebugLoc();
2825 
2826   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
2827 
2828   auto EmitMI = [&](const RegPairInfo &RPI) -> MachineBasicBlock::iterator {
2829     unsigned Reg1 = RPI.Reg1;
2830     unsigned Reg2 = RPI.Reg2;
2831 
2832     // Issue sequence of restores for cs regs. The last restore may be converted
2833     // to a post-increment load later by emitEpilogue if the callee-save stack
2834     // area allocation can't be combined with the local stack area allocation.
2835     // For example:
2836     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
2837     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
2838     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
2839     // Note: see comment in spillCalleeSavedRegisters()
2840     unsigned LdrOpc;
2841     unsigned Size;
2842     Align Alignment;
2843     switch (RPI.Type) {
2844     case RegPairInfo::GPR:
2845        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
2846        Size = 8;
2847        Alignment = Align(8);
2848        break;
2849     case RegPairInfo::FPR64:
2850        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
2851        Size = 8;
2852        Alignment = Align(8);
2853        break;
2854     case RegPairInfo::FPR128:
2855        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
2856        Size = 16;
2857        Alignment = Align(16);
2858        break;
2859     case RegPairInfo::ZPR:
2860        LdrOpc = AArch64::LDR_ZXI;
2861        Size = 16;
2862        Alignment = Align(16);
2863        break;
2864     case RegPairInfo::PPR:
2865        LdrOpc = AArch64::LDR_PXI;
2866        Size = 2;
2867        Alignment = Align(2);
2868        break;
2869     }
2870     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
2871                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2872                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2873                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2874                dbgs() << ")\n");
2875 
2876     // Windows unwind codes require consecutive registers if registers are
2877     // paired.  Make the switch here, so that the code below will save (x,x+1)
2878     // and not (x+1,x).
2879     unsigned FrameIdxReg1 = RPI.FrameIdx;
2880     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2881     if (NeedsWinCFI && RPI.isPaired()) {
2882       std::swap(Reg1, Reg2);
2883       std::swap(FrameIdxReg1, FrameIdxReg2);
2884     }
2885     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));
2886     if (RPI.isPaired()) {
2887       MIB.addReg(Reg2, getDefRegState(true));
2888       MIB.addMemOperand(MF.getMachineMemOperand(
2889           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2890           MachineMemOperand::MOLoad, Size, Alignment));
2891     }
2892     MIB.addReg(Reg1, getDefRegState(true))
2893         .addReg(AArch64::SP)
2894         .addImm(RPI.Offset) // [sp, #offset*scale]
2895                             // where factor*scale is implicit
2896         .setMIFlag(MachineInstr::FrameDestroy);
2897     MIB.addMemOperand(MF.getMachineMemOperand(
2898         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2899         MachineMemOperand::MOLoad, Size, Alignment));
2900     if (NeedsWinCFI)
2901       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
2902 
2903     return MIB->getIterator();
2904   };
2905 
2906   // SVE objects are always restored in reverse order.
2907   for (const RegPairInfo &RPI : reverse(RegPairs))
2908     if (RPI.isScalable())
2909       EmitMI(RPI);
2910 
2911   if (homogeneousPrologEpilog(MF, &MBB)) {
2912     auto MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::HOM_Epilog))
2913                    .setMIFlag(MachineInstr::FrameDestroy);
2914     for (auto &RPI : RegPairs) {
2915       MIB.addReg(RPI.Reg1, RegState::Define);
2916       MIB.addReg(RPI.Reg2, RegState::Define);
2917     }
2918     return true;
2919   }
2920 
2921   if (ReverseCSRRestoreSeq) {
2922     MachineBasicBlock::iterator First = MBB.end();
2923     for (const RegPairInfo &RPI : reverse(RegPairs)) {
2924       if (RPI.isScalable())
2925         continue;
2926       MachineBasicBlock::iterator It = EmitMI(RPI);
2927       if (First == MBB.end())
2928         First = It;
2929     }
2930     if (First != MBB.end())
2931       MBB.splice(MBBI, &MBB, First);
2932   } else {
2933     for (const RegPairInfo &RPI : RegPairs) {
2934       if (RPI.isScalable())
2935         continue;
2936       (void)EmitMI(RPI);
2937     }
2938   }
2939 
2940   return true;
2941 }
2942 
2943 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
2944                                                 BitVector &SavedRegs,
2945                                                 RegScavenger *RS) const {
2946   // All calls are tail calls in GHC calling conv, and functions have no
2947   // prologue/epilogue.
2948   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
2949     return;
2950 
2951   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2952   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
2953       MF.getSubtarget().getRegisterInfo());
2954   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2955   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2956   unsigned UnspilledCSGPR = AArch64::NoRegister;
2957   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
2958 
2959   MachineFrameInfo &MFI = MF.getFrameInfo();
2960   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2961 
2962   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
2963                                 ? RegInfo->getBaseRegister()
2964                                 : (unsigned)AArch64::NoRegister;
2965 
2966   unsigned ExtraCSSpill = 0;
2967   // Figure out which callee-saved registers to save/restore.
2968   for (unsigned i = 0; CSRegs[i]; ++i) {
2969     const unsigned Reg = CSRegs[i];
2970 
2971     // Add the base pointer register to SavedRegs if it is callee-save.
2972     if (Reg == BasePointerReg)
2973       SavedRegs.set(Reg);
2974 
2975     bool RegUsed = SavedRegs.test(Reg);
2976     unsigned PairedReg = AArch64::NoRegister;
2977     if (AArch64::GPR64RegClass.contains(Reg) ||
2978         AArch64::FPR64RegClass.contains(Reg) ||
2979         AArch64::FPR128RegClass.contains(Reg))
2980       PairedReg = CSRegs[i ^ 1];
2981 
2982     if (!RegUsed) {
2983       if (AArch64::GPR64RegClass.contains(Reg) &&
2984           !RegInfo->isReservedReg(MF, Reg)) {
2985         UnspilledCSGPR = Reg;
2986         UnspilledCSGPRPaired = PairedReg;
2987       }
2988       continue;
2989     }
2990 
2991     // MachO's compact unwind format relies on all registers being stored in
2992     // pairs.
2993     // FIXME: the usual format is actually better if unwinding isn't needed.
2994     if (producePairRegisters(MF) && PairedReg != AArch64::NoRegister &&
2995         !SavedRegs.test(PairedReg)) {
2996       SavedRegs.set(PairedReg);
2997       if (AArch64::GPR64RegClass.contains(PairedReg) &&
2998           !RegInfo->isReservedReg(MF, PairedReg))
2999         ExtraCSSpill = PairedReg;
3000     }
3001   }
3002 
3003   if (MF.getFunction().getCallingConv() == CallingConv::Win64 &&
3004       !Subtarget.isTargetWindows()) {
3005     // For Windows calling convention on a non-windows OS, where X18 is treated
3006     // as reserved, back up X18 when entering non-windows code (marked with the
3007     // Windows calling convention) and restore when returning regardless of
3008     // whether the individual function uses it - it might call other functions
3009     // that clobber it.
3010     SavedRegs.set(AArch64::X18);
3011   }
3012 
3013   // Calculates the callee saved stack size.
3014   unsigned CSStackSize = 0;
3015   unsigned SVECSStackSize = 0;
3016   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3017   const MachineRegisterInfo &MRI = MF.getRegInfo();
3018   for (unsigned Reg : SavedRegs.set_bits()) {
3019     auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
3020     if (AArch64::PPRRegClass.contains(Reg) ||
3021         AArch64::ZPRRegClass.contains(Reg))
3022       SVECSStackSize += RegSize;
3023     else
3024       CSStackSize += RegSize;
3025   }
3026 
3027   // Save number of saved regs, so we can easily update CSStackSize later.
3028   unsigned NumSavedRegs = SavedRegs.count();
3029 
3030   // The frame record needs to be created by saving the appropriate registers
3031   uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
3032   if (hasFP(MF) ||
3033       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
3034     SavedRegs.set(AArch64::FP);
3035     SavedRegs.set(AArch64::LR);
3036   }
3037 
3038   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
3039              for (unsigned Reg
3040                   : SavedRegs.set_bits()) dbgs()
3041              << ' ' << printReg(Reg, RegInfo);
3042              dbgs() << "\n";);
3043 
3044   // If any callee-saved registers are used, the frame cannot be eliminated.
3045   int64_t SVEStackSize =
3046       alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
3047   bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
3048 
3049   // The CSR spill slots have not been allocated yet, so estimateStackSize
3050   // won't include them.
3051   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
3052 
3053   // Conservatively always assume BigStack when there are SVE spills.
3054   bool BigStack = SVEStackSize ||
3055                   (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
3056   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
3057     AFI->setHasStackFrame(true);
3058 
3059   // Estimate if we might need to scavenge a register at some point in order
3060   // to materialize a stack offset. If so, either spill one additional
3061   // callee-saved register or reserve a special spill slot to facilitate
3062   // register scavenging. If we already spilled an extra callee-saved register
3063   // above to keep the number of spills even, we don't need to do anything else
3064   // here.
3065   if (BigStack) {
3066     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
3067       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
3068                         << " to get a scratch register.\n");
3069       SavedRegs.set(UnspilledCSGPR);
3070       // MachO's compact unwind format relies on all registers being stored in
3071       // pairs, so if we need to spill one extra for BigStack, then we need to
3072       // store the pair.
3073       if (producePairRegisters(MF))
3074         SavedRegs.set(UnspilledCSGPRPaired);
3075       ExtraCSSpill = UnspilledCSGPR;
3076     }
3077 
3078     // If we didn't find an extra callee-saved register to spill, create
3079     // an emergency spill slot.
3080     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
3081       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3082       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
3083       unsigned Size = TRI->getSpillSize(RC);
3084       Align Alignment = TRI->getSpillAlign(RC);
3085       int FI = MFI.CreateStackObject(Size, Alignment, false);
3086       RS->addScavengingFrameIndex(FI);
3087       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
3088                         << " as the emergency spill slot.\n");
3089     }
3090   }
3091 
3092   // Adding the size of additional 64bit GPR saves.
3093   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
3094 
3095   // A Swift asynchronous context extends the frame record with a pointer
3096   // directly before FP.
3097   if (hasFP(MF) && AFI->hasSwiftAsyncContext())
3098     CSStackSize += 8;
3099 
3100   uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
3101   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
3102                << EstimatedStackSize + AlignedCSStackSize
3103                << " bytes.\n");
3104 
3105   assert((!MFI.isCalleeSavedInfoValid() ||
3106           AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
3107          "Should not invalidate callee saved info");
3108 
3109   // Round up to register pair alignment to avoid additional SP adjustment
3110   // instructions.
3111   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
3112   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
3113   AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
3114 }
3115 
3116 bool AArch64FrameLowering::assignCalleeSavedSpillSlots(
3117     MachineFunction &MF, const TargetRegisterInfo *RegInfo,
3118     std::vector<CalleeSavedInfo> &CSI, unsigned &MinCSFrameIndex,
3119     unsigned &MaxCSFrameIndex) const {
3120   bool NeedsWinCFI = needsWinCFI(MF);
3121   // To match the canonical windows frame layout, reverse the list of
3122   // callee saved registers to get them laid out by PrologEpilogInserter
3123   // in the right order. (PrologEpilogInserter allocates stack objects top
3124   // down. Windows canonical prologs store higher numbered registers at
3125   // the top, thus have the CSI array start from the highest registers.)
3126   if (NeedsWinCFI)
3127     std::reverse(CSI.begin(), CSI.end());
3128 
3129   if (CSI.empty())
3130     return true; // Early exit if no callee saved registers are modified!
3131 
3132   // Now that we know which registers need to be saved and restored, allocate
3133   // stack slots for them.
3134   MachineFrameInfo &MFI = MF.getFrameInfo();
3135   auto *AFI = MF.getInfo<AArch64FunctionInfo>();
3136 
3137   bool UsesWinAAPCS = isTargetWindows(MF);
3138   if (UsesWinAAPCS && hasFP(MF) && AFI->hasSwiftAsyncContext()) {
3139     int FrameIdx = MFI.CreateStackObject(8, Align(16), true);
3140     AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
3141     if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
3142     if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
3143   }
3144 
3145   for (auto &CS : CSI) {
3146     Register Reg = CS.getReg();
3147     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
3148 
3149     unsigned Size = RegInfo->getSpillSize(*RC);
3150     Align Alignment(RegInfo->getSpillAlign(*RC));
3151     int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
3152     CS.setFrameIdx(FrameIdx);
3153 
3154     if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
3155     if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
3156 
3157     // Grab 8 bytes below FP for the extended asynchronous frame info.
3158     if (hasFP(MF) && AFI->hasSwiftAsyncContext() && !UsesWinAAPCS &&
3159         Reg == AArch64::FP) {
3160       FrameIdx = MFI.CreateStackObject(8, Alignment, true);
3161       AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
3162       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
3163       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
3164     }
3165   }
3166   return true;
3167 }
3168 
3169 bool AArch64FrameLowering::enableStackSlotScavenging(
3170     const MachineFunction &MF) const {
3171   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3172   return AFI->hasCalleeSaveStackFreeSpace();
3173 }
3174 
3175 /// returns true if there are any SVE callee saves.
3176 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
3177                                       int &Min, int &Max) {
3178   Min = std::numeric_limits<int>::max();
3179   Max = std::numeric_limits<int>::min();
3180 
3181   if (!MFI.isCalleeSavedInfoValid())
3182     return false;
3183 
3184   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
3185   for (auto &CS : CSI) {
3186     if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
3187         AArch64::PPRRegClass.contains(CS.getReg())) {
3188       assert((Max == std::numeric_limits<int>::min() ||
3189               Max + 1 == CS.getFrameIdx()) &&
3190              "SVE CalleeSaves are not consecutive");
3191 
3192       Min = std::min(Min, CS.getFrameIdx());
3193       Max = std::max(Max, CS.getFrameIdx());
3194     }
3195   }
3196   return Min != std::numeric_limits<int>::max();
3197 }
3198 
3199 // Process all the SVE stack objects and determine offsets for each
3200 // object. If AssignOffsets is true, the offsets get assigned.
3201 // Fills in the first and last callee-saved frame indices into
3202 // Min/MaxCSFrameIndex, respectively.
3203 // Returns the size of the stack.
3204 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
3205                                               int &MinCSFrameIndex,
3206                                               int &MaxCSFrameIndex,
3207                                               bool AssignOffsets) {
3208 #ifndef NDEBUG
3209   // First process all fixed stack objects.
3210   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
3211     assert(MFI.getStackID(I) != TargetStackID::ScalableVector &&
3212            "SVE vectors should never be passed on the stack by value, only by "
3213            "reference.");
3214 #endif
3215 
3216   auto Assign = [&MFI](int FI, int64_t Offset) {
3217     LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
3218     MFI.setObjectOffset(FI, Offset);
3219   };
3220 
3221   int64_t Offset = 0;
3222 
3223   // Then process all callee saved slots.
3224   if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
3225     // Assign offsets to the callee save slots.
3226     for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
3227       Offset += MFI.getObjectSize(I);
3228       Offset = alignTo(Offset, MFI.getObjectAlign(I));
3229       if (AssignOffsets)
3230         Assign(I, -Offset);
3231     }
3232   }
3233 
3234   // Ensure that the Callee-save area is aligned to 16bytes.
3235   Offset = alignTo(Offset, Align(16U));
3236 
3237   // Create a buffer of SVE objects to allocate and sort it.
3238   SmallVector<int, 8> ObjectsToAllocate;
3239   // If we have a stack protector, and we've previously decided that we have SVE
3240   // objects on the stack and thus need it to go in the SVE stack area, then it
3241   // needs to go first.
3242   int StackProtectorFI = -1;
3243   if (MFI.hasStackProtectorIndex()) {
3244     StackProtectorFI = MFI.getStackProtectorIndex();
3245     if (MFI.getStackID(StackProtectorFI) == TargetStackID::ScalableVector)
3246       ObjectsToAllocate.push_back(StackProtectorFI);
3247   }
3248   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
3249     unsigned StackID = MFI.getStackID(I);
3250     if (StackID != TargetStackID::ScalableVector)
3251       continue;
3252     if (I == StackProtectorFI)
3253       continue;
3254     if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
3255       continue;
3256     if (MFI.isDeadObjectIndex(I))
3257       continue;
3258 
3259     ObjectsToAllocate.push_back(I);
3260   }
3261 
3262   // Allocate all SVE locals and spills
3263   for (unsigned FI : ObjectsToAllocate) {
3264     Align Alignment = MFI.getObjectAlign(FI);
3265     // FIXME: Given that the length of SVE vectors is not necessarily a power of
3266     // two, we'd need to align every object dynamically at runtime if the
3267     // alignment is larger than 16. This is not yet supported.
3268     if (Alignment > Align(16))
3269       report_fatal_error(
3270           "Alignment of scalable vectors > 16 bytes is not yet supported");
3271 
3272     Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment);
3273     if (AssignOffsets)
3274       Assign(FI, -Offset);
3275   }
3276 
3277   return Offset;
3278 }
3279 
3280 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
3281     MachineFrameInfo &MFI) const {
3282   int MinCSFrameIndex, MaxCSFrameIndex;
3283   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
3284 }
3285 
3286 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
3287     MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
3288   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
3289                                         true);
3290 }
3291 
3292 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
3293     MachineFunction &MF, RegScavenger *RS) const {
3294   MachineFrameInfo &MFI = MF.getFrameInfo();
3295 
3296   assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
3297          "Upwards growing stack unsupported");
3298 
3299   int MinCSFrameIndex, MaxCSFrameIndex;
3300   int64_t SVEStackSize =
3301       assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
3302 
3303   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3304   AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
3305   AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
3306 
3307   // If this function isn't doing Win64-style C++ EH, we don't need to do
3308   // anything.
3309   if (!MF.hasEHFunclets())
3310     return;
3311   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
3312   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
3313 
3314   MachineBasicBlock &MBB = MF.front();
3315   auto MBBI = MBB.begin();
3316   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
3317     ++MBBI;
3318 
3319   // Create an UnwindHelp object.
3320   // The UnwindHelp object is allocated at the start of the fixed object area
3321   int64_t FixedObject =
3322       getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false);
3323   int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8,
3324                                            /*SPOffset*/ -FixedObject,
3325                                            /*IsImmutable=*/false);
3326   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
3327 
3328   // We need to store -2 into the UnwindHelp object at the start of the
3329   // function.
3330   DebugLoc DL;
3331   RS->enterBasicBlockEnd(MBB);
3332   RS->backward(std::prev(MBBI));
3333   Register DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
3334   assert(DstReg && "There must be a free register after frame setup");
3335   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
3336   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
3337       .addReg(DstReg, getKillRegState(true))
3338       .addFrameIndex(UnwindHelpFI)
3339       .addImm(0);
3340 }
3341 
3342 namespace {
3343 struct TagStoreInstr {
3344   MachineInstr *MI;
3345   int64_t Offset, Size;
3346   explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)
3347       : MI(MI), Offset(Offset), Size(Size) {}
3348 };
3349 
3350 class TagStoreEdit {
3351   MachineFunction *MF;
3352   MachineBasicBlock *MBB;
3353   MachineRegisterInfo *MRI;
3354   // Tag store instructions that are being replaced.
3355   SmallVector<TagStoreInstr, 8> TagStores;
3356   // Combined memref arguments of the above instructions.
3357   SmallVector<MachineMemOperand *, 8> CombinedMemRefs;
3358 
3359   // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
3360   // FrameRegOffset + Size) with the address tag of SP.
3361   Register FrameReg;
3362   StackOffset FrameRegOffset;
3363   int64_t Size;
3364   // If not None, move FrameReg to (FrameReg + FrameRegUpdate) at the end.
3365   Optional<int64_t> FrameRegUpdate;
3366   // MIFlags for any FrameReg updating instructions.
3367   unsigned FrameRegUpdateFlags;
3368 
3369   // Use zeroing instruction variants.
3370   bool ZeroData;
3371   DebugLoc DL;
3372 
3373   void emitUnrolled(MachineBasicBlock::iterator InsertI);
3374   void emitLoop(MachineBasicBlock::iterator InsertI);
3375 
3376 public:
3377   TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)
3378       : MBB(MBB), ZeroData(ZeroData) {
3379     MF = MBB->getParent();
3380     MRI = &MF->getRegInfo();
3381   }
3382   // Add an instruction to be replaced. Instructions must be added in the
3383   // ascending order of Offset, and have to be adjacent.
3384   void addInstruction(TagStoreInstr I) {
3385     assert((TagStores.empty() ||
3386             TagStores.back().Offset + TagStores.back().Size == I.Offset) &&
3387            "Non-adjacent tag store instructions.");
3388     TagStores.push_back(I);
3389   }
3390   void clear() { TagStores.clear(); }
3391   // Emit equivalent code at the given location, and erase the current set of
3392   // instructions. May skip if the replacement is not profitable. May invalidate
3393   // the input iterator and replace it with a valid one.
3394   void emitCode(MachineBasicBlock::iterator &InsertI,
3395                 const AArch64FrameLowering *TFI, bool TryMergeSPUpdate);
3396 };
3397 
3398 void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {
3399   const AArch64InstrInfo *TII =
3400       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
3401 
3402   const int64_t kMinOffset = -256 * 16;
3403   const int64_t kMaxOffset = 255 * 16;
3404 
3405   Register BaseReg = FrameReg;
3406   int64_t BaseRegOffsetBytes = FrameRegOffset.getFixed();
3407   if (BaseRegOffsetBytes < kMinOffset ||
3408       BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset) {
3409     Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3410     emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,
3411                     StackOffset::getFixed(BaseRegOffsetBytes), TII);
3412     BaseReg = ScratchReg;
3413     BaseRegOffsetBytes = 0;
3414   }
3415 
3416   MachineInstr *LastI = nullptr;
3417   while (Size) {
3418     int64_t InstrSize = (Size > 16) ? 32 : 16;
3419     unsigned Opcode =
3420         InstrSize == 16
3421             ? (ZeroData ? AArch64::STZGOffset : AArch64::STGOffset)
3422             : (ZeroData ? AArch64::STZ2GOffset : AArch64::ST2GOffset);
3423     MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))
3424                           .addReg(AArch64::SP)
3425                           .addReg(BaseReg)
3426                           .addImm(BaseRegOffsetBytes / 16)
3427                           .setMemRefs(CombinedMemRefs);
3428     // A store to [BaseReg, #0] should go last for an opportunity to fold the
3429     // final SP adjustment in the epilogue.
3430     if (BaseRegOffsetBytes == 0)
3431       LastI = I;
3432     BaseRegOffsetBytes += InstrSize;
3433     Size -= InstrSize;
3434   }
3435 
3436   if (LastI)
3437     MBB->splice(InsertI, MBB, LastI);
3438 }
3439 
3440 void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {
3441   const AArch64InstrInfo *TII =
3442       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
3443 
3444   Register BaseReg = FrameRegUpdate
3445                          ? FrameReg
3446                          : MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3447   Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3448 
3449   emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);
3450 
3451   int64_t LoopSize = Size;
3452   // If the loop size is not a multiple of 32, split off one 16-byte store at
3453   // the end to fold BaseReg update into.
3454   if (FrameRegUpdate && *FrameRegUpdate)
3455     LoopSize -= LoopSize % 32;
3456   MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,
3457                                 TII->get(ZeroData ? AArch64::STZGloop_wback
3458                                                   : AArch64::STGloop_wback))
3459                             .addDef(SizeReg)
3460                             .addDef(BaseReg)
3461                             .addImm(LoopSize)
3462                             .addReg(BaseReg)
3463                             .setMemRefs(CombinedMemRefs);
3464   if (FrameRegUpdate)
3465     LoopI->setFlags(FrameRegUpdateFlags);
3466 
3467   int64_t ExtraBaseRegUpdate =
3468       FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getFixed() - Size) : 0;
3469   if (LoopSize < Size) {
3470     assert(FrameRegUpdate);
3471     assert(Size - LoopSize == 16);
3472     // Tag 16 more bytes at BaseReg and update BaseReg.
3473     BuildMI(*MBB, InsertI, DL,
3474             TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))
3475         .addDef(BaseReg)
3476         .addReg(BaseReg)
3477         .addReg(BaseReg)
3478         .addImm(1 + ExtraBaseRegUpdate / 16)
3479         .setMemRefs(CombinedMemRefs)
3480         .setMIFlags(FrameRegUpdateFlags);
3481   } else if (ExtraBaseRegUpdate) {
3482     // Update BaseReg.
3483     BuildMI(
3484         *MBB, InsertI, DL,
3485         TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))
3486         .addDef(BaseReg)
3487         .addReg(BaseReg)
3488         .addImm(std::abs(ExtraBaseRegUpdate))
3489         .addImm(0)
3490         .setMIFlags(FrameRegUpdateFlags);
3491   }
3492 }
3493 
3494 // Check if *II is a register update that can be merged into STGloop that ends
3495 // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
3496 // end of the loop.
3497 bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,
3498                        int64_t Size, int64_t *TotalOffset) {
3499   MachineInstr &MI = *II;
3500   if ((MI.getOpcode() == AArch64::ADDXri ||
3501        MI.getOpcode() == AArch64::SUBXri) &&
3502       MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {
3503     unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());
3504     int64_t Offset = MI.getOperand(2).getImm() << Shift;
3505     if (MI.getOpcode() == AArch64::SUBXri)
3506       Offset = -Offset;
3507     int64_t AbsPostOffset = std::abs(Offset - Size);
3508     const int64_t kMaxOffset =
3509         0xFFF; // Max encoding for unshifted ADDXri / SUBXri
3510     if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) {
3511       *TotalOffset = Offset;
3512       return true;
3513     }
3514   }
3515   return false;
3516 }
3517 
3518 void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,
3519                   SmallVectorImpl<MachineMemOperand *> &MemRefs) {
3520   MemRefs.clear();
3521   for (auto &TS : TSE) {
3522     MachineInstr *MI = TS.MI;
3523     // An instruction without memory operands may access anything. Be
3524     // conservative and return an empty list.
3525     if (MI->memoperands_empty()) {
3526       MemRefs.clear();
3527       return;
3528     }
3529     MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());
3530   }
3531 }
3532 
3533 void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,
3534                             const AArch64FrameLowering *TFI,
3535                             bool TryMergeSPUpdate) {
3536   if (TagStores.empty())
3537     return;
3538   TagStoreInstr &FirstTagStore = TagStores[0];
3539   TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];
3540   Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;
3541   DL = TagStores[0].MI->getDebugLoc();
3542 
3543   Register Reg;
3544   FrameRegOffset = TFI->resolveFrameOffsetReference(
3545       *MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg,
3546       /*PreferFP=*/false, /*ForSimm=*/true);
3547   FrameReg = Reg;
3548   FrameRegUpdate = None;
3549 
3550   mergeMemRefs(TagStores, CombinedMemRefs);
3551 
3552   LLVM_DEBUG(dbgs() << "Replacing adjacent STG instructions:\n";
3553              for (const auto &Instr
3554                   : TagStores) { dbgs() << "  " << *Instr.MI; });
3555 
3556   // Size threshold where a loop becomes shorter than a linear sequence of
3557   // tagging instructions.
3558   const int kSetTagLoopThreshold = 176;
3559   if (Size < kSetTagLoopThreshold) {
3560     if (TagStores.size() < 2)
3561       return;
3562     emitUnrolled(InsertI);
3563   } else {
3564     MachineInstr *UpdateInstr = nullptr;
3565     int64_t TotalOffset = 0;
3566     if (TryMergeSPUpdate) {
3567       // See if we can merge base register update into the STGloop.
3568       // This is done in AArch64LoadStoreOptimizer for "normal" stores,
3569       // but STGloop is way too unusual for that, and also it only
3570       // realistically happens in function epilogue. Also, STGloop is expanded
3571       // before that pass.
3572       if (InsertI != MBB->end() &&
3573           canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getFixed() + Size,
3574                             &TotalOffset)) {
3575         UpdateInstr = &*InsertI++;
3576         LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n  "
3577                           << *UpdateInstr);
3578       }
3579     }
3580 
3581     if (!UpdateInstr && TagStores.size() < 2)
3582       return;
3583 
3584     if (UpdateInstr) {
3585       FrameRegUpdate = TotalOffset;
3586       FrameRegUpdateFlags = UpdateInstr->getFlags();
3587     }
3588     emitLoop(InsertI);
3589     if (UpdateInstr)
3590       UpdateInstr->eraseFromParent();
3591   }
3592 
3593   for (auto &TS : TagStores)
3594     TS.MI->eraseFromParent();
3595 }
3596 
3597 bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,
3598                                         int64_t &Size, bool &ZeroData) {
3599   MachineFunction &MF = *MI.getParent()->getParent();
3600   const MachineFrameInfo &MFI = MF.getFrameInfo();
3601 
3602   unsigned Opcode = MI.getOpcode();
3603   ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGOffset ||
3604               Opcode == AArch64::STZ2GOffset);
3605 
3606   if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {
3607     if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())
3608       return false;
3609     if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())
3610       return false;
3611     Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());
3612     Size = MI.getOperand(2).getImm();
3613     return true;
3614   }
3615 
3616   if (Opcode == AArch64::STGOffset || Opcode == AArch64::STZGOffset)
3617     Size = 16;
3618   else if (Opcode == AArch64::ST2GOffset || Opcode == AArch64::STZ2GOffset)
3619     Size = 32;
3620   else
3621     return false;
3622 
3623   if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())
3624     return false;
3625 
3626   Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +
3627            16 * MI.getOperand(2).getImm();
3628   return true;
3629 }
3630 
3631 // Detect a run of memory tagging instructions for adjacent stack frame slots,
3632 // and replace them with a shorter instruction sequence:
3633 // * replace STG + STG with ST2G
3634 // * replace STGloop + STGloop with STGloop
3635 // This code needs to run when stack slot offsets are already known, but before
3636 // FrameIndex operands in STG instructions are eliminated.
3637 MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II,
3638                                                 const AArch64FrameLowering *TFI,
3639                                                 RegScavenger *RS) {
3640   bool FirstZeroData;
3641   int64_t Size, Offset;
3642   MachineInstr &MI = *II;
3643   MachineBasicBlock *MBB = MI.getParent();
3644   MachineBasicBlock::iterator NextI = ++II;
3645   if (&MI == &MBB->instr_back())
3646     return II;
3647   if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))
3648     return II;
3649 
3650   SmallVector<TagStoreInstr, 4> Instrs;
3651   Instrs.emplace_back(&MI, Offset, Size);
3652 
3653   constexpr int kScanLimit = 10;
3654   int Count = 0;
3655   for (MachineBasicBlock::iterator E = MBB->end();
3656        NextI != E && Count < kScanLimit; ++NextI) {
3657     MachineInstr &MI = *NextI;
3658     bool ZeroData;
3659     int64_t Size, Offset;
3660     // Collect instructions that update memory tags with a FrameIndex operand
3661     // and (when applicable) constant size, and whose output registers are dead
3662     // (the latter is almost always the case in practice). Since these
3663     // instructions effectively have no inputs or outputs, we are free to skip
3664     // any non-aliasing instructions in between without tracking used registers.
3665     if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {
3666       if (ZeroData != FirstZeroData)
3667         break;
3668       Instrs.emplace_back(&MI, Offset, Size);
3669       continue;
3670     }
3671 
3672     // Only count non-transient, non-tagging instructions toward the scan
3673     // limit.
3674     if (!MI.isTransient())
3675       ++Count;
3676 
3677     // Just in case, stop before the epilogue code starts.
3678     if (MI.getFlag(MachineInstr::FrameSetup) ||
3679         MI.getFlag(MachineInstr::FrameDestroy))
3680       break;
3681 
3682     // Reject anything that may alias the collected instructions.
3683     if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects())
3684       break;
3685   }
3686 
3687   // New code will be inserted after the last tagging instruction we've found.
3688   MachineBasicBlock::iterator InsertI = Instrs.back().MI;
3689   InsertI++;
3690 
3691   llvm::stable_sort(Instrs,
3692                     [](const TagStoreInstr &Left, const TagStoreInstr &Right) {
3693                       return Left.Offset < Right.Offset;
3694                     });
3695 
3696   // Make sure that we don't have any overlapping stores.
3697   int64_t CurOffset = Instrs[0].Offset;
3698   for (auto &Instr : Instrs) {
3699     if (CurOffset > Instr.Offset)
3700       return NextI;
3701     CurOffset = Instr.Offset + Instr.Size;
3702   }
3703 
3704   // Find contiguous runs of tagged memory and emit shorter instruction
3705   // sequencies for them when possible.
3706   TagStoreEdit TSE(MBB, FirstZeroData);
3707   Optional<int64_t> EndOffset;
3708   for (auto &Instr : Instrs) {
3709     if (EndOffset && *EndOffset != Instr.Offset) {
3710       // Found a gap.
3711       TSE.emitCode(InsertI, TFI, /*TryMergeSPUpdate = */ false);
3712       TSE.clear();
3713     }
3714 
3715     TSE.addInstruction(Instr);
3716     EndOffset = Instr.Offset + Instr.Size;
3717   }
3718 
3719   // Multiple FP/SP updates in a loop cannot be described by CFI instructions.
3720   TSE.emitCode(InsertI, TFI, /*TryMergeSPUpdate = */
3721                !MBB->getParent()
3722                     ->getInfo<AArch64FunctionInfo>()
3723                     ->needsAsyncDwarfUnwindInfo());
3724 
3725   return InsertI;
3726 }
3727 } // namespace
3728 
3729 void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(
3730     MachineFunction &MF, RegScavenger *RS = nullptr) const {
3731   if (StackTaggingMergeSetTag)
3732     for (auto &BB : MF)
3733       for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();)
3734         II = tryMergeAdjacentSTG(II, this, RS);
3735 }
3736 
3737 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
3738 /// before the update.  This is easily retrieved as it is exactly the offset
3739 /// that is set in processFunctionBeforeFrameFinalized.
3740 StackOffset AArch64FrameLowering::getFrameIndexReferencePreferSP(
3741     const MachineFunction &MF, int FI, Register &FrameReg,
3742     bool IgnoreSPUpdates) const {
3743   const MachineFrameInfo &MFI = MF.getFrameInfo();
3744   if (IgnoreSPUpdates) {
3745     LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
3746                       << MFI.getObjectOffset(FI) << "\n");
3747     FrameReg = AArch64::SP;
3748     return StackOffset::getFixed(MFI.getObjectOffset(FI));
3749   }
3750 
3751   // Go to common code if we cannot provide sp + offset.
3752   if (MFI.hasVarSizedObjects() ||
3753       MF.getInfo<AArch64FunctionInfo>()->getStackSizeSVE() ||
3754       MF.getSubtarget().getRegisterInfo()->hasStackRealignment(MF))
3755     return getFrameIndexReference(MF, FI, FrameReg);
3756 
3757   FrameReg = AArch64::SP;
3758   return getStackOffset(MF, MFI.getObjectOffset(FI));
3759 }
3760 
3761 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
3762 /// the parent's frame pointer
3763 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
3764     const MachineFunction &MF) const {
3765   return 0;
3766 }
3767 
3768 /// Funclets only need to account for space for the callee saved registers,
3769 /// as the locals are accounted for in the parent's stack frame.
3770 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
3771     const MachineFunction &MF) const {
3772   // This is the size of the pushed CSRs.
3773   unsigned CSSize =
3774       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
3775   // This is the amount of stack a funclet needs to allocate.
3776   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
3777                  getStackAlign());
3778 }
3779 
3780 namespace {
3781 struct FrameObject {
3782   bool IsValid = false;
3783   // Index of the object in MFI.
3784   int ObjectIndex = 0;
3785   // Group ID this object belongs to.
3786   int GroupIndex = -1;
3787   // This object should be placed first (closest to SP).
3788   bool ObjectFirst = false;
3789   // This object's group (which always contains the object with
3790   // ObjectFirst==true) should be placed first.
3791   bool GroupFirst = false;
3792 };
3793 
3794 class GroupBuilder {
3795   SmallVector<int, 8> CurrentMembers;
3796   int NextGroupIndex = 0;
3797   std::vector<FrameObject> &Objects;
3798 
3799 public:
3800   GroupBuilder(std::vector<FrameObject> &Objects) : Objects(Objects) {}
3801   void AddMember(int Index) { CurrentMembers.push_back(Index); }
3802   void EndCurrentGroup() {
3803     if (CurrentMembers.size() > 1) {
3804       // Create a new group with the current member list. This might remove them
3805       // from their pre-existing groups. That's OK, dealing with overlapping
3806       // groups is too hard and unlikely to make a difference.
3807       LLVM_DEBUG(dbgs() << "group:");
3808       for (int Index : CurrentMembers) {
3809         Objects[Index].GroupIndex = NextGroupIndex;
3810         LLVM_DEBUG(dbgs() << " " << Index);
3811       }
3812       LLVM_DEBUG(dbgs() << "\n");
3813       NextGroupIndex++;
3814     }
3815     CurrentMembers.clear();
3816   }
3817 };
3818 
3819 bool FrameObjectCompare(const FrameObject &A, const FrameObject &B) {
3820   // Objects at a lower index are closer to FP; objects at a higher index are
3821   // closer to SP.
3822   //
3823   // For consistency in our comparison, all invalid objects are placed
3824   // at the end. This also allows us to stop walking when we hit the
3825   // first invalid item after it's all sorted.
3826   //
3827   // The "first" object goes first (closest to SP), followed by the members of
3828   // the "first" group.
3829   //
3830   // The rest are sorted by the group index to keep the groups together.
3831   // Higher numbered groups are more likely to be around longer (i.e. untagged
3832   // in the function epilogue and not at some earlier point). Place them closer
3833   // to SP.
3834   //
3835   // If all else equal, sort by the object index to keep the objects in the
3836   // original order.
3837   return std::make_tuple(!A.IsValid, A.ObjectFirst, A.GroupFirst, A.GroupIndex,
3838                          A.ObjectIndex) <
3839          std::make_tuple(!B.IsValid, B.ObjectFirst, B.GroupFirst, B.GroupIndex,
3840                          B.ObjectIndex);
3841 }
3842 } // namespace
3843 
3844 void AArch64FrameLowering::orderFrameObjects(
3845     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
3846   if (!OrderFrameObjects || ObjectsToAllocate.empty())
3847     return;
3848 
3849   const MachineFrameInfo &MFI = MF.getFrameInfo();
3850   std::vector<FrameObject> FrameObjects(MFI.getObjectIndexEnd());
3851   for (auto &Obj : ObjectsToAllocate) {
3852     FrameObjects[Obj].IsValid = true;
3853     FrameObjects[Obj].ObjectIndex = Obj;
3854   }
3855 
3856   // Identify stack slots that are tagged at the same time.
3857   GroupBuilder GB(FrameObjects);
3858   for (auto &MBB : MF) {
3859     for (auto &MI : MBB) {
3860       if (MI.isDebugInstr())
3861         continue;
3862       int OpIndex;
3863       switch (MI.getOpcode()) {
3864       case AArch64::STGloop:
3865       case AArch64::STZGloop:
3866         OpIndex = 3;
3867         break;
3868       case AArch64::STGOffset:
3869       case AArch64::STZGOffset:
3870       case AArch64::ST2GOffset:
3871       case AArch64::STZ2GOffset:
3872         OpIndex = 1;
3873         break;
3874       default:
3875         OpIndex = -1;
3876       }
3877 
3878       int TaggedFI = -1;
3879       if (OpIndex >= 0) {
3880         const MachineOperand &MO = MI.getOperand(OpIndex);
3881         if (MO.isFI()) {
3882           int FI = MO.getIndex();
3883           if (FI >= 0 && FI < MFI.getObjectIndexEnd() &&
3884               FrameObjects[FI].IsValid)
3885             TaggedFI = FI;
3886         }
3887       }
3888 
3889       // If this is a stack tagging instruction for a slot that is not part of a
3890       // group yet, either start a new group or add it to the current one.
3891       if (TaggedFI >= 0)
3892         GB.AddMember(TaggedFI);
3893       else
3894         GB.EndCurrentGroup();
3895     }
3896     // Groups should never span multiple basic blocks.
3897     GB.EndCurrentGroup();
3898   }
3899 
3900   // If the function's tagged base pointer is pinned to a stack slot, we want to
3901   // put that slot first when possible. This will likely place it at SP + 0,
3902   // and save one instruction when generating the base pointer because IRG does
3903   // not allow an immediate offset.
3904   const AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
3905   Optional<int> TBPI = AFI.getTaggedBasePointerIndex();
3906   if (TBPI) {
3907     FrameObjects[*TBPI].ObjectFirst = true;
3908     FrameObjects[*TBPI].GroupFirst = true;
3909     int FirstGroupIndex = FrameObjects[*TBPI].GroupIndex;
3910     if (FirstGroupIndex >= 0)
3911       for (FrameObject &Object : FrameObjects)
3912         if (Object.GroupIndex == FirstGroupIndex)
3913           Object.GroupFirst = true;
3914   }
3915 
3916   llvm::stable_sort(FrameObjects, FrameObjectCompare);
3917 
3918   int i = 0;
3919   for (auto &Obj : FrameObjects) {
3920     // All invalid items are sorted at the end, so it's safe to stop.
3921     if (!Obj.IsValid)
3922       break;
3923     ObjectsToAllocate[i++] = Obj.ObjectIndex;
3924   }
3925 
3926   LLVM_DEBUG(dbgs() << "Final frame order:\n"; for (auto &Obj
3927                                                     : FrameObjects) {
3928     if (!Obj.IsValid)
3929       break;
3930     dbgs() << "  " << Obj.ObjectIndex << ": group " << Obj.GroupIndex;
3931     if (Obj.ObjectFirst)
3932       dbgs() << ", first";
3933     if (Obj.GroupFirst)
3934       dbgs() << ", group-first";
3935     dbgs() << "\n";
3936   });
3937 }
3938