xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AArch64/AArch64FrameLowering.cpp (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
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 // |   <hazard padding>                |
56 // |-----------------------------------|
57 // |                                   |
58 // | callee-saved fp/simd/SVE regs     |
59 // |                                   |
60 // |-----------------------------------|
61 // |                                   |
62 // |        SVE stack objects          |
63 // |                                   |
64 // |-----------------------------------|
65 // |.empty.space.to.make.part.below....|
66 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
67 // |.the.standard.16-byte.alignment....|  compile time; if present)
68 // |-----------------------------------|
69 // | local variables of fixed size     |
70 // | including spill slots             |
71 // |   <FPR>                           |
72 // |   <hazard padding>                |
73 // |   <GPR>                           |
74 // |-----------------------------------| <- bp(not defined by ABI,
75 // |.variable-sized.local.variables....|       LLVM chooses X19)
76 // |.(VLAs)............................| (size of this area is unknown at
77 // |...................................|  compile time)
78 // |-----------------------------------| <- sp
79 // |                                   | Lower address
80 //
81 //
82 // To access the data in a frame, at-compile time, a constant offset must be
83 // computable from one of the pointers (fp, bp, sp) to access it. The size
84 // of the areas with a dotted background cannot be computed at compile-time
85 // if they are present, making it required to have all three of fp, bp and
86 // sp to be set up to be able to access all contents in the frame areas,
87 // assuming all of the frame areas are non-empty.
88 //
89 // For most functions, some of the frame areas are empty. For those functions,
90 // it may not be necessary to set up fp or bp:
91 // * A base pointer is definitely needed when there are both VLAs and local
92 //   variables with more-than-default alignment requirements.
93 // * A frame pointer is definitely needed when there are local variables with
94 //   more-than-default alignment requirements.
95 //
96 // For Darwin platforms the frame-record (fp, lr) is stored at the top of the
97 // callee-saved area, since the unwind encoding does not allow for encoding
98 // this dynamically and existing tools depend on this layout. For other
99 // platforms, the frame-record is stored at the bottom of the (gpr) callee-saved
100 // area to allow SVE stack objects (allocated directly below the callee-saves,
101 // if available) to be accessed directly from the framepointer.
102 // The SVE spill/fill instructions have VL-scaled addressing modes such
103 // as:
104 //    ldr z8, [fp, #-7 mul vl]
105 // For SVE the size of the vector length (VL) is not known at compile-time, so
106 // '#-7 mul vl' is an offset that can only be evaluated at runtime. With this
107 // layout, we don't need to add an unscaled offset to the framepointer before
108 // accessing the SVE object in the frame.
109 //
110 // In some cases when a base pointer is not strictly needed, it is generated
111 // anyway when offsets from the frame pointer to access local variables become
112 // so large that the offset can't be encoded in the immediate fields of loads
113 // or stores.
114 //
115 // Outgoing function arguments must be at the bottom of the stack frame when
116 // calling another function. If we do not have variable-sized stack objects, we
117 // can allocate a "reserved call frame" area at the bottom of the local
118 // variable area, large enough for all outgoing calls. If we do have VLAs, then
119 // the stack pointer must be decremented and incremented around each call to
120 // make space for the arguments below the VLAs.
121 //
122 // FIXME: also explain the redzone concept.
123 //
124 // About stack hazards: Under some SME contexts, a coprocessor with its own
125 // separate cache can used for FP operations. This can create hazards if the CPU
126 // and the SME unit try to access the same area of memory, including if the
127 // access is to an area of the stack. To try to alleviate this we attempt to
128 // introduce extra padding into the stack frame between FP and GPR accesses,
129 // controlled by the StackHazardSize option. Without changing the layout of the
130 // stack frame in the diagram above, a stack object of size StackHazardSize is
131 // added between GPR and FPR CSRs. Another is added to the stack objects
132 // section, and stack objects are sorted so that FPR > Hazard padding slot >
133 // GPRs (where possible). Unfortunately some things are not handled well (VLA
134 // area, arguments on the stack, object with both GPR and FPR accesses), but if
135 // those are controlled by the user then the entire stack frame becomes GPR at
136 // the start/end with FPR in the middle, surrounded by Hazard padding.
137 //
138 // An example of the prologue:
139 //
140 //     .globl __foo
141 //     .align 2
142 //  __foo:
143 // Ltmp0:
144 //     .cfi_startproc
145 //     .cfi_personality 155, ___gxx_personality_v0
146 // Leh_func_begin:
147 //     .cfi_lsda 16, Lexception33
148 //
149 //     stp  xa,bx, [sp, -#offset]!
150 //     ...
151 //     stp  x28, x27, [sp, #offset-32]
152 //     stp  fp, lr, [sp, #offset-16]
153 //     add  fp, sp, #offset - 16
154 //     sub  sp, sp, #1360
155 //
156 // The Stack:
157 //       +-------------------------------------------+
158 // 10000 | ........ | ........ | ........ | ........ |
159 // 10004 | ........ | ........ | ........ | ........ |
160 //       +-------------------------------------------+
161 // 10008 | ........ | ........ | ........ | ........ |
162 // 1000c | ........ | ........ | ........ | ........ |
163 //       +===========================================+
164 // 10010 |                X28 Register               |
165 // 10014 |                X28 Register               |
166 //       +-------------------------------------------+
167 // 10018 |                X27 Register               |
168 // 1001c |                X27 Register               |
169 //       +===========================================+
170 // 10020 |                Frame Pointer              |
171 // 10024 |                Frame Pointer              |
172 //       +-------------------------------------------+
173 // 10028 |                Link Register              |
174 // 1002c |                Link Register              |
175 //       +===========================================+
176 // 10030 | ........ | ........ | ........ | ........ |
177 // 10034 | ........ | ........ | ........ | ........ |
178 //       +-------------------------------------------+
179 // 10038 | ........ | ........ | ........ | ........ |
180 // 1003c | ........ | ........ | ........ | ........ |
181 //       +-------------------------------------------+
182 //
183 //     [sp] = 10030        ::    >>initial value<<
184 //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
185 //     fp = sp == 10020    ::  mov fp, sp
186 //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
187 //     sp == 10010         ::    >>final value<<
188 //
189 // The frame pointer (w29) points to address 10020. If we use an offset of
190 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
191 // for w27, and -32 for w28:
192 //
193 //  Ltmp1:
194 //     .cfi_def_cfa w29, 16
195 //  Ltmp2:
196 //     .cfi_offset w30, -8
197 //  Ltmp3:
198 //     .cfi_offset w29, -16
199 //  Ltmp4:
200 //     .cfi_offset w27, -24
201 //  Ltmp5:
202 //     .cfi_offset w28, -32
203 //
204 //===----------------------------------------------------------------------===//
205 
206 #include "AArch64FrameLowering.h"
207 #include "AArch64InstrInfo.h"
208 #include "AArch64MachineFunctionInfo.h"
209 #include "AArch64RegisterInfo.h"
210 #include "AArch64Subtarget.h"
211 #include "AArch64TargetMachine.h"
212 #include "MCTargetDesc/AArch64AddressingModes.h"
213 #include "MCTargetDesc/AArch64MCTargetDesc.h"
214 #include "llvm/ADT/ScopeExit.h"
215 #include "llvm/ADT/SmallVector.h"
216 #include "llvm/ADT/Statistic.h"
217 #include "llvm/Analysis/ValueTracking.h"
218 #include "llvm/CodeGen/LivePhysRegs.h"
219 #include "llvm/CodeGen/MachineBasicBlock.h"
220 #include "llvm/CodeGen/MachineFrameInfo.h"
221 #include "llvm/CodeGen/MachineFunction.h"
222 #include "llvm/CodeGen/MachineInstr.h"
223 #include "llvm/CodeGen/MachineInstrBuilder.h"
224 #include "llvm/CodeGen/MachineMemOperand.h"
225 #include "llvm/CodeGen/MachineModuleInfo.h"
226 #include "llvm/CodeGen/MachineOperand.h"
227 #include "llvm/CodeGen/MachineRegisterInfo.h"
228 #include "llvm/CodeGen/RegisterScavenging.h"
229 #include "llvm/CodeGen/TargetInstrInfo.h"
230 #include "llvm/CodeGen/TargetRegisterInfo.h"
231 #include "llvm/CodeGen/TargetSubtargetInfo.h"
232 #include "llvm/CodeGen/WinEHFuncInfo.h"
233 #include "llvm/IR/Attributes.h"
234 #include "llvm/IR/CallingConv.h"
235 #include "llvm/IR/DataLayout.h"
236 #include "llvm/IR/DebugLoc.h"
237 #include "llvm/IR/Function.h"
238 #include "llvm/MC/MCAsmInfo.h"
239 #include "llvm/MC/MCDwarf.h"
240 #include "llvm/Support/CommandLine.h"
241 #include "llvm/Support/Debug.h"
242 #include "llvm/Support/ErrorHandling.h"
243 #include "llvm/Support/FormatVariadic.h"
244 #include "llvm/Support/MathExtras.h"
245 #include "llvm/Support/raw_ostream.h"
246 #include "llvm/Target/TargetMachine.h"
247 #include "llvm/Target/TargetOptions.h"
248 #include <cassert>
249 #include <cstdint>
250 #include <iterator>
251 #include <optional>
252 #include <vector>
253 
254 using namespace llvm;
255 
256 #define DEBUG_TYPE "frame-info"
257 
258 static cl::opt<bool> EnableRedZone("aarch64-redzone",
259                                    cl::desc("enable use of redzone on AArch64"),
260                                    cl::init(false), cl::Hidden);
261 
262 static cl::opt<bool> StackTaggingMergeSetTag(
263     "stack-tagging-merge-settag",
264     cl::desc("merge settag instruction in function epilog"), cl::init(true),
265     cl::Hidden);
266 
267 static cl::opt<bool> OrderFrameObjects("aarch64-order-frame-objects",
268                                        cl::desc("sort stack allocations"),
269                                        cl::init(true), cl::Hidden);
270 
271 cl::opt<bool> EnableHomogeneousPrologEpilog(
272     "homogeneous-prolog-epilog", cl::Hidden,
273     cl::desc("Emit homogeneous prologue and epilogue for the size "
274              "optimization (default = off)"));
275 
276 // Stack hazard padding size. 0 = disabled.
277 static cl::opt<unsigned> StackHazardSize("aarch64-stack-hazard-size",
278                                          cl::init(0), cl::Hidden);
279 // Stack hazard size for analysis remarks. StackHazardSize takes precedence.
280 static cl::opt<unsigned>
281     StackHazardRemarkSize("aarch64-stack-hazard-remark-size", cl::init(0),
282                           cl::Hidden);
283 // Whether to insert padding into non-streaming functions (for testing).
284 static cl::opt<bool>
285     StackHazardInNonStreaming("aarch64-stack-hazard-in-non-streaming",
286                               cl::init(false), cl::Hidden);
287 
288 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
289 
290 /// Returns how much of the incoming argument stack area (in bytes) we should
291 /// clean up in an epilogue. For the C calling convention this will be 0, for
292 /// guaranteed tail call conventions it can be positive (a normal return or a
293 /// tail call to a function that uses less stack space for arguments) or
294 /// negative (for a tail call to a function that needs more stack space than us
295 /// for arguments).
296 static int64_t getArgumentStackToRestore(MachineFunction &MF,
297                                          MachineBasicBlock &MBB) {
298   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
299   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
300   bool IsTailCallReturn = (MBB.end() != MBBI)
301                               ? AArch64InstrInfo::isTailCallReturnInst(*MBBI)
302                               : false;
303 
304   int64_t ArgumentPopSize = 0;
305   if (IsTailCallReturn) {
306     MachineOperand &StackAdjust = MBBI->getOperand(1);
307 
308     // For a tail-call in a callee-pops-arguments environment, some or all of
309     // the stack may actually be in use for the call's arguments, this is
310     // calculated during LowerCall and consumed here...
311     ArgumentPopSize = StackAdjust.getImm();
312   } else {
313     // ... otherwise the amount to pop is *all* of the argument space,
314     // conveniently stored in the MachineFunctionInfo by
315     // LowerFormalArguments. This will, of course, be zero for the C calling
316     // convention.
317     ArgumentPopSize = AFI->getArgumentStackToRestore();
318   }
319 
320   return ArgumentPopSize;
321 }
322 
323 static bool produceCompactUnwindFrame(MachineFunction &MF);
324 static bool needsWinCFI(const MachineFunction &MF);
325 static StackOffset getSVEStackSize(const MachineFunction &MF);
326 static Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB);
327 
328 /// Returns true if a homogeneous prolog or epilog code can be emitted
329 /// for the size optimization. If possible, a frame helper call is injected.
330 /// When Exit block is given, this check is for epilog.
331 bool AArch64FrameLowering::homogeneousPrologEpilog(
332     MachineFunction &MF, MachineBasicBlock *Exit) const {
333   if (!MF.getFunction().hasMinSize())
334     return false;
335   if (!EnableHomogeneousPrologEpilog)
336     return false;
337   if (EnableRedZone)
338     return false;
339 
340   // TODO: Window is supported yet.
341   if (needsWinCFI(MF))
342     return false;
343   // TODO: SVE is not supported yet.
344   if (getSVEStackSize(MF))
345     return false;
346 
347   // Bail on stack adjustment needed on return for simplicity.
348   const MachineFrameInfo &MFI = MF.getFrameInfo();
349   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
350   if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF))
351     return false;
352   if (Exit && getArgumentStackToRestore(MF, *Exit))
353     return false;
354 
355   auto *AFI = MF.getInfo<AArch64FunctionInfo>();
356   if (AFI->hasSwiftAsyncContext() || AFI->hasStreamingModeChanges())
357     return false;
358 
359   // If there are an odd number of GPRs before LR and FP in the CSRs list,
360   // they will not be paired into one RegPairInfo, which is incompatible with
361   // the assumption made by the homogeneous prolog epilog pass.
362   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
363   unsigned NumGPRs = 0;
364   for (unsigned I = 0; CSRegs[I]; ++I) {
365     Register Reg = CSRegs[I];
366     if (Reg == AArch64::LR) {
367       assert(CSRegs[I + 1] == AArch64::FP);
368       if (NumGPRs % 2 != 0)
369         return false;
370       break;
371     }
372     if (AArch64::GPR64RegClass.contains(Reg))
373       ++NumGPRs;
374   }
375 
376   return true;
377 }
378 
379 /// Returns true if CSRs should be paired.
380 bool AArch64FrameLowering::producePairRegisters(MachineFunction &MF) const {
381   return produceCompactUnwindFrame(MF) || homogeneousPrologEpilog(MF);
382 }
383 
384 /// This is the biggest offset to the stack pointer we can encode in aarch64
385 /// instructions (without using a separate calculation and a temp register).
386 /// Note that the exception here are vector stores/loads which cannot encode any
387 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
388 static const unsigned DefaultSafeSPDisplacement = 255;
389 
390 /// Look at each instruction that references stack frames and return the stack
391 /// size limit beyond which some of these instructions will require a scratch
392 /// register during their expansion later.
393 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
394   // FIXME: For now, just conservatively guestimate based on unscaled indexing
395   // range. We'll end up allocating an unnecessary spill slot a lot, but
396   // realistically that's not a big deal at this stage of the game.
397   for (MachineBasicBlock &MBB : MF) {
398     for (MachineInstr &MI : MBB) {
399       if (MI.isDebugInstr() || MI.isPseudo() ||
400           MI.getOpcode() == AArch64::ADDXri ||
401           MI.getOpcode() == AArch64::ADDSXri)
402         continue;
403 
404       for (const MachineOperand &MO : MI.operands()) {
405         if (!MO.isFI())
406           continue;
407 
408         StackOffset Offset;
409         if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
410             AArch64FrameOffsetCannotUpdate)
411           return 0;
412       }
413     }
414   }
415   return DefaultSafeSPDisplacement;
416 }
417 
418 TargetStackID::Value
419 AArch64FrameLowering::getStackIDForScalableVectors() const {
420   return TargetStackID::ScalableVector;
421 }
422 
423 /// Returns the size of the fixed object area (allocated next to sp on entry)
424 /// On Win64 this may include a var args area and an UnwindHelp object for EH.
425 static unsigned getFixedObjectSize(const MachineFunction &MF,
426                                    const AArch64FunctionInfo *AFI, bool IsWin64,
427                                    bool IsFunclet) {
428   if (!IsWin64 || IsFunclet) {
429     return AFI->getTailCallReservedStack();
430   } else {
431     if (AFI->getTailCallReservedStack() != 0 &&
432         !MF.getFunction().getAttributes().hasAttrSomewhere(
433             Attribute::SwiftAsync))
434       report_fatal_error("cannot generate ABI-changing tail call for Win64");
435     // Var args are stored here in the primary function.
436     const unsigned VarArgsArea = AFI->getVarArgsGPRSize();
437     // To support EH funclets we allocate an UnwindHelp object
438     const unsigned UnwindHelpObject = (MF.hasEHFunclets() ? 8 : 0);
439     return AFI->getTailCallReservedStack() +
440            alignTo(VarArgsArea + UnwindHelpObject, 16);
441   }
442 }
443 
444 /// Returns the size of the entire SVE stackframe (calleesaves + spills).
445 static StackOffset getSVEStackSize(const MachineFunction &MF) {
446   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
447   return StackOffset::getScalable((int64_t)AFI->getStackSizeSVE());
448 }
449 
450 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
451   if (!EnableRedZone)
452     return false;
453 
454   // Don't use the red zone if the function explicitly asks us not to.
455   // This is typically used for kernel code.
456   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
457   const unsigned RedZoneSize =
458       Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
459   if (!RedZoneSize)
460     return false;
461 
462   const MachineFrameInfo &MFI = MF.getFrameInfo();
463   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
464   uint64_t NumBytes = AFI->getLocalStackSize();
465 
466   // If neither NEON or SVE are available, a COPY from one Q-reg to
467   // another requires a spill -> reload sequence. We can do that
468   // using a pre-decrementing store/post-decrementing load, but
469   // if we do so, we can't use the Red Zone.
470   bool LowerQRegCopyThroughMem = Subtarget.hasFPARMv8() &&
471                                  !Subtarget.isNeonAvailable() &&
472                                  !Subtarget.hasSVE();
473 
474   return !(MFI.hasCalls() || hasFP(MF) || NumBytes > RedZoneSize ||
475            getSVEStackSize(MF) || LowerQRegCopyThroughMem);
476 }
477 
478 /// hasFP - Return true if the specified function should have a dedicated frame
479 /// pointer register.
480 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
481   const MachineFrameInfo &MFI = MF.getFrameInfo();
482   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
483 
484   // Win64 EH requires a frame pointer if funclets are present, as the locals
485   // are accessed off the frame pointer in both the parent function and the
486   // funclets.
487   if (MF.hasEHFunclets())
488     return true;
489   // Retain behavior of always omitting the FP for leaf functions when possible.
490   if (MF.getTarget().Options.DisableFramePointerElim(MF))
491     return true;
492   if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
493       MFI.hasStackMap() || MFI.hasPatchPoint() ||
494       RegInfo->hasStackRealignment(MF))
495     return true;
496   // With large callframes around we may need to use FP to access the scavenging
497   // emergency spillslot.
498   //
499   // Unfortunately some calls to hasFP() like machine verifier ->
500   // getReservedReg() -> hasFP in the middle of global isel are too early
501   // to know the max call frame size. Hopefully conservatively returning "true"
502   // in those cases is fine.
503   // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
504   if (!MFI.isMaxCallFrameSizeComputed() ||
505       MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
506     return true;
507 
508   return false;
509 }
510 
511 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
512 /// not required, we reserve argument space for call sites in the function
513 /// immediately on entry to the current function.  This eliminates the need for
514 /// add/sub sp brackets around call sites.  Returns true if the call frame is
515 /// included as part of the stack frame.
516 bool AArch64FrameLowering::hasReservedCallFrame(
517     const MachineFunction &MF) const {
518   // The stack probing code for the dynamically allocated outgoing arguments
519   // area assumes that the stack is probed at the top - either by the prologue
520   // code, which issues a probe if `hasVarSizedObjects` return true, or by the
521   // most recent variable-sized object allocation. Changing the condition here
522   // may need to be followed up by changes to the probe issuing logic.
523   return !MF.getFrameInfo().hasVarSizedObjects();
524 }
525 
526 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
527     MachineFunction &MF, MachineBasicBlock &MBB,
528     MachineBasicBlock::iterator I) const {
529   const AArch64InstrInfo *TII =
530       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
531   const AArch64TargetLowering *TLI =
532       MF.getSubtarget<AArch64Subtarget>().getTargetLowering();
533   [[maybe_unused]] MachineFrameInfo &MFI = MF.getFrameInfo();
534   DebugLoc DL = I->getDebugLoc();
535   unsigned Opc = I->getOpcode();
536   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
537   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
538 
539   if (!hasReservedCallFrame(MF)) {
540     int64_t Amount = I->getOperand(0).getImm();
541     Amount = alignTo(Amount, getStackAlign());
542     if (!IsDestroy)
543       Amount = -Amount;
544 
545     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
546     // doesn't have to pop anything), then the first operand will be zero too so
547     // this adjustment is a no-op.
548     if (CalleePopAmount == 0) {
549       // FIXME: in-function stack adjustment for calls is limited to 24-bits
550       // because there's no guaranteed temporary register available.
551       //
552       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
553       // 1) For offset <= 12-bit, we use LSL #0
554       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
555       // LSL #0, and the other uses LSL #12.
556       //
557       // Most call frames will be allocated at the start of a function so
558       // this is OK, but it is a limitation that needs dealing with.
559       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
560 
561       if (TLI->hasInlineStackProbe(MF) &&
562           -Amount >= AArch64::StackProbeMaxUnprobedStack) {
563         // When stack probing is enabled, the decrement of SP may need to be
564         // probed. We only need to do this if the call site needs 1024 bytes of
565         // space or more, because a region smaller than that is allowed to be
566         // unprobed at an ABI boundary. We rely on the fact that SP has been
567         // probed exactly at this point, either by the prologue or most recent
568         // dynamic allocation.
569         assert(MFI.hasVarSizedObjects() &&
570                "non-reserved call frame without var sized objects?");
571         Register ScratchReg =
572             MF.getRegInfo().createVirtualRegister(&AArch64::GPR64RegClass);
573         inlineStackProbeFixed(I, ScratchReg, -Amount, StackOffset::get(0, 0));
574       } else {
575         emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
576                         StackOffset::getFixed(Amount), TII);
577       }
578     }
579   } else if (CalleePopAmount != 0) {
580     // If the calling convention demands that the callee pops arguments from the
581     // stack, we want to add it back if we have a reserved call frame.
582     assert(CalleePopAmount < 0xffffff && "call frame too large");
583     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
584                     StackOffset::getFixed(-(int64_t)CalleePopAmount), TII);
585   }
586   return MBB.erase(I);
587 }
588 
589 void AArch64FrameLowering::emitCalleeSavedGPRLocations(
590     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
591   MachineFunction &MF = *MBB.getParent();
592   MachineFrameInfo &MFI = MF.getFrameInfo();
593   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
594   SMEAttrs Attrs(MF.getFunction());
595   bool LocallyStreaming =
596       Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface();
597 
598   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
599   if (CSI.empty())
600     return;
601 
602   const TargetSubtargetInfo &STI = MF.getSubtarget();
603   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
604   const TargetInstrInfo &TII = *STI.getInstrInfo();
605   DebugLoc DL = MBB.findDebugLoc(MBBI);
606 
607   for (const auto &Info : CSI) {
608     unsigned FrameIdx = Info.getFrameIdx();
609     if (MFI.getStackID(FrameIdx) == TargetStackID::ScalableVector)
610       continue;
611 
612     assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");
613     int64_t DwarfReg = TRI.getDwarfRegNum(Info.getReg(), true);
614     int64_t Offset = MFI.getObjectOffset(FrameIdx) - getOffsetOfLocalArea();
615 
616     // The location of VG will be emitted before each streaming-mode change in
617     // the function. Only locally-streaming functions require emitting the
618     // non-streaming VG location here.
619     if ((LocallyStreaming && FrameIdx == AFI->getStreamingVGIdx()) ||
620         (!LocallyStreaming &&
621          DwarfReg == TRI.getDwarfRegNum(AArch64::VG, true)))
622       continue;
623 
624     unsigned CFIIndex = MF.addFrameInst(
625         MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
626     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
627         .addCFIIndex(CFIIndex)
628         .setMIFlags(MachineInstr::FrameSetup);
629   }
630 }
631 
632 void AArch64FrameLowering::emitCalleeSavedSVELocations(
633     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
634   MachineFunction &MF = *MBB.getParent();
635   MachineFrameInfo &MFI = MF.getFrameInfo();
636 
637   // Add callee saved registers to move list.
638   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
639   if (CSI.empty())
640     return;
641 
642   const TargetSubtargetInfo &STI = MF.getSubtarget();
643   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
644   const TargetInstrInfo &TII = *STI.getInstrInfo();
645   DebugLoc DL = MBB.findDebugLoc(MBBI);
646   AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
647 
648   for (const auto &Info : CSI) {
649     if (!(MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))
650       continue;
651 
652     // Not all unwinders may know about SVE registers, so assume the lowest
653     // common demoninator.
654     assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");
655     unsigned Reg = Info.getReg();
656     if (!static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))
657       continue;
658 
659     StackOffset Offset =
660         StackOffset::getScalable(MFI.getObjectOffset(Info.getFrameIdx())) -
661         StackOffset::getFixed(AFI.getCalleeSavedStackSize(MFI));
662 
663     unsigned CFIIndex = MF.addFrameInst(createCFAOffset(TRI, Reg, Offset));
664     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
665         .addCFIIndex(CFIIndex)
666         .setMIFlags(MachineInstr::FrameSetup);
667   }
668 }
669 
670 static void insertCFISameValue(const MCInstrDesc &Desc, MachineFunction &MF,
671                                MachineBasicBlock &MBB,
672                                MachineBasicBlock::iterator InsertPt,
673                                unsigned DwarfReg) {
674   unsigned CFIIndex =
675       MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, DwarfReg));
676   BuildMI(MBB, InsertPt, DebugLoc(), Desc).addCFIIndex(CFIIndex);
677 }
678 
679 void AArch64FrameLowering::resetCFIToInitialState(
680     MachineBasicBlock &MBB) const {
681 
682   MachineFunction &MF = *MBB.getParent();
683   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
684   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
685   const auto &TRI =
686       static_cast<const AArch64RegisterInfo &>(*Subtarget.getRegisterInfo());
687   const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();
688 
689   const MCInstrDesc &CFIDesc = TII.get(TargetOpcode::CFI_INSTRUCTION);
690   DebugLoc DL;
691 
692   // Reset the CFA to `SP + 0`.
693   MachineBasicBlock::iterator InsertPt = MBB.begin();
694   unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
695       nullptr, TRI.getDwarfRegNum(AArch64::SP, true), 0));
696   BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);
697 
698   // Flip the RA sign state.
699   if (MFI.shouldSignReturnAddress(MF)) {
700     CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
701     BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);
702   }
703 
704   // Shadow call stack uses X18, reset it.
705   if (MFI.needsShadowCallStackPrologueEpilogue(MF))
706     insertCFISameValue(CFIDesc, MF, MBB, InsertPt,
707                        TRI.getDwarfRegNum(AArch64::X18, true));
708 
709   // Emit .cfi_same_value for callee-saved registers.
710   const std::vector<CalleeSavedInfo> &CSI =
711       MF.getFrameInfo().getCalleeSavedInfo();
712   for (const auto &Info : CSI) {
713     unsigned Reg = Info.getReg();
714     if (!TRI.regNeedsCFI(Reg, Reg))
715       continue;
716     insertCFISameValue(CFIDesc, MF, MBB, InsertPt,
717                        TRI.getDwarfRegNum(Reg, true));
718   }
719 }
720 
721 static void emitCalleeSavedRestores(MachineBasicBlock &MBB,
722                                     MachineBasicBlock::iterator MBBI,
723                                     bool SVE) {
724   MachineFunction &MF = *MBB.getParent();
725   MachineFrameInfo &MFI = MF.getFrameInfo();
726 
727   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
728   if (CSI.empty())
729     return;
730 
731   const TargetSubtargetInfo &STI = MF.getSubtarget();
732   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
733   const TargetInstrInfo &TII = *STI.getInstrInfo();
734   DebugLoc DL = MBB.findDebugLoc(MBBI);
735 
736   for (const auto &Info : CSI) {
737     if (SVE !=
738         (MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))
739       continue;
740 
741     unsigned Reg = Info.getReg();
742     if (SVE &&
743         !static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))
744       continue;
745 
746     if (!Info.isRestored())
747       continue;
748 
749     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(
750         nullptr, TRI.getDwarfRegNum(Info.getReg(), true)));
751     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
752         .addCFIIndex(CFIIndex)
753         .setMIFlags(MachineInstr::FrameDestroy);
754   }
755 }
756 
757 void AArch64FrameLowering::emitCalleeSavedGPRRestores(
758     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
759   emitCalleeSavedRestores(MBB, MBBI, false);
760 }
761 
762 void AArch64FrameLowering::emitCalleeSavedSVERestores(
763     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
764   emitCalleeSavedRestores(MBB, MBBI, true);
765 }
766 
767 // Return the maximum possible number of bytes for `Size` due to the
768 // architectural limit on the size of a SVE register.
769 static int64_t upperBound(StackOffset Size) {
770   static const int64_t MAX_BYTES_PER_SCALABLE_BYTE = 16;
771   return Size.getScalable() * MAX_BYTES_PER_SCALABLE_BYTE + Size.getFixed();
772 }
773 
774 void AArch64FrameLowering::allocateStackSpace(
775     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
776     int64_t RealignmentPadding, StackOffset AllocSize, bool NeedsWinCFI,
777     bool *HasWinCFI, bool EmitCFI, StackOffset InitialOffset,
778     bool FollowupAllocs) const {
779 
780   if (!AllocSize)
781     return;
782 
783   DebugLoc DL;
784   MachineFunction &MF = *MBB.getParent();
785   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
786   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
787   AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
788   const MachineFrameInfo &MFI = MF.getFrameInfo();
789 
790   const int64_t MaxAlign = MFI.getMaxAlign().value();
791   const uint64_t AndMask = ~(MaxAlign - 1);
792 
793   if (!Subtarget.getTargetLowering()->hasInlineStackProbe(MF)) {
794     Register TargetReg = RealignmentPadding
795                              ? findScratchNonCalleeSaveRegister(&MBB)
796                              : AArch64::SP;
797     // SUB Xd/SP, SP, AllocSize
798     emitFrameOffset(MBB, MBBI, DL, TargetReg, AArch64::SP, -AllocSize, &TII,
799                     MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI,
800                     EmitCFI, InitialOffset);
801 
802     if (RealignmentPadding) {
803       // AND SP, X9, 0b11111...0000
804       BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), AArch64::SP)
805           .addReg(TargetReg, RegState::Kill)
806           .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64))
807           .setMIFlags(MachineInstr::FrameSetup);
808       AFI.setStackRealigned(true);
809 
810       // No need for SEH instructions here; if we're realigning the stack,
811       // we've set a frame pointer and already finished the SEH prologue.
812       assert(!NeedsWinCFI);
813     }
814     return;
815   }
816 
817   //
818   // Stack probing allocation.
819   //
820 
821   // Fixed length allocation. If we don't need to re-align the stack and don't
822   // have SVE objects, we can use a more efficient sequence for stack probing.
823   if (AllocSize.getScalable() == 0 && RealignmentPadding == 0) {
824     Register ScratchReg = findScratchNonCalleeSaveRegister(&MBB);
825     assert(ScratchReg != AArch64::NoRegister);
826     BuildMI(MBB, MBBI, DL, TII.get(AArch64::PROBED_STACKALLOC))
827         .addDef(ScratchReg)
828         .addImm(AllocSize.getFixed())
829         .addImm(InitialOffset.getFixed())
830         .addImm(InitialOffset.getScalable());
831     // The fixed allocation may leave unprobed bytes at the top of the
832     // stack. If we have subsequent alocation (e.g. if we have variable-sized
833     // objects), we need to issue an extra probe, so these allocations start in
834     // a known state.
835     if (FollowupAllocs) {
836       // STR XZR, [SP]
837       BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXui))
838           .addReg(AArch64::XZR)
839           .addReg(AArch64::SP)
840           .addImm(0)
841           .setMIFlags(MachineInstr::FrameSetup);
842     }
843 
844     return;
845   }
846 
847   // Variable length allocation.
848 
849   // If the (unknown) allocation size cannot exceed the probe size, decrement
850   // the stack pointer right away.
851   int64_t ProbeSize = AFI.getStackProbeSize();
852   if (upperBound(AllocSize) + RealignmentPadding <= ProbeSize) {
853     Register ScratchReg = RealignmentPadding
854                               ? findScratchNonCalleeSaveRegister(&MBB)
855                               : AArch64::SP;
856     assert(ScratchReg != AArch64::NoRegister);
857     // SUB Xd, SP, AllocSize
858     emitFrameOffset(MBB, MBBI, DL, ScratchReg, AArch64::SP, -AllocSize, &TII,
859                     MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI,
860                     EmitCFI, InitialOffset);
861     if (RealignmentPadding) {
862       // AND SP, Xn, 0b11111...0000
863       BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), AArch64::SP)
864           .addReg(ScratchReg, RegState::Kill)
865           .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64))
866           .setMIFlags(MachineInstr::FrameSetup);
867       AFI.setStackRealigned(true);
868     }
869     if (FollowupAllocs || upperBound(AllocSize) + RealignmentPadding >
870                               AArch64::StackProbeMaxUnprobedStack) {
871       // STR XZR, [SP]
872       BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXui))
873           .addReg(AArch64::XZR)
874           .addReg(AArch64::SP)
875           .addImm(0)
876           .setMIFlags(MachineInstr::FrameSetup);
877     }
878     return;
879   }
880 
881   // Emit a variable-length allocation probing loop.
882   // TODO: As an optimisation, the loop can be "unrolled" into a few parts,
883   // each of them guaranteed to adjust the stack by less than the probe size.
884   Register TargetReg = findScratchNonCalleeSaveRegister(&MBB);
885   assert(TargetReg != AArch64::NoRegister);
886   // SUB Xd, SP, AllocSize
887   emitFrameOffset(MBB, MBBI, DL, TargetReg, AArch64::SP, -AllocSize, &TII,
888                   MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI,
889                   EmitCFI, InitialOffset);
890   if (RealignmentPadding) {
891     // AND Xn, Xn, 0b11111...0000
892     BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), TargetReg)
893         .addReg(TargetReg, RegState::Kill)
894         .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64))
895         .setMIFlags(MachineInstr::FrameSetup);
896   }
897 
898   BuildMI(MBB, MBBI, DL, TII.get(AArch64::PROBED_STACKALLOC_VAR))
899       .addReg(TargetReg);
900   if (EmitCFI) {
901     // Set the CFA register back to SP.
902     unsigned Reg =
903         Subtarget.getRegisterInfo()->getDwarfRegNum(AArch64::SP, true);
904     unsigned CFIIndex =
905         MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
906     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
907         .addCFIIndex(CFIIndex)
908         .setMIFlags(MachineInstr::FrameSetup);
909   }
910   if (RealignmentPadding)
911     AFI.setStackRealigned(true);
912 }
913 
914 static MCRegister getRegisterOrZero(MCRegister Reg, bool HasSVE) {
915   switch (Reg.id()) {
916   default:
917     // The called routine is expected to preserve r19-r28
918     // r29 and r30 are used as frame pointer and link register resp.
919     return 0;
920 
921     // GPRs
922 #define CASE(n)                                                                \
923   case AArch64::W##n:                                                          \
924   case AArch64::X##n:                                                          \
925     return AArch64::X##n
926   CASE(0);
927   CASE(1);
928   CASE(2);
929   CASE(3);
930   CASE(4);
931   CASE(5);
932   CASE(6);
933   CASE(7);
934   CASE(8);
935   CASE(9);
936   CASE(10);
937   CASE(11);
938   CASE(12);
939   CASE(13);
940   CASE(14);
941   CASE(15);
942   CASE(16);
943   CASE(17);
944   CASE(18);
945 #undef CASE
946 
947     // FPRs
948 #define CASE(n)                                                                \
949   case AArch64::B##n:                                                          \
950   case AArch64::H##n:                                                          \
951   case AArch64::S##n:                                                          \
952   case AArch64::D##n:                                                          \
953   case AArch64::Q##n:                                                          \
954     return HasSVE ? AArch64::Z##n : AArch64::Q##n
955   CASE(0);
956   CASE(1);
957   CASE(2);
958   CASE(3);
959   CASE(4);
960   CASE(5);
961   CASE(6);
962   CASE(7);
963   CASE(8);
964   CASE(9);
965   CASE(10);
966   CASE(11);
967   CASE(12);
968   CASE(13);
969   CASE(14);
970   CASE(15);
971   CASE(16);
972   CASE(17);
973   CASE(18);
974   CASE(19);
975   CASE(20);
976   CASE(21);
977   CASE(22);
978   CASE(23);
979   CASE(24);
980   CASE(25);
981   CASE(26);
982   CASE(27);
983   CASE(28);
984   CASE(29);
985   CASE(30);
986   CASE(31);
987 #undef CASE
988   }
989 }
990 
991 void AArch64FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
992                                                 MachineBasicBlock &MBB) const {
993   // Insertion point.
994   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
995 
996   // Fake a debug loc.
997   DebugLoc DL;
998   if (MBBI != MBB.end())
999     DL = MBBI->getDebugLoc();
1000 
1001   const MachineFunction &MF = *MBB.getParent();
1002   const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
1003   const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
1004 
1005   BitVector GPRsToZero(TRI.getNumRegs());
1006   BitVector FPRsToZero(TRI.getNumRegs());
1007   bool HasSVE = STI.hasSVE();
1008   for (MCRegister Reg : RegsToZero.set_bits()) {
1009     if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1010       // For GPRs, we only care to clear out the 64-bit register.
1011       if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
1012         GPRsToZero.set(XReg);
1013     } else if (AArch64InstrInfo::isFpOrNEON(Reg)) {
1014       // For FPRs,
1015       if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
1016         FPRsToZero.set(XReg);
1017     }
1018   }
1019 
1020   const AArch64InstrInfo &TII = *STI.getInstrInfo();
1021 
1022   // Zero out GPRs.
1023   for (MCRegister Reg : GPRsToZero.set_bits())
1024     TII.buildClearRegister(Reg, MBB, MBBI, DL);
1025 
1026   // Zero out FP/vector registers.
1027   for (MCRegister Reg : FPRsToZero.set_bits())
1028     TII.buildClearRegister(Reg, MBB, MBBI, DL);
1029 
1030   if (HasSVE) {
1031     for (MCRegister PReg :
1032          {AArch64::P0, AArch64::P1, AArch64::P2, AArch64::P3, AArch64::P4,
1033           AArch64::P5, AArch64::P6, AArch64::P7, AArch64::P8, AArch64::P9,
1034           AArch64::P10, AArch64::P11, AArch64::P12, AArch64::P13, AArch64::P14,
1035           AArch64::P15}) {
1036       if (RegsToZero[PReg])
1037         BuildMI(MBB, MBBI, DL, TII.get(AArch64::PFALSE), PReg);
1038     }
1039   }
1040 }
1041 
1042 static void getLiveRegsForEntryMBB(LivePhysRegs &LiveRegs,
1043                                    const MachineBasicBlock &MBB) {
1044   const MachineFunction *MF = MBB.getParent();
1045   LiveRegs.addLiveIns(MBB);
1046   // Mark callee saved registers as used so we will not choose them.
1047   const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
1048   for (unsigned i = 0; CSRegs[i]; ++i)
1049     LiveRegs.addReg(CSRegs[i]);
1050 }
1051 
1052 // Find a scratch register that we can use at the start of the prologue to
1053 // re-align the stack pointer.  We avoid using callee-save registers since they
1054 // may appear to be free when this is called from canUseAsPrologue (during
1055 // shrink wrapping), but then no longer be free when this is called from
1056 // emitPrologue.
1057 //
1058 // FIXME: This is a bit conservative, since in the above case we could use one
1059 // of the callee-save registers as a scratch temp to re-align the stack pointer,
1060 // but we would then have to make sure that we were in fact saving at least one
1061 // callee-save register in the prologue, which is additional complexity that
1062 // doesn't seem worth the benefit.
1063 static Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
1064   MachineFunction *MF = MBB->getParent();
1065 
1066   // If MBB is an entry block, use X9 as the scratch register
1067   // preserve_none functions may be using X9 to pass arguments,
1068   // so prefer to pick an available register below.
1069   if (&MF->front() == MBB &&
1070       MF->getFunction().getCallingConv() != CallingConv::PreserveNone)
1071     return AArch64::X9;
1072 
1073   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
1074   const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
1075   LivePhysRegs LiveRegs(TRI);
1076   getLiveRegsForEntryMBB(LiveRegs, *MBB);
1077 
1078   // Prefer X9 since it was historically used for the prologue scratch reg.
1079   const MachineRegisterInfo &MRI = MF->getRegInfo();
1080   if (LiveRegs.available(MRI, AArch64::X9))
1081     return AArch64::X9;
1082 
1083   for (unsigned Reg : AArch64::GPR64RegClass) {
1084     if (LiveRegs.available(MRI, Reg))
1085       return Reg;
1086   }
1087   return AArch64::NoRegister;
1088 }
1089 
1090 bool AArch64FrameLowering::canUseAsPrologue(
1091     const MachineBasicBlock &MBB) const {
1092   const MachineFunction *MF = MBB.getParent();
1093   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1094   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
1095   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1096   const AArch64TargetLowering *TLI = Subtarget.getTargetLowering();
1097   const AArch64FunctionInfo *AFI = MF->getInfo<AArch64FunctionInfo>();
1098 
1099   if (AFI->hasSwiftAsyncContext()) {
1100     const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
1101     const MachineRegisterInfo &MRI = MF->getRegInfo();
1102     LivePhysRegs LiveRegs(TRI);
1103     getLiveRegsForEntryMBB(LiveRegs, MBB);
1104     // The StoreSwiftAsyncContext clobbers X16 and X17. Make sure they are
1105     // available.
1106     if (!LiveRegs.available(MRI, AArch64::X16) ||
1107         !LiveRegs.available(MRI, AArch64::X17))
1108       return false;
1109   }
1110 
1111   // Certain stack probing sequences might clobber flags, then we can't use
1112   // the block as a prologue if the flags register is a live-in.
1113   if (MF->getInfo<AArch64FunctionInfo>()->hasStackProbing() &&
1114       MBB.isLiveIn(AArch64::NZCV))
1115     return false;
1116 
1117   // Don't need a scratch register if we're not going to re-align the stack or
1118   // emit stack probes.
1119   if (!RegInfo->hasStackRealignment(*MF) && !TLI->hasInlineStackProbe(*MF))
1120     return true;
1121   // Otherwise, we can use any block as long as it has a scratch register
1122   // available.
1123   return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
1124 }
1125 
1126 static bool windowsRequiresStackProbe(MachineFunction &MF,
1127                                       uint64_t StackSizeInBytes) {
1128   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1129   const AArch64FunctionInfo &MFI = *MF.getInfo<AArch64FunctionInfo>();
1130   // TODO: When implementing stack protectors, take that into account
1131   // for the probe threshold.
1132   return Subtarget.isTargetWindows() && MFI.hasStackProbing() &&
1133          StackSizeInBytes >= uint64_t(MFI.getStackProbeSize());
1134 }
1135 
1136 static bool needsWinCFI(const MachineFunction &MF) {
1137   const Function &F = MF.getFunction();
1138   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
1139          F.needsUnwindTableEntry();
1140 }
1141 
1142 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
1143     MachineFunction &MF, uint64_t StackBumpBytes) const {
1144   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1145   const MachineFrameInfo &MFI = MF.getFrameInfo();
1146   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1147   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1148   if (homogeneousPrologEpilog(MF))
1149     return false;
1150 
1151   if (AFI->getLocalStackSize() == 0)
1152     return false;
1153 
1154   // For WinCFI, if optimizing for size, prefer to not combine the stack bump
1155   // (to force a stp with predecrement) to match the packed unwind format,
1156   // provided that there actually are any callee saved registers to merge the
1157   // decrement with.
1158   // This is potentially marginally slower, but allows using the packed
1159   // unwind format for functions that both have a local area and callee saved
1160   // registers. Using the packed unwind format notably reduces the size of
1161   // the unwind info.
1162   if (needsWinCFI(MF) && AFI->getCalleeSavedStackSize() > 0 &&
1163       MF.getFunction().hasOptSize())
1164     return false;
1165 
1166   // 512 is the maximum immediate for stp/ldp that will be used for
1167   // callee-save save/restores
1168   if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
1169     return false;
1170 
1171   if (MFI.hasVarSizedObjects())
1172     return false;
1173 
1174   if (RegInfo->hasStackRealignment(MF))
1175     return false;
1176 
1177   // This isn't strictly necessary, but it simplifies things a bit since the
1178   // current RedZone handling code assumes the SP is adjusted by the
1179   // callee-save save/restore code.
1180   if (canUseRedZone(MF))
1181     return false;
1182 
1183   // When there is an SVE area on the stack, always allocate the
1184   // callee-saves and spills/locals separately.
1185   if (getSVEStackSize(MF))
1186     return false;
1187 
1188   return true;
1189 }
1190 
1191 bool AArch64FrameLowering::shouldCombineCSRLocalStackBumpInEpilogue(
1192     MachineBasicBlock &MBB, unsigned StackBumpBytes) const {
1193   if (!shouldCombineCSRLocalStackBump(*MBB.getParent(), StackBumpBytes))
1194     return false;
1195 
1196   if (MBB.empty())
1197     return true;
1198 
1199   // Disable combined SP bump if the last instruction is an MTE tag store. It
1200   // is almost always better to merge SP adjustment into those instructions.
1201   MachineBasicBlock::iterator LastI = MBB.getFirstTerminator();
1202   MachineBasicBlock::iterator Begin = MBB.begin();
1203   while (LastI != Begin) {
1204     --LastI;
1205     if (LastI->isTransient())
1206       continue;
1207     if (!LastI->getFlag(MachineInstr::FrameDestroy))
1208       break;
1209   }
1210   switch (LastI->getOpcode()) {
1211   case AArch64::STGloop:
1212   case AArch64::STZGloop:
1213   case AArch64::STGi:
1214   case AArch64::STZGi:
1215   case AArch64::ST2Gi:
1216   case AArch64::STZ2Gi:
1217     return false;
1218   default:
1219     return true;
1220   }
1221   llvm_unreachable("unreachable");
1222 }
1223 
1224 // Given a load or a store instruction, generate an appropriate unwinding SEH
1225 // code on Windows.
1226 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,
1227                                              const TargetInstrInfo &TII,
1228                                              MachineInstr::MIFlag Flag) {
1229   unsigned Opc = MBBI->getOpcode();
1230   MachineBasicBlock *MBB = MBBI->getParent();
1231   MachineFunction &MF = *MBB->getParent();
1232   DebugLoc DL = MBBI->getDebugLoc();
1233   unsigned ImmIdx = MBBI->getNumOperands() - 1;
1234   int Imm = MBBI->getOperand(ImmIdx).getImm();
1235   MachineInstrBuilder MIB;
1236   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1237   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1238 
1239   switch (Opc) {
1240   default:
1241     llvm_unreachable("No SEH Opcode for this instruction");
1242   case AArch64::LDPDpost:
1243     Imm = -Imm;
1244     [[fallthrough]];
1245   case AArch64::STPDpre: {
1246     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1247     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
1248     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
1249               .addImm(Reg0)
1250               .addImm(Reg1)
1251               .addImm(Imm * 8)
1252               .setMIFlag(Flag);
1253     break;
1254   }
1255   case AArch64::LDPXpost:
1256     Imm = -Imm;
1257     [[fallthrough]];
1258   case AArch64::STPXpre: {
1259     Register Reg0 = MBBI->getOperand(1).getReg();
1260     Register Reg1 = MBBI->getOperand(2).getReg();
1261     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
1262       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
1263                 .addImm(Imm * 8)
1264                 .setMIFlag(Flag);
1265     else
1266       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
1267                 .addImm(RegInfo->getSEHRegNum(Reg0))
1268                 .addImm(RegInfo->getSEHRegNum(Reg1))
1269                 .addImm(Imm * 8)
1270                 .setMIFlag(Flag);
1271     break;
1272   }
1273   case AArch64::LDRDpost:
1274     Imm = -Imm;
1275     [[fallthrough]];
1276   case AArch64::STRDpre: {
1277     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1278     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
1279               .addImm(Reg)
1280               .addImm(Imm)
1281               .setMIFlag(Flag);
1282     break;
1283   }
1284   case AArch64::LDRXpost:
1285     Imm = -Imm;
1286     [[fallthrough]];
1287   case AArch64::STRXpre: {
1288     unsigned Reg =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1289     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
1290               .addImm(Reg)
1291               .addImm(Imm)
1292               .setMIFlag(Flag);
1293     break;
1294   }
1295   case AArch64::STPDi:
1296   case AArch64::LDPDi: {
1297     unsigned Reg0 =  RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1298     unsigned Reg1 =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1299     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
1300               .addImm(Reg0)
1301               .addImm(Reg1)
1302               .addImm(Imm * 8)
1303               .setMIFlag(Flag);
1304     break;
1305   }
1306   case AArch64::STPXi:
1307   case AArch64::LDPXi: {
1308     Register Reg0 = MBBI->getOperand(0).getReg();
1309     Register Reg1 = MBBI->getOperand(1).getReg();
1310     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
1311       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
1312                 .addImm(Imm * 8)
1313                 .setMIFlag(Flag);
1314     else
1315       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
1316                 .addImm(RegInfo->getSEHRegNum(Reg0))
1317                 .addImm(RegInfo->getSEHRegNum(Reg1))
1318                 .addImm(Imm * 8)
1319                 .setMIFlag(Flag);
1320     break;
1321   }
1322   case AArch64::STRXui:
1323   case AArch64::LDRXui: {
1324     int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1325     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
1326               .addImm(Reg)
1327               .addImm(Imm * 8)
1328               .setMIFlag(Flag);
1329     break;
1330   }
1331   case AArch64::STRDui:
1332   case AArch64::LDRDui: {
1333     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1334     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
1335               .addImm(Reg)
1336               .addImm(Imm * 8)
1337               .setMIFlag(Flag);
1338     break;
1339   }
1340   case AArch64::STPQi:
1341   case AArch64::LDPQi: {
1342     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1343     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1344     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQP))
1345               .addImm(Reg0)
1346               .addImm(Reg1)
1347               .addImm(Imm * 16)
1348               .setMIFlag(Flag);
1349     break;
1350   }
1351   case AArch64::LDPQpost:
1352     Imm = -Imm;
1353     [[fallthrough]];
1354   case AArch64::STPQpre: {
1355     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1356     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
1357     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQPX))
1358               .addImm(Reg0)
1359               .addImm(Reg1)
1360               .addImm(Imm * 16)
1361               .setMIFlag(Flag);
1362     break;
1363   }
1364   }
1365   auto I = MBB->insertAfter(MBBI, MIB);
1366   return I;
1367 }
1368 
1369 // Fix up the SEH opcode associated with the save/restore instruction.
1370 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,
1371                            unsigned LocalStackSize) {
1372   MachineOperand *ImmOpnd = nullptr;
1373   unsigned ImmIdx = MBBI->getNumOperands() - 1;
1374   switch (MBBI->getOpcode()) {
1375   default:
1376     llvm_unreachable("Fix the offset in the SEH instruction");
1377   case AArch64::SEH_SaveFPLR:
1378   case AArch64::SEH_SaveRegP:
1379   case AArch64::SEH_SaveReg:
1380   case AArch64::SEH_SaveFRegP:
1381   case AArch64::SEH_SaveFReg:
1382   case AArch64::SEH_SaveAnyRegQP:
1383   case AArch64::SEH_SaveAnyRegQPX:
1384     ImmOpnd = &MBBI->getOperand(ImmIdx);
1385     break;
1386   }
1387   if (ImmOpnd)
1388     ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);
1389 }
1390 
1391 bool requiresGetVGCall(MachineFunction &MF) {
1392   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1393   return AFI->hasStreamingModeChanges() &&
1394          !MF.getSubtarget<AArch64Subtarget>().hasSVE();
1395 }
1396 
1397 static bool requiresSaveVG(MachineFunction &MF) {
1398   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1399   // For Darwin platforms we don't save VG for non-SVE functions, even if SME
1400   // is enabled with streaming mode changes.
1401   if (!AFI->hasStreamingModeChanges())
1402     return false;
1403   auto &ST = MF.getSubtarget<AArch64Subtarget>();
1404   if (ST.isTargetDarwin())
1405     return ST.hasSVE();
1406   return true;
1407 }
1408 
1409 bool isVGInstruction(MachineBasicBlock::iterator MBBI) {
1410   unsigned Opc = MBBI->getOpcode();
1411   if (Opc == AArch64::CNTD_XPiI || Opc == AArch64::RDSVLI_XI ||
1412       Opc == AArch64::UBFMXri)
1413     return true;
1414 
1415   if (requiresGetVGCall(*MBBI->getMF())) {
1416     if (Opc == AArch64::ORRXrr)
1417       return true;
1418 
1419     if (Opc == AArch64::BL) {
1420       auto Op1 = MBBI->getOperand(0);
1421       return Op1.isSymbol() &&
1422              (StringRef(Op1.getSymbolName()) == "__arm_get_current_vg");
1423     }
1424   }
1425 
1426   return false;
1427 }
1428 
1429 // Convert callee-save register save/restore instruction to do stack pointer
1430 // decrement/increment to allocate/deallocate the callee-save stack area by
1431 // converting store/load to use pre/post increment version.
1432 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
1433     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
1434     const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,
1435     bool NeedsWinCFI, bool *HasWinCFI, bool EmitCFI,
1436     MachineInstr::MIFlag FrameFlag = MachineInstr::FrameSetup,
1437     int CFAOffset = 0) {
1438   unsigned NewOpc;
1439 
1440   // If the function contains streaming mode changes, we expect instructions
1441   // to calculate the value of VG before spilling. For locally-streaming
1442   // functions, we need to do this for both the streaming and non-streaming
1443   // vector length. Move past these instructions if necessary.
1444   MachineFunction &MF = *MBB.getParent();
1445   if (requiresSaveVG(MF))
1446     while (isVGInstruction(MBBI))
1447       ++MBBI;
1448 
1449   switch (MBBI->getOpcode()) {
1450   default:
1451     llvm_unreachable("Unexpected callee-save save/restore opcode!");
1452   case AArch64::STPXi:
1453     NewOpc = AArch64::STPXpre;
1454     break;
1455   case AArch64::STPDi:
1456     NewOpc = AArch64::STPDpre;
1457     break;
1458   case AArch64::STPQi:
1459     NewOpc = AArch64::STPQpre;
1460     break;
1461   case AArch64::STRXui:
1462     NewOpc = AArch64::STRXpre;
1463     break;
1464   case AArch64::STRDui:
1465     NewOpc = AArch64::STRDpre;
1466     break;
1467   case AArch64::STRQui:
1468     NewOpc = AArch64::STRQpre;
1469     break;
1470   case AArch64::LDPXi:
1471     NewOpc = AArch64::LDPXpost;
1472     break;
1473   case AArch64::LDPDi:
1474     NewOpc = AArch64::LDPDpost;
1475     break;
1476   case AArch64::LDPQi:
1477     NewOpc = AArch64::LDPQpost;
1478     break;
1479   case AArch64::LDRXui:
1480     NewOpc = AArch64::LDRXpost;
1481     break;
1482   case AArch64::LDRDui:
1483     NewOpc = AArch64::LDRDpost;
1484     break;
1485   case AArch64::LDRQui:
1486     NewOpc = AArch64::LDRQpost;
1487     break;
1488   }
1489   // Get rid of the SEH code associated with the old instruction.
1490   if (NeedsWinCFI) {
1491     auto SEH = std::next(MBBI);
1492     if (AArch64InstrInfo::isSEHInstruction(*SEH))
1493       SEH->eraseFromParent();
1494   }
1495 
1496   TypeSize Scale = TypeSize::getFixed(1), Width = TypeSize::getFixed(0);
1497   int64_t MinOffset, MaxOffset;
1498   bool Success = static_cast<const AArch64InstrInfo *>(TII)->getMemOpInfo(
1499       NewOpc, Scale, Width, MinOffset, MaxOffset);
1500   (void)Success;
1501   assert(Success && "unknown load/store opcode");
1502 
1503   // If the first store isn't right where we want SP then we can't fold the
1504   // update in so create a normal arithmetic instruction instead.
1505   if (MBBI->getOperand(MBBI->getNumOperands() - 1).getImm() != 0 ||
1506       CSStackSizeInc < MinOffset || CSStackSizeInc > MaxOffset) {
1507     // If we are destroying the frame, make sure we add the increment after the
1508     // last frame operation.
1509     if (FrameFlag == MachineInstr::FrameDestroy)
1510       ++MBBI;
1511     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1512                     StackOffset::getFixed(CSStackSizeInc), TII, FrameFlag,
1513                     false, false, nullptr, EmitCFI,
1514                     StackOffset::getFixed(CFAOffset));
1515 
1516     return std::prev(MBBI);
1517   }
1518 
1519   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1520   MIB.addReg(AArch64::SP, RegState::Define);
1521 
1522   // Copy all operands other than the immediate offset.
1523   unsigned OpndIdx = 0;
1524   for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
1525        ++OpndIdx)
1526     MIB.add(MBBI->getOperand(OpndIdx));
1527 
1528   assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
1529          "Unexpected immediate offset in first/last callee-save save/restore "
1530          "instruction!");
1531   assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
1532          "Unexpected base register in callee-save save/restore instruction!");
1533   assert(CSStackSizeInc % Scale == 0);
1534   MIB.addImm(CSStackSizeInc / (int)Scale);
1535 
1536   MIB.setMIFlags(MBBI->getFlags());
1537   MIB.setMemRefs(MBBI->memoperands());
1538 
1539   // Generate a new SEH code that corresponds to the new instruction.
1540   if (NeedsWinCFI) {
1541     *HasWinCFI = true;
1542     InsertSEH(*MIB, *TII, FrameFlag);
1543   }
1544 
1545   if (EmitCFI) {
1546     unsigned CFIIndex = MF.addFrameInst(
1547         MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset - CSStackSizeInc));
1548     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1549         .addCFIIndex(CFIIndex)
1550         .setMIFlags(FrameFlag);
1551   }
1552 
1553   return std::prev(MBB.erase(MBBI));
1554 }
1555 
1556 // Fixup callee-save register save/restore instructions to take into account
1557 // combined SP bump by adding the local stack size to the stack offsets.
1558 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
1559                                               uint64_t LocalStackSize,
1560                                               bool NeedsWinCFI,
1561                                               bool *HasWinCFI) {
1562   if (AArch64InstrInfo::isSEHInstruction(MI))
1563     return;
1564 
1565   unsigned Opc = MI.getOpcode();
1566   unsigned Scale;
1567   switch (Opc) {
1568   case AArch64::STPXi:
1569   case AArch64::STRXui:
1570   case AArch64::STPDi:
1571   case AArch64::STRDui:
1572   case AArch64::LDPXi:
1573   case AArch64::LDRXui:
1574   case AArch64::LDPDi:
1575   case AArch64::LDRDui:
1576     Scale = 8;
1577     break;
1578   case AArch64::STPQi:
1579   case AArch64::STRQui:
1580   case AArch64::LDPQi:
1581   case AArch64::LDRQui:
1582     Scale = 16;
1583     break;
1584   default:
1585     llvm_unreachable("Unexpected callee-save save/restore opcode!");
1586   }
1587 
1588   unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
1589   assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
1590          "Unexpected base register in callee-save save/restore instruction!");
1591   // Last operand is immediate offset that needs fixing.
1592   MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
1593   // All generated opcodes have scaled offsets.
1594   assert(LocalStackSize % Scale == 0);
1595   OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
1596 
1597   if (NeedsWinCFI) {
1598     *HasWinCFI = true;
1599     auto MBBI = std::next(MachineBasicBlock::iterator(MI));
1600     assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");
1601     assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&
1602            "Expecting a SEH instruction");
1603     fixupSEHOpcode(MBBI, LocalStackSize);
1604   }
1605 }
1606 
1607 static bool isTargetWindows(const MachineFunction &MF) {
1608   return MF.getSubtarget<AArch64Subtarget>().isTargetWindows();
1609 }
1610 
1611 // Convenience function to determine whether I is an SVE callee save.
1612 static bool IsSVECalleeSave(MachineBasicBlock::iterator I) {
1613   switch (I->getOpcode()) {
1614   default:
1615     return false;
1616   case AArch64::PTRUE_C_B:
1617   case AArch64::LD1B_2Z_IMM:
1618   case AArch64::ST1B_2Z_IMM:
1619   case AArch64::STR_ZXI:
1620   case AArch64::STR_PXI:
1621   case AArch64::LDR_ZXI:
1622   case AArch64::LDR_PXI:
1623     return I->getFlag(MachineInstr::FrameSetup) ||
1624            I->getFlag(MachineInstr::FrameDestroy);
1625   }
1626 }
1627 
1628 static void emitShadowCallStackPrologue(const TargetInstrInfo &TII,
1629                                         MachineFunction &MF,
1630                                         MachineBasicBlock &MBB,
1631                                         MachineBasicBlock::iterator MBBI,
1632                                         const DebugLoc &DL, bool NeedsWinCFI,
1633                                         bool NeedsUnwindInfo) {
1634   // Shadow call stack prolog: str x30, [x18], #8
1635   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXpost))
1636       .addReg(AArch64::X18, RegState::Define)
1637       .addReg(AArch64::LR)
1638       .addReg(AArch64::X18)
1639       .addImm(8)
1640       .setMIFlag(MachineInstr::FrameSetup);
1641 
1642   // This instruction also makes x18 live-in to the entry block.
1643   MBB.addLiveIn(AArch64::X18);
1644 
1645   if (NeedsWinCFI)
1646     BuildMI(MBB, MBBI, DL, TII.get(AArch64::SEH_Nop))
1647         .setMIFlag(MachineInstr::FrameSetup);
1648 
1649   if (NeedsUnwindInfo) {
1650     // Emit a CFI instruction that causes 8 to be subtracted from the value of
1651     // x18 when unwinding past this frame.
1652     static const char CFIInst[] = {
1653         dwarf::DW_CFA_val_expression,
1654         18, // register
1655         2,  // length
1656         static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
1657         static_cast<char>(-8) & 0x7f, // addend (sleb128)
1658     };
1659     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
1660         nullptr, StringRef(CFIInst, sizeof(CFIInst))));
1661     BuildMI(MBB, MBBI, DL, TII.get(AArch64::CFI_INSTRUCTION))
1662         .addCFIIndex(CFIIndex)
1663         .setMIFlag(MachineInstr::FrameSetup);
1664   }
1665 }
1666 
1667 static void emitShadowCallStackEpilogue(const TargetInstrInfo &TII,
1668                                         MachineFunction &MF,
1669                                         MachineBasicBlock &MBB,
1670                                         MachineBasicBlock::iterator MBBI,
1671                                         const DebugLoc &DL) {
1672   // Shadow call stack epilog: ldr x30, [x18, #-8]!
1673   BuildMI(MBB, MBBI, DL, TII.get(AArch64::LDRXpre))
1674       .addReg(AArch64::X18, RegState::Define)
1675       .addReg(AArch64::LR, RegState::Define)
1676       .addReg(AArch64::X18)
1677       .addImm(-8)
1678       .setMIFlag(MachineInstr::FrameDestroy);
1679 
1680   if (MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF)) {
1681     unsigned CFIIndex =
1682         MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, 18));
1683     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1684         .addCFIIndex(CFIIndex)
1685         .setMIFlags(MachineInstr::FrameDestroy);
1686   }
1687 }
1688 
1689 // Define the current CFA rule to use the provided FP.
1690 static void emitDefineCFAWithFP(MachineFunction &MF, MachineBasicBlock &MBB,
1691                                 MachineBasicBlock::iterator MBBI,
1692                                 const DebugLoc &DL, unsigned FixedObject) {
1693   const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
1694   const AArch64RegisterInfo *TRI = STI.getRegisterInfo();
1695   const TargetInstrInfo *TII = STI.getInstrInfo();
1696   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1697 
1698   const int OffsetToFirstCalleeSaveFromFP =
1699       AFI->getCalleeSaveBaseToFrameRecordOffset() -
1700       AFI->getCalleeSavedStackSize();
1701   Register FramePtr = TRI->getFrameRegister(MF);
1702   unsigned Reg = TRI->getDwarfRegNum(FramePtr, true);
1703   unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
1704       nullptr, Reg, FixedObject - OffsetToFirstCalleeSaveFromFP));
1705   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1706       .addCFIIndex(CFIIndex)
1707       .setMIFlags(MachineInstr::FrameSetup);
1708 }
1709 
1710 #ifndef NDEBUG
1711 /// Collect live registers from the end of \p MI's parent up to (including) \p
1712 /// MI in \p LiveRegs.
1713 static void getLivePhysRegsUpTo(MachineInstr &MI, const TargetRegisterInfo &TRI,
1714                                 LivePhysRegs &LiveRegs) {
1715 
1716   MachineBasicBlock &MBB = *MI.getParent();
1717   LiveRegs.addLiveOuts(MBB);
1718   for (const MachineInstr &MI :
1719        reverse(make_range(MI.getIterator(), MBB.instr_end())))
1720     LiveRegs.stepBackward(MI);
1721 }
1722 #endif
1723 
1724 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
1725                                         MachineBasicBlock &MBB) const {
1726   MachineBasicBlock::iterator MBBI = MBB.begin();
1727   const MachineFrameInfo &MFI = MF.getFrameInfo();
1728   const Function &F = MF.getFunction();
1729   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1730   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1731   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1732 
1733   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1734   bool EmitCFI = AFI->needsDwarfUnwindInfo(MF);
1735   bool EmitAsyncCFI = AFI->needsAsyncDwarfUnwindInfo(MF);
1736   bool HasFP = hasFP(MF);
1737   bool NeedsWinCFI = needsWinCFI(MF);
1738   bool HasWinCFI = false;
1739   auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); });
1740 
1741   MachineBasicBlock::iterator End = MBB.end();
1742 #ifndef NDEBUG
1743   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1744   // Collect live register from the end of MBB up to the start of the existing
1745   // frame setup instructions.
1746   MachineBasicBlock::iterator NonFrameStart = MBB.begin();
1747   while (NonFrameStart != End &&
1748          NonFrameStart->getFlag(MachineInstr::FrameSetup))
1749     ++NonFrameStart;
1750 
1751   LivePhysRegs LiveRegs(*TRI);
1752   if (NonFrameStart != MBB.end()) {
1753     getLivePhysRegsUpTo(*NonFrameStart, *TRI, LiveRegs);
1754     // Ignore registers used for stack management for now.
1755     LiveRegs.removeReg(AArch64::SP);
1756     LiveRegs.removeReg(AArch64::X19);
1757     LiveRegs.removeReg(AArch64::FP);
1758     LiveRegs.removeReg(AArch64::LR);
1759 
1760     // X0 will be clobbered by a call to __arm_get_current_vg in the prologue.
1761     // This is necessary to spill VG if required where SVE is unavailable, but
1762     // X0 is preserved around this call.
1763     if (requiresGetVGCall(MF))
1764       LiveRegs.removeReg(AArch64::X0);
1765   }
1766 
1767   auto VerifyClobberOnExit = make_scope_exit([&]() {
1768     if (NonFrameStart == MBB.end())
1769       return;
1770     // Check if any of the newly instructions clobber any of the live registers.
1771     for (MachineInstr &MI :
1772          make_range(MBB.instr_begin(), NonFrameStart->getIterator())) {
1773       for (auto &Op : MI.operands())
1774         if (Op.isReg() && Op.isDef())
1775           assert(!LiveRegs.contains(Op.getReg()) &&
1776                  "live register clobbered by inserted prologue instructions");
1777     }
1778   });
1779 #endif
1780 
1781   bool IsFunclet = MBB.isEHFuncletEntry();
1782 
1783   // At this point, we're going to decide whether or not the function uses a
1784   // redzone. In most cases, the function doesn't have a redzone so let's
1785   // assume that's false and set it to true in the case that there's a redzone.
1786   AFI->setHasRedZone(false);
1787 
1788   // Debug location must be unknown since the first debug location is used
1789   // to determine the end of the prologue.
1790   DebugLoc DL;
1791 
1792   const auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();
1793   if (MFnI.needsShadowCallStackPrologueEpilogue(MF))
1794     emitShadowCallStackPrologue(*TII, MF, MBB, MBBI, DL, NeedsWinCFI,
1795                                 MFnI.needsDwarfUnwindInfo(MF));
1796 
1797   if (MFnI.shouldSignReturnAddress(MF)) {
1798     BuildMI(MBB, MBBI, DL, TII->get(AArch64::PAUTH_PROLOGUE))
1799         .setMIFlag(MachineInstr::FrameSetup);
1800     if (NeedsWinCFI)
1801       HasWinCFI = true; // AArch64PointerAuth pass will insert SEH_PACSignLR
1802   }
1803 
1804   if (EmitCFI && MFnI.isMTETagged()) {
1805     BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITMTETAGGED))
1806         .setMIFlag(MachineInstr::FrameSetup);
1807   }
1808 
1809   // We signal the presence of a Swift extended frame to external tools by
1810   // storing FP with 0b0001 in bits 63:60. In normal userland operation a simple
1811   // ORR is sufficient, it is assumed a Swift kernel would initialize the TBI
1812   // bits so that is still true.
1813   if (HasFP && AFI->hasSwiftAsyncContext()) {
1814     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
1815     case SwiftAsyncFramePointerMode::DeploymentBased:
1816       if (Subtarget.swiftAsyncContextIsDynamicallySet()) {
1817         // The special symbol below is absolute and has a *value* that can be
1818         // combined with the frame pointer to signal an extended frame.
1819         BuildMI(MBB, MBBI, DL, TII->get(AArch64::LOADgot), AArch64::X16)
1820             .addExternalSymbol("swift_async_extendedFramePointerFlags",
1821                                AArch64II::MO_GOT);
1822         if (NeedsWinCFI) {
1823           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1824               .setMIFlags(MachineInstr::FrameSetup);
1825           HasWinCFI = true;
1826         }
1827         BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::FP)
1828             .addUse(AArch64::FP)
1829             .addUse(AArch64::X16)
1830             .addImm(Subtarget.isTargetILP32() ? 32 : 0);
1831         if (NeedsWinCFI) {
1832           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1833               .setMIFlags(MachineInstr::FrameSetup);
1834           HasWinCFI = true;
1835         }
1836         break;
1837       }
1838       [[fallthrough]];
1839 
1840     case SwiftAsyncFramePointerMode::Always:
1841       // ORR x29, x29, #0x1000_0000_0000_0000
1842       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXri), AArch64::FP)
1843           .addUse(AArch64::FP)
1844           .addImm(0x1100)
1845           .setMIFlag(MachineInstr::FrameSetup);
1846       if (NeedsWinCFI) {
1847         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1848             .setMIFlags(MachineInstr::FrameSetup);
1849         HasWinCFI = true;
1850       }
1851       break;
1852 
1853     case SwiftAsyncFramePointerMode::Never:
1854       break;
1855     }
1856   }
1857 
1858   // All calls are tail calls in GHC calling conv, and functions have no
1859   // prologue/epilogue.
1860   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1861     return;
1862 
1863   // Set tagged base pointer to the requested stack slot.
1864   // Ideally it should match SP value after prologue.
1865   std::optional<int> TBPI = AFI->getTaggedBasePointerIndex();
1866   if (TBPI)
1867     AFI->setTaggedBasePointerOffset(-MFI.getObjectOffset(*TBPI));
1868   else
1869     AFI->setTaggedBasePointerOffset(MFI.getStackSize());
1870 
1871   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1872 
1873   // getStackSize() includes all the locals in its size calculation. We don't
1874   // include these locals when computing the stack size of a funclet, as they
1875   // are allocated in the parent's stack frame and accessed via the frame
1876   // pointer from the funclet.  We only save the callee saved registers in the
1877   // funclet, which are really the callee saved registers of the parent
1878   // function, including the funclet.
1879   int64_t NumBytes =
1880       IsFunclet ? getWinEHFuncletFrameSize(MF) : MFI.getStackSize();
1881   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
1882     assert(!HasFP && "unexpected function without stack frame but with FP");
1883     assert(!SVEStackSize &&
1884            "unexpected function without stack frame but with SVE objects");
1885     // All of the stack allocation is for locals.
1886     AFI->setLocalStackSize(NumBytes);
1887     if (!NumBytes)
1888       return;
1889     // REDZONE: If the stack size is less than 128 bytes, we don't need
1890     // to actually allocate.
1891     if (canUseRedZone(MF)) {
1892       AFI->setHasRedZone(true);
1893       ++NumRedZoneFunctions;
1894     } else {
1895       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1896                       StackOffset::getFixed(-NumBytes), TII,
1897                       MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
1898       if (EmitCFI) {
1899         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
1900         MCSymbol *FrameLabel = MF.getContext().createTempSymbol();
1901         // Encode the stack size of the leaf function.
1902         unsigned CFIIndex = MF.addFrameInst(
1903             MCCFIInstruction::cfiDefCfaOffset(FrameLabel, NumBytes));
1904         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1905             .addCFIIndex(CFIIndex)
1906             .setMIFlags(MachineInstr::FrameSetup);
1907       }
1908     }
1909 
1910     if (NeedsWinCFI) {
1911       HasWinCFI = true;
1912       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1913           .setMIFlag(MachineInstr::FrameSetup);
1914     }
1915 
1916     return;
1917   }
1918 
1919   bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv(), F.isVarArg());
1920   unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
1921 
1922   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1923   // All of the remaining stack allocations are for locals.
1924   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1925   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1926   bool HomPrologEpilog = homogeneousPrologEpilog(MF);
1927   if (CombineSPBump) {
1928     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
1929     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1930                     StackOffset::getFixed(-NumBytes), TII,
1931                     MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI,
1932                     EmitAsyncCFI);
1933     NumBytes = 0;
1934   } else if (HomPrologEpilog) {
1935     // Stack has been already adjusted.
1936     NumBytes -= PrologueSaveSize;
1937   } else if (PrologueSaveSize != 0) {
1938     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
1939         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI,
1940         EmitAsyncCFI);
1941     NumBytes -= PrologueSaveSize;
1942   }
1943   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1944 
1945   // Move past the saves of the callee-saved registers, fixing up the offsets
1946   // and pre-inc if we decided to combine the callee-save and local stack
1947   // pointer bump above.
1948   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) &&
1949          !IsSVECalleeSave(MBBI)) {
1950     if (CombineSPBump &&
1951         // Only fix-up frame-setup load/store instructions.
1952         (!requiresSaveVG(MF) || !isVGInstruction(MBBI)))
1953       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
1954                                         NeedsWinCFI, &HasWinCFI);
1955     ++MBBI;
1956   }
1957 
1958   // For funclets the FP belongs to the containing function.
1959   if (!IsFunclet && HasFP) {
1960     // Only set up FP if we actually need to.
1961     int64_t FPOffset = AFI->getCalleeSaveBaseToFrameRecordOffset();
1962 
1963     if (CombineSPBump)
1964       FPOffset += AFI->getLocalStackSize();
1965 
1966     if (AFI->hasSwiftAsyncContext()) {
1967       // Before we update the live FP we have to ensure there's a valid (or
1968       // null) asynchronous context in its slot just before FP in the frame
1969       // record, so store it now.
1970       const auto &Attrs = MF.getFunction().getAttributes();
1971       bool HaveInitialContext = Attrs.hasAttrSomewhere(Attribute::SwiftAsync);
1972       if (HaveInitialContext)
1973         MBB.addLiveIn(AArch64::X22);
1974       Register Reg = HaveInitialContext ? AArch64::X22 : AArch64::XZR;
1975       BuildMI(MBB, MBBI, DL, TII->get(AArch64::StoreSwiftAsyncContext))
1976           .addUse(Reg)
1977           .addUse(AArch64::SP)
1978           .addImm(FPOffset - 8)
1979           .setMIFlags(MachineInstr::FrameSetup);
1980       if (NeedsWinCFI) {
1981         // WinCFI and arm64e, where StoreSwiftAsyncContext is expanded
1982         // to multiple instructions, should be mutually-exclusive.
1983         assert(Subtarget.getTargetTriple().getArchName() != "arm64e");
1984         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1985             .setMIFlags(MachineInstr::FrameSetup);
1986         HasWinCFI = true;
1987       }
1988     }
1989 
1990     if (HomPrologEpilog) {
1991       auto Prolog = MBBI;
1992       --Prolog;
1993       assert(Prolog->getOpcode() == AArch64::HOM_Prolog);
1994       Prolog->addOperand(MachineOperand::CreateImm(FPOffset));
1995     } else {
1996       // Issue    sub fp, sp, FPOffset or
1997       //          mov fp,sp          when FPOffset is zero.
1998       // Note: All stores of callee-saved registers are marked as "FrameSetup".
1999       // This code marks the instruction(s) that set the FP also.
2000       emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP,
2001                       StackOffset::getFixed(FPOffset), TII,
2002                       MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
2003       if (NeedsWinCFI && HasWinCFI) {
2004         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
2005             .setMIFlag(MachineInstr::FrameSetup);
2006         // After setting up the FP, the rest of the prolog doesn't need to be
2007         // included in the SEH unwind info.
2008         NeedsWinCFI = false;
2009       }
2010     }
2011     if (EmitAsyncCFI)
2012       emitDefineCFAWithFP(MF, MBB, MBBI, DL, FixedObject);
2013   }
2014 
2015   // Now emit the moves for whatever callee saved regs we have (including FP,
2016   // LR if those are saved). Frame instructions for SVE register are emitted
2017   // later, after the instruction which actually save SVE regs.
2018   if (EmitAsyncCFI)
2019     emitCalleeSavedGPRLocations(MBB, MBBI);
2020 
2021   // Alignment is required for the parent frame, not the funclet
2022   const bool NeedsRealignment =
2023       NumBytes && !IsFunclet && RegInfo->hasStackRealignment(MF);
2024   const int64_t RealignmentPadding =
2025       (NeedsRealignment && MFI.getMaxAlign() > Align(16))
2026           ? MFI.getMaxAlign().value() - 16
2027           : 0;
2028 
2029   if (windowsRequiresStackProbe(MF, NumBytes + RealignmentPadding)) {
2030     uint64_t NumWords = (NumBytes + RealignmentPadding) >> 4;
2031     if (NeedsWinCFI) {
2032       HasWinCFI = true;
2033       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
2034       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
2035       // This is at most two instructions, MOVZ follwed by MOVK.
2036       // TODO: Fix to use multiple stack alloc unwind codes for stacks
2037       // exceeding 256MB in size.
2038       if (NumBytes >= (1 << 28))
2039         report_fatal_error("Stack size cannot exceed 256MB for stack "
2040                            "unwinding purposes");
2041 
2042       uint32_t LowNumWords = NumWords & 0xFFFF;
2043       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
2044           .addImm(LowNumWords)
2045           .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
2046           .setMIFlag(MachineInstr::FrameSetup);
2047       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
2048           .setMIFlag(MachineInstr::FrameSetup);
2049       if ((NumWords & 0xFFFF0000) != 0) {
2050         BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
2051             .addReg(AArch64::X15)
2052             .addImm((NumWords & 0xFFFF0000) >> 16) // High half
2053             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
2054             .setMIFlag(MachineInstr::FrameSetup);
2055         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
2056             .setMIFlag(MachineInstr::FrameSetup);
2057       }
2058     } else {
2059       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
2060           .addImm(NumWords)
2061           .setMIFlags(MachineInstr::FrameSetup);
2062     }
2063 
2064     const char *ChkStk = Subtarget.getChkStkName();
2065     switch (MF.getTarget().getCodeModel()) {
2066     case CodeModel::Tiny:
2067     case CodeModel::Small:
2068     case CodeModel::Medium:
2069     case CodeModel::Kernel:
2070       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
2071           .addExternalSymbol(ChkStk)
2072           .addReg(AArch64::X15, RegState::Implicit)
2073           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
2074           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
2075           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
2076           .setMIFlags(MachineInstr::FrameSetup);
2077       if (NeedsWinCFI) {
2078         HasWinCFI = true;
2079         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
2080             .setMIFlag(MachineInstr::FrameSetup);
2081       }
2082       break;
2083     case CodeModel::Large:
2084       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
2085           .addReg(AArch64::X16, RegState::Define)
2086           .addExternalSymbol(ChkStk)
2087           .addExternalSymbol(ChkStk)
2088           .setMIFlags(MachineInstr::FrameSetup);
2089       if (NeedsWinCFI) {
2090         HasWinCFI = true;
2091         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
2092             .setMIFlag(MachineInstr::FrameSetup);
2093       }
2094 
2095       BuildMI(MBB, MBBI, DL, TII->get(getBLRCallOpcode(MF)))
2096           .addReg(AArch64::X16, RegState::Kill)
2097           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
2098           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
2099           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
2100           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
2101           .setMIFlags(MachineInstr::FrameSetup);
2102       if (NeedsWinCFI) {
2103         HasWinCFI = true;
2104         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
2105             .setMIFlag(MachineInstr::FrameSetup);
2106       }
2107       break;
2108     }
2109 
2110     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
2111         .addReg(AArch64::SP, RegState::Kill)
2112         .addReg(AArch64::X15, RegState::Kill)
2113         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
2114         .setMIFlags(MachineInstr::FrameSetup);
2115     if (NeedsWinCFI) {
2116       HasWinCFI = true;
2117       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
2118           .addImm(NumBytes)
2119           .setMIFlag(MachineInstr::FrameSetup);
2120     }
2121     NumBytes = 0;
2122 
2123     if (RealignmentPadding > 0) {
2124       if (RealignmentPadding >= 4096) {
2125         BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm))
2126             .addReg(AArch64::X16, RegState::Define)
2127             .addImm(RealignmentPadding)
2128             .setMIFlags(MachineInstr::FrameSetup);
2129         BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDXrx64), AArch64::X15)
2130             .addReg(AArch64::SP)
2131             .addReg(AArch64::X16, RegState::Kill)
2132             .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 0))
2133             .setMIFlag(MachineInstr::FrameSetup);
2134       } else {
2135         BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDXri), AArch64::X15)
2136             .addReg(AArch64::SP)
2137             .addImm(RealignmentPadding)
2138             .addImm(0)
2139             .setMIFlag(MachineInstr::FrameSetup);
2140       }
2141 
2142       uint64_t AndMask = ~(MFI.getMaxAlign().value() - 1);
2143       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
2144           .addReg(AArch64::X15, RegState::Kill)
2145           .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64));
2146       AFI->setStackRealigned(true);
2147 
2148       // No need for SEH instructions here; if we're realigning the stack,
2149       // we've set a frame pointer and already finished the SEH prologue.
2150       assert(!NeedsWinCFI);
2151     }
2152   }
2153 
2154   StackOffset SVECalleeSavesSize = {}, SVELocalsSize = SVEStackSize;
2155   MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;
2156 
2157   // Process the SVE callee-saves to determine what space needs to be
2158   // allocated.
2159   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
2160     LLVM_DEBUG(dbgs() << "SVECalleeSavedStackSize = " << CalleeSavedSize
2161                       << "\n");
2162     // Find callee save instructions in frame.
2163     CalleeSavesBegin = MBBI;
2164     assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");
2165     while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())
2166       ++MBBI;
2167     CalleeSavesEnd = MBBI;
2168 
2169     SVECalleeSavesSize = StackOffset::getScalable(CalleeSavedSize);
2170     SVELocalsSize = SVEStackSize - SVECalleeSavesSize;
2171   }
2172 
2173   // Allocate space for the callee saves (if any).
2174   StackOffset CFAOffset =
2175       StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes);
2176   StackOffset LocalsSize = SVELocalsSize + StackOffset::getFixed(NumBytes);
2177   allocateStackSpace(MBB, CalleeSavesBegin, 0, SVECalleeSavesSize, false,
2178                      nullptr, EmitAsyncCFI && !HasFP, CFAOffset,
2179                      MFI.hasVarSizedObjects() || LocalsSize);
2180   CFAOffset += SVECalleeSavesSize;
2181 
2182   if (EmitAsyncCFI)
2183     emitCalleeSavedSVELocations(MBB, CalleeSavesEnd);
2184 
2185   // Allocate space for the rest of the frame including SVE locals. Align the
2186   // stack as necessary.
2187   assert(!(canUseRedZone(MF) && NeedsRealignment) &&
2188          "Cannot use redzone with stack realignment");
2189   if (!canUseRedZone(MF)) {
2190     // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
2191     // the correct value here, as NumBytes also includes padding bytes,
2192     // which shouldn't be counted here.
2193     allocateStackSpace(MBB, CalleeSavesEnd, RealignmentPadding,
2194                        SVELocalsSize + StackOffset::getFixed(NumBytes),
2195                        NeedsWinCFI, &HasWinCFI, EmitAsyncCFI && !HasFP,
2196                        CFAOffset, MFI.hasVarSizedObjects());
2197   }
2198 
2199   // If we need a base pointer, set it up here. It's whatever the value of the
2200   // stack pointer is at this point. Any variable size objects will be allocated
2201   // after this, so we can still use the base pointer to reference locals.
2202   //
2203   // FIXME: Clarify FrameSetup flags here.
2204   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
2205   // needed.
2206   // For funclets the BP belongs to the containing function.
2207   if (!IsFunclet && RegInfo->hasBasePointer(MF)) {
2208     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
2209                      false);
2210     if (NeedsWinCFI) {
2211       HasWinCFI = true;
2212       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
2213           .setMIFlag(MachineInstr::FrameSetup);
2214     }
2215   }
2216 
2217   // The very last FrameSetup instruction indicates the end of prologue. Emit a
2218   // SEH opcode indicating the prologue end.
2219   if (NeedsWinCFI && HasWinCFI) {
2220     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
2221         .setMIFlag(MachineInstr::FrameSetup);
2222   }
2223 
2224   // SEH funclets are passed the frame pointer in X1.  If the parent
2225   // function uses the base register, then the base register is used
2226   // directly, and is not retrieved from X1.
2227   if (IsFunclet && F.hasPersonalityFn()) {
2228     EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());
2229     if (isAsynchronousEHPersonality(Per)) {
2230       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)
2231           .addReg(AArch64::X1)
2232           .setMIFlag(MachineInstr::FrameSetup);
2233       MBB.addLiveIn(AArch64::X1);
2234     }
2235   }
2236 
2237   if (EmitCFI && !EmitAsyncCFI) {
2238     if (HasFP) {
2239       emitDefineCFAWithFP(MF, MBB, MBBI, DL, FixedObject);
2240     } else {
2241       StackOffset TotalSize =
2242           SVEStackSize + StackOffset::getFixed((int64_t)MFI.getStackSize());
2243       unsigned CFIIndex = MF.addFrameInst(createDefCFA(
2244           *RegInfo, /*FrameReg=*/AArch64::SP, /*Reg=*/AArch64::SP, TotalSize,
2245           /*LastAdjustmentWasScalable=*/false));
2246       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2247           .addCFIIndex(CFIIndex)
2248           .setMIFlags(MachineInstr::FrameSetup);
2249     }
2250     emitCalleeSavedGPRLocations(MBB, MBBI);
2251     emitCalleeSavedSVELocations(MBB, MBBI);
2252   }
2253 }
2254 
2255 static bool isFuncletReturnInstr(const MachineInstr &MI) {
2256   switch (MI.getOpcode()) {
2257   default:
2258     return false;
2259   case AArch64::CATCHRET:
2260   case AArch64::CLEANUPRET:
2261     return true;
2262   }
2263 }
2264 
2265 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
2266                                         MachineBasicBlock &MBB) const {
2267   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
2268   MachineFrameInfo &MFI = MF.getFrameInfo();
2269   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2270   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2271   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
2272   DebugLoc DL;
2273   bool NeedsWinCFI = needsWinCFI(MF);
2274   bool EmitCFI = AFI->needsAsyncDwarfUnwindInfo(MF);
2275   bool HasWinCFI = false;
2276   bool IsFunclet = false;
2277 
2278   if (MBB.end() != MBBI) {
2279     DL = MBBI->getDebugLoc();
2280     IsFunclet = isFuncletReturnInstr(*MBBI);
2281   }
2282 
2283   MachineBasicBlock::iterator EpilogStartI = MBB.end();
2284 
2285   auto FinishingTouches = make_scope_exit([&]() {
2286     if (AFI->shouldSignReturnAddress(MF)) {
2287       BuildMI(MBB, MBB.getFirstTerminator(), DL,
2288               TII->get(AArch64::PAUTH_EPILOGUE))
2289           .setMIFlag(MachineInstr::FrameDestroy);
2290       if (NeedsWinCFI)
2291         HasWinCFI = true; // AArch64PointerAuth pass will insert SEH_PACSignLR
2292     }
2293     if (AFI->needsShadowCallStackPrologueEpilogue(MF))
2294       emitShadowCallStackEpilogue(*TII, MF, MBB, MBB.getFirstTerminator(), DL);
2295     if (EmitCFI)
2296       emitCalleeSavedGPRRestores(MBB, MBB.getFirstTerminator());
2297     if (HasWinCFI) {
2298       BuildMI(MBB, MBB.getFirstTerminator(), DL,
2299               TII->get(AArch64::SEH_EpilogEnd))
2300           .setMIFlag(MachineInstr::FrameDestroy);
2301       if (!MF.hasWinCFI())
2302         MF.setHasWinCFI(true);
2303     }
2304     if (NeedsWinCFI) {
2305       assert(EpilogStartI != MBB.end());
2306       if (!HasWinCFI)
2307         MBB.erase(EpilogStartI);
2308     }
2309   });
2310 
2311   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
2312                                : MFI.getStackSize();
2313 
2314   // All calls are tail calls in GHC calling conv, and functions have no
2315   // prologue/epilogue.
2316   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
2317     return;
2318 
2319   // How much of the stack used by incoming arguments this function is expected
2320   // to restore in this particular epilogue.
2321   int64_t ArgumentStackToRestore = getArgumentStackToRestore(MF, MBB);
2322   bool IsWin64 = Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv(),
2323                                               MF.getFunction().isVarArg());
2324   unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
2325 
2326   int64_t AfterCSRPopSize = ArgumentStackToRestore;
2327   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
2328   // We cannot rely on the local stack size set in emitPrologue if the function
2329   // has funclets, as funclets have different local stack size requirements, and
2330   // the current value set in emitPrologue may be that of the containing
2331   // function.
2332   if (MF.hasEHFunclets())
2333     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
2334   if (homogeneousPrologEpilog(MF, &MBB)) {
2335     assert(!NeedsWinCFI);
2336     auto LastPopI = MBB.getFirstTerminator();
2337     if (LastPopI != MBB.begin()) {
2338       auto HomogeneousEpilog = std::prev(LastPopI);
2339       if (HomogeneousEpilog->getOpcode() == AArch64::HOM_Epilog)
2340         LastPopI = HomogeneousEpilog;
2341     }
2342 
2343     // Adjust local stack
2344     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
2345                     StackOffset::getFixed(AFI->getLocalStackSize()), TII,
2346                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
2347 
2348     // SP has been already adjusted while restoring callee save regs.
2349     // We've bailed-out the case with adjusting SP for arguments.
2350     assert(AfterCSRPopSize == 0);
2351     return;
2352   }
2353   bool CombineSPBump = shouldCombineCSRLocalStackBumpInEpilogue(MBB, NumBytes);
2354   // Assume we can't combine the last pop with the sp restore.
2355 
2356   bool CombineAfterCSRBump = false;
2357   if (!CombineSPBump && PrologueSaveSize != 0) {
2358     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
2359     while (Pop->getOpcode() == TargetOpcode::CFI_INSTRUCTION ||
2360            AArch64InstrInfo::isSEHInstruction(*Pop))
2361       Pop = std::prev(Pop);
2362     // Converting the last ldp to a post-index ldp is valid only if the last
2363     // ldp's offset is 0.
2364     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
2365     // If the offset is 0 and the AfterCSR pop is not actually trying to
2366     // allocate more stack for arguments (in space that an untimely interrupt
2367     // may clobber), convert it to a post-index ldp.
2368     if (OffsetOp.getImm() == 0 && AfterCSRPopSize >= 0) {
2369       convertCalleeSaveRestoreToSPPrePostIncDec(
2370           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, EmitCFI,
2371           MachineInstr::FrameDestroy, PrologueSaveSize);
2372     } else {
2373       // If not, make sure to emit an add after the last ldp.
2374       // We're doing this by transfering the size to be restored from the
2375       // adjustment *before* the CSR pops to the adjustment *after* the CSR
2376       // pops.
2377       AfterCSRPopSize += PrologueSaveSize;
2378       CombineAfterCSRBump = true;
2379     }
2380   }
2381 
2382   // Move past the restores of the callee-saved registers.
2383   // If we plan on combining the sp bump of the local stack size and the callee
2384   // save stack size, we might need to adjust the CSR save and restore offsets.
2385   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
2386   MachineBasicBlock::iterator Begin = MBB.begin();
2387   while (LastPopI != Begin) {
2388     --LastPopI;
2389     if (!LastPopI->getFlag(MachineInstr::FrameDestroy) ||
2390         IsSVECalleeSave(LastPopI)) {
2391       ++LastPopI;
2392       break;
2393     } else if (CombineSPBump)
2394       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
2395                                         NeedsWinCFI, &HasWinCFI);
2396   }
2397 
2398   if (NeedsWinCFI) {
2399     // Note that there are cases where we insert SEH opcodes in the
2400     // epilogue when we had no SEH opcodes in the prologue. For
2401     // example, when there is no stack frame but there are stack
2402     // arguments. Insert the SEH_EpilogStart and remove it later if it
2403     // we didn't emit any SEH opcodes to avoid generating WinCFI for
2404     // functions that don't need it.
2405     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
2406         .setMIFlag(MachineInstr::FrameDestroy);
2407     EpilogStartI = LastPopI;
2408     --EpilogStartI;
2409   }
2410 
2411   if (hasFP(MF) && AFI->hasSwiftAsyncContext()) {
2412     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
2413     case SwiftAsyncFramePointerMode::DeploymentBased:
2414       // Avoid the reload as it is GOT relative, and instead fall back to the
2415       // hardcoded value below.  This allows a mismatch between the OS and
2416       // application without immediately terminating on the difference.
2417       [[fallthrough]];
2418     case SwiftAsyncFramePointerMode::Always:
2419       // We need to reset FP to its untagged state on return. Bit 60 is
2420       // currently used to show the presence of an extended frame.
2421 
2422       // BIC x29, x29, #0x1000_0000_0000_0000
2423       BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::ANDXri),
2424               AArch64::FP)
2425           .addUse(AArch64::FP)
2426           .addImm(0x10fe)
2427           .setMIFlag(MachineInstr::FrameDestroy);
2428       if (NeedsWinCFI) {
2429         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
2430             .setMIFlags(MachineInstr::FrameDestroy);
2431         HasWinCFI = true;
2432       }
2433       break;
2434 
2435     case SwiftAsyncFramePointerMode::Never:
2436       break;
2437     }
2438   }
2439 
2440   const StackOffset &SVEStackSize = getSVEStackSize(MF);
2441 
2442   // If there is a single SP update, insert it before the ret and we're done.
2443   if (CombineSPBump) {
2444     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
2445 
2446     // When we are about to restore the CSRs, the CFA register is SP again.
2447     if (EmitCFI && hasFP(MF)) {
2448       const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();
2449       unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
2450       unsigned CFIIndex =
2451           MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, NumBytes));
2452       BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2453           .addCFIIndex(CFIIndex)
2454           .setMIFlags(MachineInstr::FrameDestroy);
2455     }
2456 
2457     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
2458                     StackOffset::getFixed(NumBytes + (int64_t)AfterCSRPopSize),
2459                     TII, MachineInstr::FrameDestroy, false, NeedsWinCFI,
2460                     &HasWinCFI, EmitCFI, StackOffset::getFixed(NumBytes));
2461     return;
2462   }
2463 
2464   NumBytes -= PrologueSaveSize;
2465   assert(NumBytes >= 0 && "Negative stack allocation size!?");
2466 
2467   // Process the SVE callee-saves to determine what space needs to be
2468   // deallocated.
2469   StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize;
2470   MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI;
2471   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
2472     RestoreBegin = std::prev(RestoreEnd);
2473     while (RestoreBegin != MBB.begin() &&
2474            IsSVECalleeSave(std::prev(RestoreBegin)))
2475       --RestoreBegin;
2476 
2477     assert(IsSVECalleeSave(RestoreBegin) &&
2478            IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction");
2479 
2480     StackOffset CalleeSavedSizeAsOffset =
2481         StackOffset::getScalable(CalleeSavedSize);
2482     DeallocateBefore = SVEStackSize - CalleeSavedSizeAsOffset;
2483     DeallocateAfter = CalleeSavedSizeAsOffset;
2484   }
2485 
2486   // Deallocate the SVE area.
2487   if (SVEStackSize) {
2488     // If we have stack realignment or variable sized objects on the stack,
2489     // restore the stack pointer from the frame pointer prior to SVE CSR
2490     // restoration.
2491     if (AFI->isStackRealigned() || MFI.hasVarSizedObjects()) {
2492       if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
2493         // Set SP to start of SVE callee-save area from which they can
2494         // be reloaded. The code below will deallocate the stack space
2495         // space by moving FP -> SP.
2496         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP,
2497                         StackOffset::getScalable(-CalleeSavedSize), TII,
2498                         MachineInstr::FrameDestroy);
2499       }
2500     } else {
2501       if (AFI->getSVECalleeSavedStackSize()) {
2502         // Deallocate the non-SVE locals first before we can deallocate (and
2503         // restore callee saves) from the SVE area.
2504         emitFrameOffset(
2505             MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
2506             StackOffset::getFixed(NumBytes), TII, MachineInstr::FrameDestroy,
2507             false, false, nullptr, EmitCFI && !hasFP(MF),
2508             SVEStackSize + StackOffset::getFixed(NumBytes + PrologueSaveSize));
2509         NumBytes = 0;
2510       }
2511 
2512       emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
2513                       DeallocateBefore, TII, MachineInstr::FrameDestroy, false,
2514                       false, nullptr, EmitCFI && !hasFP(MF),
2515                       SVEStackSize +
2516                           StackOffset::getFixed(NumBytes + PrologueSaveSize));
2517 
2518       emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP,
2519                       DeallocateAfter, TII, MachineInstr::FrameDestroy, false,
2520                       false, nullptr, EmitCFI && !hasFP(MF),
2521                       DeallocateAfter +
2522                           StackOffset::getFixed(NumBytes + PrologueSaveSize));
2523     }
2524     if (EmitCFI)
2525       emitCalleeSavedSVERestores(MBB, RestoreEnd);
2526   }
2527 
2528   if (!hasFP(MF)) {
2529     bool RedZone = canUseRedZone(MF);
2530     // If this was a redzone leaf function, we don't need to restore the
2531     // stack pointer (but we may need to pop stack args for fastcc).
2532     if (RedZone && AfterCSRPopSize == 0)
2533       return;
2534 
2535     // Pop the local variables off the stack. If there are no callee-saved
2536     // registers, it means we are actually positioned at the terminator and can
2537     // combine stack increment for the locals and the stack increment for
2538     // callee-popped arguments into (possibly) a single instruction and be done.
2539     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
2540     int64_t StackRestoreBytes = RedZone ? 0 : NumBytes;
2541     if (NoCalleeSaveRestore)
2542       StackRestoreBytes += AfterCSRPopSize;
2543 
2544     emitFrameOffset(
2545         MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
2546         StackOffset::getFixed(StackRestoreBytes), TII,
2547         MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI, EmitCFI,
2548         StackOffset::getFixed((RedZone ? 0 : NumBytes) + PrologueSaveSize));
2549 
2550     // If we were able to combine the local stack pop with the argument pop,
2551     // then we're done.
2552     if (NoCalleeSaveRestore || AfterCSRPopSize == 0) {
2553       return;
2554     }
2555 
2556     NumBytes = 0;
2557   }
2558 
2559   // Restore the original stack pointer.
2560   // FIXME: Rather than doing the math here, we should instead just use
2561   // non-post-indexed loads for the restores if we aren't actually going to
2562   // be able to save any instructions.
2563   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) {
2564     emitFrameOffset(
2565         MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
2566         StackOffset::getFixed(-AFI->getCalleeSaveBaseToFrameRecordOffset()),
2567         TII, MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
2568   } else if (NumBytes)
2569     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
2570                     StackOffset::getFixed(NumBytes), TII,
2571                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
2572 
2573   // When we are about to restore the CSRs, the CFA register is SP again.
2574   if (EmitCFI && hasFP(MF)) {
2575     const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();
2576     unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
2577     unsigned CFIIndex = MF.addFrameInst(
2578         MCCFIInstruction::cfiDefCfa(nullptr, Reg, PrologueSaveSize));
2579     BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2580         .addCFIIndex(CFIIndex)
2581         .setMIFlags(MachineInstr::FrameDestroy);
2582   }
2583 
2584   // This must be placed after the callee-save restore code because that code
2585   // assumes the SP is at the same location as it was after the callee-save save
2586   // code in the prologue.
2587   if (AfterCSRPopSize) {
2588     assert(AfterCSRPopSize > 0 && "attempting to reallocate arg stack that an "
2589                                   "interrupt may have clobbered");
2590 
2591     emitFrameOffset(
2592         MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
2593         StackOffset::getFixed(AfterCSRPopSize), TII, MachineInstr::FrameDestroy,
2594         false, NeedsWinCFI, &HasWinCFI, EmitCFI,
2595         StackOffset::getFixed(CombineAfterCSRBump ? PrologueSaveSize : 0));
2596   }
2597 }
2598 
2599 bool AArch64FrameLowering::enableCFIFixup(MachineFunction &MF) const {
2600   return TargetFrameLowering::enableCFIFixup(MF) &&
2601          MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF);
2602 }
2603 
2604 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
2605 /// debug info.  It's the same as what we use for resolving the code-gen
2606 /// references for now.  FIXME: This can go wrong when references are
2607 /// SP-relative and simple call frames aren't used.
2608 StackOffset
2609 AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
2610                                              Register &FrameReg) const {
2611   return resolveFrameIndexReference(
2612       MF, FI, FrameReg,
2613       /*PreferFP=*/
2614       MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress) ||
2615           MF.getFunction().hasFnAttribute(Attribute::SanitizeMemTag),
2616       /*ForSimm=*/false);
2617 }
2618 
2619 StackOffset
2620 AArch64FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
2621                                                    int FI) const {
2622   // This function serves to provide a comparable offset from a single reference
2623   // point (the value of SP at function entry) that can be used for analysis,
2624   // e.g. the stack-frame-layout analysis pass. It is not guaranteed to be
2625   // correct for all objects in the presence of VLA-area objects or dynamic
2626   // stack re-alignment.
2627 
2628   const auto &MFI = MF.getFrameInfo();
2629 
2630   int64_t ObjectOffset = MFI.getObjectOffset(FI);
2631   StackOffset SVEStackSize = getSVEStackSize(MF);
2632 
2633   // For VLA-area objects, just emit an offset at the end of the stack frame.
2634   // Whilst not quite correct, these objects do live at the end of the frame and
2635   // so it is more useful for analysis for the offset to reflect this.
2636   if (MFI.isVariableSizedObjectIndex(FI)) {
2637     return StackOffset::getFixed(-((int64_t)MFI.getStackSize())) - SVEStackSize;
2638   }
2639 
2640   // This is correct in the absence of any SVE stack objects.
2641   if (!SVEStackSize)
2642     return StackOffset::getFixed(ObjectOffset - getOffsetOfLocalArea());
2643 
2644   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2645   if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
2646     return StackOffset::get(-((int64_t)AFI->getCalleeSavedStackSize()),
2647                             ObjectOffset);
2648   }
2649 
2650   bool IsFixed = MFI.isFixedObjectIndex(FI);
2651   bool IsCSR =
2652       !IsFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
2653 
2654   StackOffset ScalableOffset = {};
2655   if (!IsFixed && !IsCSR)
2656     ScalableOffset = -SVEStackSize;
2657 
2658   return StackOffset::getFixed(ObjectOffset) + ScalableOffset;
2659 }
2660 
2661 StackOffset
2662 AArch64FrameLowering::getNonLocalFrameIndexReference(const MachineFunction &MF,
2663                                                      int FI) const {
2664   return StackOffset::getFixed(getSEHFrameIndexOffset(MF, FI));
2665 }
2666 
2667 static StackOffset getFPOffset(const MachineFunction &MF,
2668                                int64_t ObjectOffset) {
2669   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2670   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2671   const Function &F = MF.getFunction();
2672   bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv(), F.isVarArg());
2673   unsigned FixedObject =
2674       getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet=*/false);
2675   int64_t CalleeSaveSize = AFI->getCalleeSavedStackSize(MF.getFrameInfo());
2676   int64_t FPAdjust =
2677       CalleeSaveSize - AFI->getCalleeSaveBaseToFrameRecordOffset();
2678   return StackOffset::getFixed(ObjectOffset + FixedObject + FPAdjust);
2679 }
2680 
2681 static StackOffset getStackOffset(const MachineFunction &MF,
2682                                   int64_t ObjectOffset) {
2683   const auto &MFI = MF.getFrameInfo();
2684   return StackOffset::getFixed(ObjectOffset + (int64_t)MFI.getStackSize());
2685 }
2686 
2687 // TODO: This function currently does not work for scalable vectors.
2688 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,
2689                                                  int FI) const {
2690   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
2691       MF.getSubtarget().getRegisterInfo());
2692   int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);
2693   return RegInfo->getLocalAddressRegister(MF) == AArch64::FP
2694              ? getFPOffset(MF, ObjectOffset).getFixed()
2695              : getStackOffset(MF, ObjectOffset).getFixed();
2696 }
2697 
2698 StackOffset AArch64FrameLowering::resolveFrameIndexReference(
2699     const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP,
2700     bool ForSimm) const {
2701   const auto &MFI = MF.getFrameInfo();
2702   int64_t ObjectOffset = MFI.getObjectOffset(FI);
2703   bool isFixed = MFI.isFixedObjectIndex(FI);
2704   bool isSVE = MFI.getStackID(FI) == TargetStackID::ScalableVector;
2705   return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg,
2706                                      PreferFP, ForSimm);
2707 }
2708 
2709 StackOffset AArch64FrameLowering::resolveFrameOffsetReference(
2710     const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, bool isSVE,
2711     Register &FrameReg, bool PreferFP, bool ForSimm) const {
2712   const auto &MFI = MF.getFrameInfo();
2713   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
2714       MF.getSubtarget().getRegisterInfo());
2715   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2716   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2717 
2718   int64_t FPOffset = getFPOffset(MF, ObjectOffset).getFixed();
2719   int64_t Offset = getStackOffset(MF, ObjectOffset).getFixed();
2720   bool isCSR =
2721       !isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
2722 
2723   const StackOffset &SVEStackSize = getSVEStackSize(MF);
2724 
2725   // Use frame pointer to reference fixed objects. Use it for locals if
2726   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
2727   // reliable as a base). Make sure useFPForScavengingIndex() does the
2728   // right thing for the emergency spill slot.
2729   bool UseFP = false;
2730   if (AFI->hasStackFrame() && !isSVE) {
2731     // We shouldn't prefer using the FP to access fixed-sized stack objects when
2732     // there are scalable (SVE) objects in between the FP and the fixed-sized
2733     // objects.
2734     PreferFP &= !SVEStackSize;
2735 
2736     // Note: Keeping the following as multiple 'if' statements rather than
2737     // merging to a single expression for readability.
2738     //
2739     // Argument access should always use the FP.
2740     if (isFixed) {
2741       UseFP = hasFP(MF);
2742     } else if (isCSR && RegInfo->hasStackRealignment(MF)) {
2743       // References to the CSR area must use FP if we're re-aligning the stack
2744       // since the dynamically-sized alignment padding is between the SP/BP and
2745       // the CSR area.
2746       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
2747       UseFP = true;
2748     } else if (hasFP(MF) && !RegInfo->hasStackRealignment(MF)) {
2749       // If the FPOffset is negative and we're producing a signed immediate, we
2750       // have to keep in mind that the available offset range for negative
2751       // offsets is smaller than for positive ones. If an offset is available
2752       // via the FP and the SP, use whichever is closest.
2753       bool FPOffsetFits = !ForSimm || FPOffset >= -256;
2754       PreferFP |= Offset > -FPOffset && !SVEStackSize;
2755 
2756       if (MFI.hasVarSizedObjects()) {
2757         // If we have variable sized objects, we can use either FP or BP, as the
2758         // SP offset is unknown. We can use the base pointer if we have one and
2759         // FP is not preferred. If not, we're stuck with using FP.
2760         bool CanUseBP = RegInfo->hasBasePointer(MF);
2761         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
2762           UseFP = PreferFP;
2763         else if (!CanUseBP) // Can't use BP. Forced to use FP.
2764           UseFP = true;
2765         // else we can use BP and FP, but the offset from FP won't fit.
2766         // That will make us scavenge registers which we can probably avoid by
2767         // using BP. If it won't fit for BP either, we'll scavenge anyway.
2768       } else if (FPOffset >= 0) {
2769         // Use SP or FP, whichever gives us the best chance of the offset
2770         // being in range for direct access. If the FPOffset is positive,
2771         // that'll always be best, as the SP will be even further away.
2772         UseFP = true;
2773       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
2774         // Funclets access the locals contained in the parent's stack frame
2775         // via the frame pointer, so we have to use the FP in the parent
2776         // function.
2777         (void) Subtarget;
2778         assert(Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv(),
2779                                             MF.getFunction().isVarArg()) &&
2780                "Funclets should only be present on Win64");
2781         UseFP = true;
2782       } else {
2783         // We have the choice between FP and (SP or BP).
2784         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
2785           UseFP = true;
2786       }
2787     }
2788   }
2789 
2790   assert(
2791       ((isFixed || isCSR) || !RegInfo->hasStackRealignment(MF) || !UseFP) &&
2792       "In the presence of dynamic stack pointer realignment, "
2793       "non-argument/CSR objects cannot be accessed through the frame pointer");
2794 
2795   if (isSVE) {
2796     StackOffset FPOffset =
2797         StackOffset::get(-AFI->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset);
2798     StackOffset SPOffset =
2799         SVEStackSize +
2800         StackOffset::get(MFI.getStackSize() - AFI->getCalleeSavedStackSize(),
2801                          ObjectOffset);
2802     // Always use the FP for SVE spills if available and beneficial.
2803     if (hasFP(MF) && (SPOffset.getFixed() ||
2804                       FPOffset.getScalable() < SPOffset.getScalable() ||
2805                       RegInfo->hasStackRealignment(MF))) {
2806       FrameReg = RegInfo->getFrameRegister(MF);
2807       return FPOffset;
2808     }
2809 
2810     FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
2811                                            : (unsigned)AArch64::SP;
2812     return SPOffset;
2813   }
2814 
2815   StackOffset ScalableOffset = {};
2816   if (UseFP && !(isFixed || isCSR))
2817     ScalableOffset = -SVEStackSize;
2818   if (!UseFP && (isFixed || isCSR))
2819     ScalableOffset = SVEStackSize;
2820 
2821   if (UseFP) {
2822     FrameReg = RegInfo->getFrameRegister(MF);
2823     return StackOffset::getFixed(FPOffset) + ScalableOffset;
2824   }
2825 
2826   // Use the base pointer if we have one.
2827   if (RegInfo->hasBasePointer(MF))
2828     FrameReg = RegInfo->getBaseRegister();
2829   else {
2830     assert(!MFI.hasVarSizedObjects() &&
2831            "Can't use SP when we have var sized objects.");
2832     FrameReg = AArch64::SP;
2833     // If we're using the red zone for this function, the SP won't actually
2834     // be adjusted, so the offsets will be negative. They're also all
2835     // within range of the signed 9-bit immediate instructions.
2836     if (canUseRedZone(MF))
2837       Offset -= AFI->getLocalStackSize();
2838   }
2839 
2840   return StackOffset::getFixed(Offset) + ScalableOffset;
2841 }
2842 
2843 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
2844   // Do not set a kill flag on values that are also marked as live-in. This
2845   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
2846   // callee saved registers.
2847   // Omitting the kill flags is conservatively correct even if the live-in
2848   // is not used after all.
2849   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
2850   return getKillRegState(!IsLiveIn);
2851 }
2852 
2853 static bool produceCompactUnwindFrame(MachineFunction &MF) {
2854   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2855   AttributeList Attrs = MF.getFunction().getAttributes();
2856   return Subtarget.isTargetMachO() &&
2857          !(Subtarget.getTargetLowering()->supportSwiftError() &&
2858            Attrs.hasAttrSomewhere(Attribute::SwiftError)) &&
2859          MF.getFunction().getCallingConv() != CallingConv::SwiftTail &&
2860          !requiresSaveVG(MF);
2861 }
2862 
2863 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
2864                                              bool NeedsWinCFI, bool IsFirst,
2865                                              const TargetRegisterInfo *TRI) {
2866   // If we are generating register pairs for a Windows function that requires
2867   // EH support, then pair consecutive registers only.  There are no unwind
2868   // opcodes for saves/restores of non-consectuve register pairs.
2869   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x,
2870   // save_lrpair.
2871   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
2872 
2873   if (Reg2 == AArch64::FP)
2874     return true;
2875   if (!NeedsWinCFI)
2876     return false;
2877   if (TRI->getEncodingValue(Reg2) == TRI->getEncodingValue(Reg1) + 1)
2878     return false;
2879   // If pairing a GPR with LR, the pair can be described by the save_lrpair
2880   // opcode. If this is the first register pair, it would end up with a
2881   // predecrement, but there's no save_lrpair_x opcode, so we can only do this
2882   // if LR is paired with something else than the first register.
2883   // The save_lrpair opcode requires the first register to be an odd one.
2884   if (Reg1 >= AArch64::X19 && Reg1 <= AArch64::X27 &&
2885       (Reg1 - AArch64::X19) % 2 == 0 && Reg2 == AArch64::LR && !IsFirst)
2886     return false;
2887   return true;
2888 }
2889 
2890 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
2891 /// WindowsCFI requires that only consecutive registers can be paired.
2892 /// LR and FP need to be allocated together when the frame needs to save
2893 /// the frame-record. This means any other register pairing with LR is invalid.
2894 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
2895                                       bool UsesWinAAPCS, bool NeedsWinCFI,
2896                                       bool NeedsFrameRecord, bool IsFirst,
2897                                       const TargetRegisterInfo *TRI) {
2898   if (UsesWinAAPCS)
2899     return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI, IsFirst,
2900                                             TRI);
2901 
2902   // If we need to store the frame record, don't pair any register
2903   // with LR other than FP.
2904   if (NeedsFrameRecord)
2905     return Reg2 == AArch64::LR;
2906 
2907   return false;
2908 }
2909 
2910 namespace {
2911 
2912 struct RegPairInfo {
2913   unsigned Reg1 = AArch64::NoRegister;
2914   unsigned Reg2 = AArch64::NoRegister;
2915   int FrameIdx;
2916   int Offset;
2917   enum RegType { GPR, FPR64, FPR128, PPR, ZPR, VG } Type;
2918 
2919   RegPairInfo() = default;
2920 
2921   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
2922 
2923   unsigned getScale() const {
2924     switch (Type) {
2925     case PPR:
2926       return 2;
2927     case GPR:
2928     case FPR64:
2929     case VG:
2930       return 8;
2931     case ZPR:
2932     case FPR128:
2933       return 16;
2934     }
2935     llvm_unreachable("Unsupported type");
2936   }
2937 
2938   bool isScalable() const { return Type == PPR || Type == ZPR; }
2939 };
2940 
2941 } // end anonymous namespace
2942 
2943 static void computeCalleeSaveRegisterPairs(
2944     MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI,
2945     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
2946     bool NeedsFrameRecord) {
2947 
2948   if (CSI.empty())
2949     return;
2950 
2951   bool IsWindows = isTargetWindows(MF);
2952   bool NeedsWinCFI = needsWinCFI(MF);
2953   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2954   MachineFrameInfo &MFI = MF.getFrameInfo();
2955   CallingConv::ID CC = MF.getFunction().getCallingConv();
2956   unsigned Count = CSI.size();
2957   (void)CC;
2958   // MachO's compact unwind format relies on all registers being stored in
2959   // pairs.
2960   assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost ||
2961           CC == CallingConv::PreserveAll || CC == CallingConv::CXX_FAST_TLS ||
2962           CC == CallingConv::Win64 || (Count & 1) == 0) &&
2963          "Odd number of callee-saved regs to spill!");
2964   int ByteOffset = AFI->getCalleeSavedStackSize();
2965   int StackFillDir = -1;
2966   int RegInc = 1;
2967   unsigned FirstReg = 0;
2968   if (NeedsWinCFI) {
2969     // For WinCFI, fill the stack from the bottom up.
2970     ByteOffset = 0;
2971     StackFillDir = 1;
2972     // As the CSI array is reversed to match PrologEpilogInserter, iterate
2973     // backwards, to pair up registers starting from lower numbered registers.
2974     RegInc = -1;
2975     FirstReg = Count - 1;
2976   }
2977   int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
2978   bool NeedGapToAlignStack = AFI->hasCalleeSaveStackFreeSpace();
2979   Register LastReg = 0;
2980 
2981   // When iterating backwards, the loop condition relies on unsigned wraparound.
2982   for (unsigned i = FirstReg; i < Count; i += RegInc) {
2983     RegPairInfo RPI;
2984     RPI.Reg1 = CSI[i].getReg();
2985 
2986     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
2987       RPI.Type = RegPairInfo::GPR;
2988     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
2989       RPI.Type = RegPairInfo::FPR64;
2990     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
2991       RPI.Type = RegPairInfo::FPR128;
2992     else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
2993       RPI.Type = RegPairInfo::ZPR;
2994     else if (AArch64::PPRRegClass.contains(RPI.Reg1))
2995       RPI.Type = RegPairInfo::PPR;
2996     else if (RPI.Reg1 == AArch64::VG)
2997       RPI.Type = RegPairInfo::VG;
2998     else
2999       llvm_unreachable("Unsupported register class.");
3000 
3001     // Add the stack hazard size as we transition from GPR->FPR CSRs.
3002     if (AFI->hasStackHazardSlotIndex() &&
3003         (!LastReg || !AArch64InstrInfo::isFpOrNEON(LastReg)) &&
3004         AArch64InstrInfo::isFpOrNEON(RPI.Reg1))
3005       ByteOffset += StackFillDir * StackHazardSize;
3006     LastReg = RPI.Reg1;
3007 
3008     // Add the next reg to the pair if it is in the same register class.
3009     if (unsigned(i + RegInc) < Count && !AFI->hasStackHazardSlotIndex()) {
3010       Register NextReg = CSI[i + RegInc].getReg();
3011       bool IsFirst = i == FirstReg;
3012       switch (RPI.Type) {
3013       case RegPairInfo::GPR:
3014         if (AArch64::GPR64RegClass.contains(NextReg) &&
3015             !invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows,
3016                                        NeedsWinCFI, NeedsFrameRecord, IsFirst,
3017                                        TRI))
3018           RPI.Reg2 = NextReg;
3019         break;
3020       case RegPairInfo::FPR64:
3021         if (AArch64::FPR64RegClass.contains(NextReg) &&
3022             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI,
3023                                               IsFirst, TRI))
3024           RPI.Reg2 = NextReg;
3025         break;
3026       case RegPairInfo::FPR128:
3027         if (AArch64::FPR128RegClass.contains(NextReg))
3028           RPI.Reg2 = NextReg;
3029         break;
3030       case RegPairInfo::PPR:
3031         break;
3032       case RegPairInfo::ZPR:
3033         if (AFI->getPredicateRegForFillSpill() != 0)
3034           if (((RPI.Reg1 - AArch64::Z0) & 1) == 0 && (NextReg == RPI.Reg1 + 1))
3035             RPI.Reg2 = NextReg;
3036         break;
3037       case RegPairInfo::VG:
3038         break;
3039       }
3040     }
3041 
3042     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
3043     // list to come in sorted by frame index so that we can issue the store
3044     // pair instructions directly. Assert if we see anything otherwise.
3045     //
3046     // The order of the registers in the list is controlled by
3047     // getCalleeSavedRegs(), so they will always be in-order, as well.
3048     assert((!RPI.isPaired() ||
3049             (CSI[i].getFrameIdx() + RegInc == CSI[i + RegInc].getFrameIdx())) &&
3050            "Out of order callee saved regs!");
3051 
3052     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
3053             RPI.Reg1 == AArch64::LR) &&
3054            "FrameRecord must be allocated together with LR");
3055 
3056     // Windows AAPCS has FP and LR reversed.
3057     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP ||
3058             RPI.Reg2 == AArch64::LR) &&
3059            "FrameRecord must be allocated together with LR");
3060 
3061     // MachO's compact unwind format relies on all registers being stored in
3062     // adjacent register pairs.
3063     assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost ||
3064             CC == CallingConv::PreserveAll || CC == CallingConv::CXX_FAST_TLS ||
3065             CC == CallingConv::Win64 ||
3066             (RPI.isPaired() &&
3067              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
3068               RPI.Reg1 + 1 == RPI.Reg2))) &&
3069            "Callee-save registers not saved as adjacent register pair!");
3070 
3071     RPI.FrameIdx = CSI[i].getFrameIdx();
3072     if (NeedsWinCFI &&
3073         RPI.isPaired()) // RPI.FrameIdx must be the lower index of the pair
3074       RPI.FrameIdx = CSI[i + RegInc].getFrameIdx();
3075     int Scale = RPI.getScale();
3076 
3077     int OffsetPre = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
3078     assert(OffsetPre % Scale == 0);
3079 
3080     if (RPI.isScalable())
3081       ScalableByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale);
3082     else
3083       ByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale);
3084 
3085     // Swift's async context is directly before FP, so allocate an extra
3086     // 8 bytes for it.
3087     if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
3088         ((!IsWindows && RPI.Reg2 == AArch64::FP) ||
3089          (IsWindows && RPI.Reg2 == AArch64::LR)))
3090       ByteOffset += StackFillDir * 8;
3091 
3092     // Round up size of non-pair to pair size if we need to pad the
3093     // callee-save area to ensure 16-byte alignment.
3094     if (NeedGapToAlignStack && !NeedsWinCFI && !RPI.isScalable() &&
3095         RPI.Type != RegPairInfo::FPR128 && !RPI.isPaired() &&
3096         ByteOffset % 16 != 0) {
3097       ByteOffset += 8 * StackFillDir;
3098       assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16));
3099       // A stack frame with a gap looks like this, bottom up:
3100       // d9, d8. x21, gap, x20, x19.
3101       // Set extra alignment on the x21 object to create the gap above it.
3102       MFI.setObjectAlignment(RPI.FrameIdx, Align(16));
3103       NeedGapToAlignStack = false;
3104     }
3105 
3106     int OffsetPost = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
3107     assert(OffsetPost % Scale == 0);
3108     // If filling top down (default), we want the offset after incrementing it.
3109     // If filling bottom up (WinCFI) we need the original offset.
3110     int Offset = NeedsWinCFI ? OffsetPre : OffsetPost;
3111 
3112     // The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the
3113     // Swift context can directly precede FP.
3114     if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
3115         ((!IsWindows && RPI.Reg2 == AArch64::FP) ||
3116          (IsWindows && RPI.Reg2 == AArch64::LR)))
3117       Offset += 8;
3118     RPI.Offset = Offset / Scale;
3119 
3120     assert((!RPI.isPaired() ||
3121             (!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
3122             (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
3123            "Offset out of bounds for LDP/STP immediate");
3124 
3125     // Save the offset to frame record so that the FP register can point to the
3126     // innermost frame record (spilled FP and LR registers).
3127     if (NeedsFrameRecord &&
3128         ((!IsWindows && RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
3129          (IsWindows && RPI.Reg1 == AArch64::FP && RPI.Reg2 == AArch64::LR)))
3130       AFI->setCalleeSaveBaseToFrameRecordOffset(Offset);
3131 
3132     RegPairs.push_back(RPI);
3133     if (RPI.isPaired())
3134       i += RegInc;
3135   }
3136   if (NeedsWinCFI) {
3137     // If we need an alignment gap in the stack, align the topmost stack
3138     // object. A stack frame with a gap looks like this, bottom up:
3139     // x19, d8. d9, gap.
3140     // Set extra alignment on the topmost stack object (the first element in
3141     // CSI, which goes top down), to create the gap above it.
3142     if (AFI->hasCalleeSaveStackFreeSpace())
3143       MFI.setObjectAlignment(CSI[0].getFrameIdx(), Align(16));
3144     // We iterated bottom up over the registers; flip RegPairs back to top
3145     // down order.
3146     std::reverse(RegPairs.begin(), RegPairs.end());
3147   }
3148 }
3149 
3150 bool AArch64FrameLowering::spillCalleeSavedRegisters(
3151     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
3152     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
3153   MachineFunction &MF = *MBB.getParent();
3154   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
3155   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3156   bool NeedsWinCFI = needsWinCFI(MF);
3157   DebugLoc DL;
3158   SmallVector<RegPairInfo, 8> RegPairs;
3159 
3160   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
3161 
3162   MachineRegisterInfo &MRI = MF.getRegInfo();
3163   // Refresh the reserved regs in case there are any potential changes since the
3164   // last freeze.
3165   MRI.freezeReservedRegs();
3166 
3167   if (homogeneousPrologEpilog(MF)) {
3168     auto MIB = BuildMI(MBB, MI, DL, TII.get(AArch64::HOM_Prolog))
3169                    .setMIFlag(MachineInstr::FrameSetup);
3170 
3171     for (auto &RPI : RegPairs) {
3172       MIB.addReg(RPI.Reg1);
3173       MIB.addReg(RPI.Reg2);
3174 
3175       // Update register live in.
3176       if (!MRI.isReserved(RPI.Reg1))
3177         MBB.addLiveIn(RPI.Reg1);
3178       if (RPI.isPaired() && !MRI.isReserved(RPI.Reg2))
3179         MBB.addLiveIn(RPI.Reg2);
3180     }
3181     return true;
3182   }
3183   bool PTrueCreated = false;
3184   for (const RegPairInfo &RPI : llvm::reverse(RegPairs)) {
3185     unsigned Reg1 = RPI.Reg1;
3186     unsigned Reg2 = RPI.Reg2;
3187     unsigned StrOpc;
3188 
3189     // Issue sequence of spills for cs regs.  The first spill may be converted
3190     // to a pre-decrement store later by emitPrologue if the callee-save stack
3191     // area allocation can't be combined with the local stack area allocation.
3192     // For example:
3193     //    stp     x22, x21, [sp, #0]     // addImm(+0)
3194     //    stp     x20, x19, [sp, #16]    // addImm(+2)
3195     //    stp     fp, lr, [sp, #32]      // addImm(+4)
3196     // Rationale: This sequence saves uop updates compared to a sequence of
3197     // pre-increment spills like stp xi,xj,[sp,#-16]!
3198     // Note: Similar rationale and sequence for restores in epilog.
3199     unsigned Size;
3200     Align Alignment;
3201     switch (RPI.Type) {
3202     case RegPairInfo::GPR:
3203       StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
3204       Size = 8;
3205       Alignment = Align(8);
3206       break;
3207     case RegPairInfo::FPR64:
3208       StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
3209       Size = 8;
3210       Alignment = Align(8);
3211       break;
3212     case RegPairInfo::FPR128:
3213       StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
3214       Size = 16;
3215       Alignment = Align(16);
3216       break;
3217     case RegPairInfo::ZPR:
3218       StrOpc = RPI.isPaired() ? AArch64::ST1B_2Z_IMM : AArch64::STR_ZXI;
3219       Size = 16;
3220       Alignment = Align(16);
3221       break;
3222     case RegPairInfo::PPR:
3223       StrOpc = AArch64::STR_PXI;
3224       Size = 2;
3225       Alignment = Align(2);
3226       break;
3227     case RegPairInfo::VG:
3228       StrOpc = AArch64::STRXui;
3229       Size = 8;
3230       Alignment = Align(8);
3231       break;
3232     }
3233 
3234     unsigned X0Scratch = AArch64::NoRegister;
3235     if (Reg1 == AArch64::VG) {
3236       // Find an available register to store value of VG to.
3237       Reg1 = findScratchNonCalleeSaveRegister(&MBB);
3238       assert(Reg1 != AArch64::NoRegister);
3239       SMEAttrs Attrs(MF.getFunction());
3240 
3241       if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface() &&
3242           AFI->getStreamingVGIdx() == std::numeric_limits<int>::max()) {
3243         // For locally-streaming functions, we need to store both the streaming
3244         // & non-streaming VG. Spill the streaming value first.
3245         BuildMI(MBB, MI, DL, TII.get(AArch64::RDSVLI_XI), Reg1)
3246             .addImm(1)
3247             .setMIFlag(MachineInstr::FrameSetup);
3248         BuildMI(MBB, MI, DL, TII.get(AArch64::UBFMXri), Reg1)
3249             .addReg(Reg1)
3250             .addImm(3)
3251             .addImm(63)
3252             .setMIFlag(MachineInstr::FrameSetup);
3253 
3254         AFI->setStreamingVGIdx(RPI.FrameIdx);
3255       } else if (MF.getSubtarget<AArch64Subtarget>().hasSVE()) {
3256         BuildMI(MBB, MI, DL, TII.get(AArch64::CNTD_XPiI), Reg1)
3257             .addImm(31)
3258             .addImm(1)
3259             .setMIFlag(MachineInstr::FrameSetup);
3260         AFI->setVGIdx(RPI.FrameIdx);
3261       } else {
3262         const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
3263         if (llvm::any_of(
3264                 MBB.liveins(),
3265                 [&STI](const MachineBasicBlock::RegisterMaskPair &LiveIn) {
3266                   return STI.getRegisterInfo()->isSuperOrSubRegisterEq(
3267                       AArch64::X0, LiveIn.PhysReg);
3268                 }))
3269           X0Scratch = Reg1;
3270 
3271         if (X0Scratch != AArch64::NoRegister)
3272           BuildMI(MBB, MI, DL, TII.get(AArch64::ORRXrr), Reg1)
3273               .addReg(AArch64::XZR)
3274               .addReg(AArch64::X0, RegState::Undef)
3275               .addReg(AArch64::X0, RegState::Implicit)
3276               .setMIFlag(MachineInstr::FrameSetup);
3277 
3278         const uint32_t *RegMask = TRI->getCallPreservedMask(
3279             MF,
3280             CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1);
3281         BuildMI(MBB, MI, DL, TII.get(AArch64::BL))
3282             .addExternalSymbol("__arm_get_current_vg")
3283             .addRegMask(RegMask)
3284             .addReg(AArch64::X0, RegState::ImplicitDefine)
3285             .setMIFlag(MachineInstr::FrameSetup);
3286         Reg1 = AArch64::X0;
3287         AFI->setVGIdx(RPI.FrameIdx);
3288       }
3289     }
3290 
3291     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
3292                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
3293                dbgs() << ") -> fi#(" << RPI.FrameIdx;
3294                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
3295                dbgs() << ")\n");
3296 
3297     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
3298            "Windows unwdinding requires a consecutive (FP,LR) pair");
3299     // Windows unwind codes require consecutive registers if registers are
3300     // paired.  Make the switch here, so that the code below will save (x,x+1)
3301     // and not (x+1,x).
3302     unsigned FrameIdxReg1 = RPI.FrameIdx;
3303     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
3304     if (NeedsWinCFI && RPI.isPaired()) {
3305       std::swap(Reg1, Reg2);
3306       std::swap(FrameIdxReg1, FrameIdxReg2);
3307     }
3308 
3309     if (RPI.isPaired() && RPI.isScalable()) {
3310       [[maybe_unused]] const AArch64Subtarget &Subtarget =
3311                               MF.getSubtarget<AArch64Subtarget>();
3312       AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3313       unsigned PnReg = AFI->getPredicateRegForFillSpill();
3314       assert(((Subtarget.hasSVE2p1() || Subtarget.hasSME2()) && PnReg != 0) &&
3315              "Expects SVE2.1 or SME2 target and a predicate register");
3316 #ifdef EXPENSIVE_CHECKS
3317       auto IsPPR = [](const RegPairInfo &c) {
3318         return c.Reg1 == RegPairInfo::PPR;
3319       };
3320       auto PPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsPPR);
3321       auto IsZPR = [](const RegPairInfo &c) {
3322         return c.Type == RegPairInfo::ZPR;
3323       };
3324       auto ZPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsZPR);
3325       assert(!(PPRBegin < ZPRBegin) &&
3326              "Expected callee save predicate to be handled first");
3327 #endif
3328       if (!PTrueCreated) {
3329         PTrueCreated = true;
3330         BuildMI(MBB, MI, DL, TII.get(AArch64::PTRUE_C_B), PnReg)
3331             .setMIFlags(MachineInstr::FrameSetup);
3332       }
3333       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
3334       if (!MRI.isReserved(Reg1))
3335         MBB.addLiveIn(Reg1);
3336       if (!MRI.isReserved(Reg2))
3337         MBB.addLiveIn(Reg2);
3338       MIB.addReg(/*PairRegs*/ AArch64::Z0_Z1 + (RPI.Reg1 - AArch64::Z0));
3339       MIB.addMemOperand(MF.getMachineMemOperand(
3340           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
3341           MachineMemOperand::MOStore, Size, Alignment));
3342       MIB.addReg(PnReg);
3343       MIB.addReg(AArch64::SP)
3344           .addImm(RPI.Offset) // [sp, #offset*scale],
3345                               // where factor*scale is implicit
3346           .setMIFlag(MachineInstr::FrameSetup);
3347       MIB.addMemOperand(MF.getMachineMemOperand(
3348           MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
3349           MachineMemOperand::MOStore, Size, Alignment));
3350       if (NeedsWinCFI)
3351         InsertSEH(MIB, TII, MachineInstr::FrameSetup);
3352     } else { // The code when the pair of ZReg is not present
3353       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
3354       if (!MRI.isReserved(Reg1))
3355         MBB.addLiveIn(Reg1);
3356       if (RPI.isPaired()) {
3357         if (!MRI.isReserved(Reg2))
3358           MBB.addLiveIn(Reg2);
3359         MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
3360         MIB.addMemOperand(MF.getMachineMemOperand(
3361             MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
3362             MachineMemOperand::MOStore, Size, Alignment));
3363       }
3364       MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
3365           .addReg(AArch64::SP)
3366           .addImm(RPI.Offset) // [sp, #offset*scale],
3367                               // where factor*scale is implicit
3368           .setMIFlag(MachineInstr::FrameSetup);
3369       MIB.addMemOperand(MF.getMachineMemOperand(
3370           MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
3371           MachineMemOperand::MOStore, Size, Alignment));
3372       if (NeedsWinCFI)
3373         InsertSEH(MIB, TII, MachineInstr::FrameSetup);
3374     }
3375     // Update the StackIDs of the SVE stack slots.
3376     MachineFrameInfo &MFI = MF.getFrameInfo();
3377     if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR) {
3378       MFI.setStackID(FrameIdxReg1, TargetStackID::ScalableVector);
3379       if (RPI.isPaired())
3380         MFI.setStackID(FrameIdxReg2, TargetStackID::ScalableVector);
3381     }
3382 
3383     if (X0Scratch != AArch64::NoRegister)
3384       BuildMI(MBB, MI, DL, TII.get(AArch64::ORRXrr), AArch64::X0)
3385           .addReg(AArch64::XZR)
3386           .addReg(X0Scratch, RegState::Undef)
3387           .addReg(X0Scratch, RegState::Implicit)
3388           .setMIFlag(MachineInstr::FrameSetup);
3389   }
3390   return true;
3391 }
3392 
3393 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
3394     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
3395     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
3396   MachineFunction &MF = *MBB.getParent();
3397   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
3398   DebugLoc DL;
3399   SmallVector<RegPairInfo, 8> RegPairs;
3400   bool NeedsWinCFI = needsWinCFI(MF);
3401 
3402   if (MBBI != MBB.end())
3403     DL = MBBI->getDebugLoc();
3404 
3405   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
3406   if (homogeneousPrologEpilog(MF, &MBB)) {
3407     auto MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::HOM_Epilog))
3408                    .setMIFlag(MachineInstr::FrameDestroy);
3409     for (auto &RPI : RegPairs) {
3410       MIB.addReg(RPI.Reg1, RegState::Define);
3411       MIB.addReg(RPI.Reg2, RegState::Define);
3412     }
3413     return true;
3414   }
3415 
3416   // For performance reasons restore SVE register in increasing order
3417   auto IsPPR = [](const RegPairInfo &c) { return c.Type == RegPairInfo::PPR; };
3418   auto PPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsPPR);
3419   auto PPREnd = std::find_if_not(PPRBegin, RegPairs.end(), IsPPR);
3420   std::reverse(PPRBegin, PPREnd);
3421   auto IsZPR = [](const RegPairInfo &c) { return c.Type == RegPairInfo::ZPR; };
3422   auto ZPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsZPR);
3423   auto ZPREnd = std::find_if_not(ZPRBegin, RegPairs.end(), IsZPR);
3424   std::reverse(ZPRBegin, ZPREnd);
3425 
3426   bool PTrueCreated = false;
3427   for (const RegPairInfo &RPI : RegPairs) {
3428     unsigned Reg1 = RPI.Reg1;
3429     unsigned Reg2 = RPI.Reg2;
3430 
3431     // Issue sequence of restores for cs regs. The last restore may be converted
3432     // to a post-increment load later by emitEpilogue if the callee-save stack
3433     // area allocation can't be combined with the local stack area allocation.
3434     // For example:
3435     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
3436     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
3437     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
3438     // Note: see comment in spillCalleeSavedRegisters()
3439     unsigned LdrOpc;
3440     unsigned Size;
3441     Align Alignment;
3442     switch (RPI.Type) {
3443     case RegPairInfo::GPR:
3444       LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
3445       Size = 8;
3446       Alignment = Align(8);
3447       break;
3448     case RegPairInfo::FPR64:
3449       LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
3450       Size = 8;
3451       Alignment = Align(8);
3452       break;
3453     case RegPairInfo::FPR128:
3454       LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
3455       Size = 16;
3456       Alignment = Align(16);
3457       break;
3458     case RegPairInfo::ZPR:
3459       LdrOpc = RPI.isPaired() ? AArch64::LD1B_2Z_IMM : AArch64::LDR_ZXI;
3460       Size = 16;
3461       Alignment = Align(16);
3462       break;
3463     case RegPairInfo::PPR:
3464       LdrOpc = AArch64::LDR_PXI;
3465       Size = 2;
3466       Alignment = Align(2);
3467       break;
3468     case RegPairInfo::VG:
3469       continue;
3470     }
3471     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
3472                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
3473                dbgs() << ") -> fi#(" << RPI.FrameIdx;
3474                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
3475                dbgs() << ")\n");
3476 
3477     // Windows unwind codes require consecutive registers if registers are
3478     // paired.  Make the switch here, so that the code below will save (x,x+1)
3479     // and not (x+1,x).
3480     unsigned FrameIdxReg1 = RPI.FrameIdx;
3481     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
3482     if (NeedsWinCFI && RPI.isPaired()) {
3483       std::swap(Reg1, Reg2);
3484       std::swap(FrameIdxReg1, FrameIdxReg2);
3485     }
3486 
3487     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3488     if (RPI.isPaired() && RPI.isScalable()) {
3489       [[maybe_unused]] const AArch64Subtarget &Subtarget =
3490                               MF.getSubtarget<AArch64Subtarget>();
3491       unsigned PnReg = AFI->getPredicateRegForFillSpill();
3492       assert(((Subtarget.hasSVE2p1() || Subtarget.hasSME2()) && PnReg != 0) &&
3493              "Expects SVE2.1 or SME2 target and a predicate register");
3494 #ifdef EXPENSIVE_CHECKS
3495       assert(!(PPRBegin < ZPRBegin) &&
3496              "Expected callee save predicate to be handled first");
3497 #endif
3498       if (!PTrueCreated) {
3499         PTrueCreated = true;
3500         BuildMI(MBB, MBBI, DL, TII.get(AArch64::PTRUE_C_B), PnReg)
3501             .setMIFlags(MachineInstr::FrameDestroy);
3502       }
3503       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));
3504       MIB.addReg(/*PairRegs*/ AArch64::Z0_Z1 + (RPI.Reg1 - AArch64::Z0),
3505                  getDefRegState(true));
3506       MIB.addMemOperand(MF.getMachineMemOperand(
3507           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
3508           MachineMemOperand::MOLoad, Size, Alignment));
3509       MIB.addReg(PnReg);
3510       MIB.addReg(AArch64::SP)
3511           .addImm(RPI.Offset) // [sp, #offset*scale]
3512                               // where factor*scale is implicit
3513           .setMIFlag(MachineInstr::FrameDestroy);
3514       MIB.addMemOperand(MF.getMachineMemOperand(
3515           MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
3516           MachineMemOperand::MOLoad, Size, Alignment));
3517       if (NeedsWinCFI)
3518         InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
3519     } else {
3520       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));
3521       if (RPI.isPaired()) {
3522         MIB.addReg(Reg2, getDefRegState(true));
3523         MIB.addMemOperand(MF.getMachineMemOperand(
3524             MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
3525             MachineMemOperand::MOLoad, Size, Alignment));
3526       }
3527       MIB.addReg(Reg1, getDefRegState(true));
3528       MIB.addReg(AArch64::SP)
3529           .addImm(RPI.Offset) // [sp, #offset*scale]
3530                               // where factor*scale is implicit
3531           .setMIFlag(MachineInstr::FrameDestroy);
3532       MIB.addMemOperand(MF.getMachineMemOperand(
3533           MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
3534           MachineMemOperand::MOLoad, Size, Alignment));
3535       if (NeedsWinCFI)
3536         InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
3537     }
3538   }
3539   return true;
3540 }
3541 
3542 // Return the FrameID for a MMO.
3543 static std::optional<int> getMMOFrameID(MachineMemOperand *MMO,
3544                                         const MachineFrameInfo &MFI) {
3545   auto *PSV =
3546       dyn_cast_or_null<FixedStackPseudoSourceValue>(MMO->getPseudoValue());
3547   if (PSV)
3548     return std::optional<int>(PSV->getFrameIndex());
3549 
3550   if (MMO->getValue()) {
3551     if (auto *Al = dyn_cast<AllocaInst>(getUnderlyingObject(MMO->getValue()))) {
3552       for (int FI = MFI.getObjectIndexBegin(); FI < MFI.getObjectIndexEnd();
3553            FI++)
3554         if (MFI.getObjectAllocation(FI) == Al)
3555           return FI;
3556     }
3557   }
3558 
3559   return std::nullopt;
3560 }
3561 
3562 // Return the FrameID for a Load/Store instruction by looking at the first MMO.
3563 static std::optional<int> getLdStFrameID(const MachineInstr &MI,
3564                                          const MachineFrameInfo &MFI) {
3565   if (!MI.mayLoadOrStore() || MI.getNumMemOperands() < 1)
3566     return std::nullopt;
3567 
3568   return getMMOFrameID(*MI.memoperands_begin(), MFI);
3569 }
3570 
3571 // Check if a Hazard slot is needed for the current function, and if so create
3572 // one for it. The index is stored in AArch64FunctionInfo->StackHazardSlotIndex,
3573 // which can be used to determine if any hazard padding is needed.
3574 void AArch64FrameLowering::determineStackHazardSlot(
3575     MachineFunction &MF, BitVector &SavedRegs) const {
3576   if (StackHazardSize == 0 || StackHazardSize % 16 != 0 ||
3577       MF.getInfo<AArch64FunctionInfo>()->hasStackHazardSlotIndex())
3578     return;
3579 
3580   // Stack hazards are only needed in streaming functions.
3581   SMEAttrs Attrs(MF.getFunction());
3582   if (!StackHazardInNonStreaming && Attrs.hasNonStreamingInterfaceAndBody())
3583     return;
3584 
3585   MachineFrameInfo &MFI = MF.getFrameInfo();
3586 
3587   // Add a hazard slot if there are any CSR FPR registers, or are any fp-only
3588   // stack objects.
3589   bool HasFPRCSRs = any_of(SavedRegs.set_bits(), [](unsigned Reg) {
3590     return AArch64::FPR64RegClass.contains(Reg) ||
3591            AArch64::FPR128RegClass.contains(Reg) ||
3592            AArch64::ZPRRegClass.contains(Reg) ||
3593            AArch64::PPRRegClass.contains(Reg);
3594   });
3595   bool HasFPRStackObjects = false;
3596   if (!HasFPRCSRs) {
3597     std::vector<unsigned> FrameObjects(MFI.getObjectIndexEnd());
3598     for (auto &MBB : MF) {
3599       for (auto &MI : MBB) {
3600         std::optional<int> FI = getLdStFrameID(MI, MFI);
3601         if (FI && *FI >= 0 && *FI < (int)FrameObjects.size()) {
3602           if (MFI.getStackID(*FI) == TargetStackID::ScalableVector ||
3603               AArch64InstrInfo::isFpOrNEON(MI))
3604             FrameObjects[*FI] |= 2;
3605           else
3606             FrameObjects[*FI] |= 1;
3607         }
3608       }
3609     }
3610     HasFPRStackObjects =
3611         any_of(FrameObjects, [](unsigned B) { return (B & 3) == 2; });
3612   }
3613 
3614   if (HasFPRCSRs || HasFPRStackObjects) {
3615     int ID = MFI.CreateStackObject(StackHazardSize, Align(16), false);
3616     LLVM_DEBUG(dbgs() << "Created Hazard slot at " << ID << " size "
3617                       << StackHazardSize << "\n");
3618     MF.getInfo<AArch64FunctionInfo>()->setStackHazardSlotIndex(ID);
3619   }
3620 }
3621 
3622 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
3623                                                 BitVector &SavedRegs,
3624                                                 RegScavenger *RS) const {
3625   // All calls are tail calls in GHC calling conv, and functions have no
3626   // prologue/epilogue.
3627   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
3628     return;
3629 
3630   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
3631   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
3632       MF.getSubtarget().getRegisterInfo());
3633   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
3634   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3635   unsigned UnspilledCSGPR = AArch64::NoRegister;
3636   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
3637 
3638   MachineFrameInfo &MFI = MF.getFrameInfo();
3639   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
3640 
3641   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
3642                                 ? RegInfo->getBaseRegister()
3643                                 : (unsigned)AArch64::NoRegister;
3644 
3645   unsigned ExtraCSSpill = 0;
3646   bool HasUnpairedGPR64 = false;
3647   // Figure out which callee-saved registers to save/restore.
3648   for (unsigned i = 0; CSRegs[i]; ++i) {
3649     const unsigned Reg = CSRegs[i];
3650 
3651     // Add the base pointer register to SavedRegs if it is callee-save.
3652     if (Reg == BasePointerReg)
3653       SavedRegs.set(Reg);
3654 
3655     bool RegUsed = SavedRegs.test(Reg);
3656     unsigned PairedReg = AArch64::NoRegister;
3657     const bool RegIsGPR64 = AArch64::GPR64RegClass.contains(Reg);
3658     if (RegIsGPR64 || AArch64::FPR64RegClass.contains(Reg) ||
3659         AArch64::FPR128RegClass.contains(Reg)) {
3660       // Compensate for odd numbers of GP CSRs.
3661       // For now, all the known cases of odd number of CSRs are of GPRs.
3662       if (HasUnpairedGPR64)
3663         PairedReg = CSRegs[i % 2 == 0 ? i - 1 : i + 1];
3664       else
3665         PairedReg = CSRegs[i ^ 1];
3666     }
3667 
3668     // If the function requires all the GP registers to save (SavedRegs),
3669     // and there are an odd number of GP CSRs at the same time (CSRegs),
3670     // PairedReg could be in a different register class from Reg, which would
3671     // lead to a FPR (usually D8) accidentally being marked saved.
3672     if (RegIsGPR64 && !AArch64::GPR64RegClass.contains(PairedReg)) {
3673       PairedReg = AArch64::NoRegister;
3674       HasUnpairedGPR64 = true;
3675     }
3676     assert(PairedReg == AArch64::NoRegister ||
3677            AArch64::GPR64RegClass.contains(Reg, PairedReg) ||
3678            AArch64::FPR64RegClass.contains(Reg, PairedReg) ||
3679            AArch64::FPR128RegClass.contains(Reg, PairedReg));
3680 
3681     if (!RegUsed) {
3682       if (AArch64::GPR64RegClass.contains(Reg) &&
3683           !RegInfo->isReservedReg(MF, Reg)) {
3684         UnspilledCSGPR = Reg;
3685         UnspilledCSGPRPaired = PairedReg;
3686       }
3687       continue;
3688     }
3689 
3690     // MachO's compact unwind format relies on all registers being stored in
3691     // pairs.
3692     // FIXME: the usual format is actually better if unwinding isn't needed.
3693     if (producePairRegisters(MF) && PairedReg != AArch64::NoRegister &&
3694         !SavedRegs.test(PairedReg)) {
3695       SavedRegs.set(PairedReg);
3696       if (AArch64::GPR64RegClass.contains(PairedReg) &&
3697           !RegInfo->isReservedReg(MF, PairedReg))
3698         ExtraCSSpill = PairedReg;
3699     }
3700   }
3701 
3702   if (MF.getFunction().getCallingConv() == CallingConv::Win64 &&
3703       !Subtarget.isTargetWindows()) {
3704     // For Windows calling convention on a non-windows OS, where X18 is treated
3705     // as reserved, back up X18 when entering non-windows code (marked with the
3706     // Windows calling convention) and restore when returning regardless of
3707     // whether the individual function uses it - it might call other functions
3708     // that clobber it.
3709     SavedRegs.set(AArch64::X18);
3710   }
3711 
3712   // Calculates the callee saved stack size.
3713   unsigned CSStackSize = 0;
3714   unsigned SVECSStackSize = 0;
3715   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3716   const MachineRegisterInfo &MRI = MF.getRegInfo();
3717   for (unsigned Reg : SavedRegs.set_bits()) {
3718     auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
3719     if (AArch64::PPRRegClass.contains(Reg) ||
3720         AArch64::ZPRRegClass.contains(Reg))
3721       SVECSStackSize += RegSize;
3722     else
3723       CSStackSize += RegSize;
3724   }
3725 
3726   // Increase the callee-saved stack size if the function has streaming mode
3727   // changes, as we will need to spill the value of the VG register.
3728   // For locally streaming functions, we spill both the streaming and
3729   // non-streaming VG value.
3730   const Function &F = MF.getFunction();
3731   SMEAttrs Attrs(F);
3732   if (requiresSaveVG(MF)) {
3733     if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface())
3734       CSStackSize += 16;
3735     else
3736       CSStackSize += 8;
3737   }
3738 
3739   // Determine if a Hazard slot should be used, and increase the CSStackSize by
3740   // StackHazardSize if so.
3741   determineStackHazardSlot(MF, SavedRegs);
3742   if (AFI->hasStackHazardSlotIndex())
3743     CSStackSize += StackHazardSize;
3744 
3745   // Save number of saved regs, so we can easily update CSStackSize later.
3746   unsigned NumSavedRegs = SavedRegs.count();
3747 
3748   // The frame record needs to be created by saving the appropriate registers
3749   uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
3750   if (hasFP(MF) ||
3751       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
3752     SavedRegs.set(AArch64::FP);
3753     SavedRegs.set(AArch64::LR);
3754   }
3755 
3756   LLVM_DEBUG({
3757     dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
3758     for (unsigned Reg : SavedRegs.set_bits())
3759       dbgs() << ' ' << printReg(Reg, RegInfo);
3760     dbgs() << "\n";
3761   });
3762 
3763   // If any callee-saved registers are used, the frame cannot be eliminated.
3764   int64_t SVEStackSize =
3765       alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
3766   bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
3767 
3768   // The CSR spill slots have not been allocated yet, so estimateStackSize
3769   // won't include them.
3770   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
3771 
3772   // We may address some of the stack above the canonical frame address, either
3773   // for our own arguments or during a call. Include that in calculating whether
3774   // we have complicated addressing concerns.
3775   int64_t CalleeStackUsed = 0;
3776   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I) {
3777     int64_t FixedOff = MFI.getObjectOffset(I);
3778     if (FixedOff > CalleeStackUsed)
3779       CalleeStackUsed = FixedOff;
3780   }
3781 
3782   // Conservatively always assume BigStack when there are SVE spills.
3783   bool BigStack = SVEStackSize || (EstimatedStackSize + CSStackSize +
3784                                    CalleeStackUsed) > EstimatedStackSizeLimit;
3785   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
3786     AFI->setHasStackFrame(true);
3787 
3788   // Estimate if we might need to scavenge a register at some point in order
3789   // to materialize a stack offset. If so, either spill one additional
3790   // callee-saved register or reserve a special spill slot to facilitate
3791   // register scavenging. If we already spilled an extra callee-saved register
3792   // above to keep the number of spills even, we don't need to do anything else
3793   // here.
3794   if (BigStack) {
3795     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
3796       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
3797                         << " to get a scratch register.\n");
3798       SavedRegs.set(UnspilledCSGPR);
3799       ExtraCSSpill = UnspilledCSGPR;
3800 
3801       // MachO's compact unwind format relies on all registers being stored in
3802       // pairs, so if we need to spill one extra for BigStack, then we need to
3803       // store the pair.
3804       if (producePairRegisters(MF)) {
3805         if (UnspilledCSGPRPaired == AArch64::NoRegister) {
3806           // Failed to make a pair for compact unwind format, revert spilling.
3807           if (produceCompactUnwindFrame(MF)) {
3808             SavedRegs.reset(UnspilledCSGPR);
3809             ExtraCSSpill = AArch64::NoRegister;
3810           }
3811         } else
3812           SavedRegs.set(UnspilledCSGPRPaired);
3813       }
3814     }
3815 
3816     // If we didn't find an extra callee-saved register to spill, create
3817     // an emergency spill slot.
3818     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
3819       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3820       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
3821       unsigned Size = TRI->getSpillSize(RC);
3822       Align Alignment = TRI->getSpillAlign(RC);
3823       int FI = MFI.CreateStackObject(Size, Alignment, false);
3824       RS->addScavengingFrameIndex(FI);
3825       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
3826                         << " as the emergency spill slot.\n");
3827     }
3828   }
3829 
3830   // Adding the size of additional 64bit GPR saves.
3831   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
3832 
3833   // A Swift asynchronous context extends the frame record with a pointer
3834   // directly before FP.
3835   if (hasFP(MF) && AFI->hasSwiftAsyncContext())
3836     CSStackSize += 8;
3837 
3838   uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
3839   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
3840                     << EstimatedStackSize + AlignedCSStackSize << " bytes.\n");
3841 
3842   assert((!MFI.isCalleeSavedInfoValid() ||
3843           AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
3844          "Should not invalidate callee saved info");
3845 
3846   // Round up to register pair alignment to avoid additional SP adjustment
3847   // instructions.
3848   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
3849   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
3850   AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
3851 }
3852 
3853 bool AArch64FrameLowering::assignCalleeSavedSpillSlots(
3854     MachineFunction &MF, const TargetRegisterInfo *RegInfo,
3855     std::vector<CalleeSavedInfo> &CSI, unsigned &MinCSFrameIndex,
3856     unsigned &MaxCSFrameIndex) const {
3857   bool NeedsWinCFI = needsWinCFI(MF);
3858   // To match the canonical windows frame layout, reverse the list of
3859   // callee saved registers to get them laid out by PrologEpilogInserter
3860   // in the right order. (PrologEpilogInserter allocates stack objects top
3861   // down. Windows canonical prologs store higher numbered registers at
3862   // the top, thus have the CSI array start from the highest registers.)
3863   if (NeedsWinCFI)
3864     std::reverse(CSI.begin(), CSI.end());
3865 
3866   if (CSI.empty())
3867     return true; // Early exit if no callee saved registers are modified!
3868 
3869   // Now that we know which registers need to be saved and restored, allocate
3870   // stack slots for them.
3871   MachineFrameInfo &MFI = MF.getFrameInfo();
3872   auto *AFI = MF.getInfo<AArch64FunctionInfo>();
3873 
3874   bool UsesWinAAPCS = isTargetWindows(MF);
3875   if (UsesWinAAPCS && hasFP(MF) && AFI->hasSwiftAsyncContext()) {
3876     int FrameIdx = MFI.CreateStackObject(8, Align(16), true);
3877     AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
3878     if ((unsigned)FrameIdx < MinCSFrameIndex)
3879       MinCSFrameIndex = FrameIdx;
3880     if ((unsigned)FrameIdx > MaxCSFrameIndex)
3881       MaxCSFrameIndex = FrameIdx;
3882   }
3883 
3884   // Insert VG into the list of CSRs, immediately before LR if saved.
3885   if (requiresSaveVG(MF)) {
3886     std::vector<CalleeSavedInfo> VGSaves;
3887     SMEAttrs Attrs(MF.getFunction());
3888 
3889     auto VGInfo = CalleeSavedInfo(AArch64::VG);
3890     VGInfo.setRestored(false);
3891     VGSaves.push_back(VGInfo);
3892 
3893     // Add VG again if the function is locally-streaming, as we will spill two
3894     // values.
3895     if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface())
3896       VGSaves.push_back(VGInfo);
3897 
3898     bool InsertBeforeLR = false;
3899 
3900     for (unsigned I = 0; I < CSI.size(); I++)
3901       if (CSI[I].getReg() == AArch64::LR) {
3902         InsertBeforeLR = true;
3903         CSI.insert(CSI.begin() + I, VGSaves.begin(), VGSaves.end());
3904         break;
3905       }
3906 
3907     if (!InsertBeforeLR)
3908       CSI.insert(CSI.end(), VGSaves.begin(), VGSaves.end());
3909   }
3910 
3911   Register LastReg = 0;
3912   int HazardSlotIndex = std::numeric_limits<int>::max();
3913   for (auto &CS : CSI) {
3914     Register Reg = CS.getReg();
3915     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
3916 
3917     // Create a hazard slot as we switch between GPR and FPR CSRs.
3918     if (AFI->hasStackHazardSlotIndex() &&
3919         (!LastReg || !AArch64InstrInfo::isFpOrNEON(LastReg)) &&
3920         AArch64InstrInfo::isFpOrNEON(Reg)) {
3921       assert(HazardSlotIndex == std::numeric_limits<int>::max() &&
3922              "Unexpected register order for hazard slot");
3923       HazardSlotIndex = MFI.CreateStackObject(StackHazardSize, Align(8), true);
3924       LLVM_DEBUG(dbgs() << "Created CSR Hazard at slot " << HazardSlotIndex
3925                         << "\n");
3926       AFI->setStackHazardCSRSlotIndex(HazardSlotIndex);
3927       if ((unsigned)HazardSlotIndex < MinCSFrameIndex)
3928         MinCSFrameIndex = HazardSlotIndex;
3929       if ((unsigned)HazardSlotIndex > MaxCSFrameIndex)
3930         MaxCSFrameIndex = HazardSlotIndex;
3931     }
3932 
3933     unsigned Size = RegInfo->getSpillSize(*RC);
3934     Align Alignment(RegInfo->getSpillAlign(*RC));
3935     int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
3936     CS.setFrameIdx(FrameIdx);
3937 
3938     if ((unsigned)FrameIdx < MinCSFrameIndex)
3939       MinCSFrameIndex = FrameIdx;
3940     if ((unsigned)FrameIdx > MaxCSFrameIndex)
3941       MaxCSFrameIndex = FrameIdx;
3942 
3943     // Grab 8 bytes below FP for the extended asynchronous frame info.
3944     if (hasFP(MF) && AFI->hasSwiftAsyncContext() && !UsesWinAAPCS &&
3945         Reg == AArch64::FP) {
3946       FrameIdx = MFI.CreateStackObject(8, Alignment, true);
3947       AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
3948       if ((unsigned)FrameIdx < MinCSFrameIndex)
3949         MinCSFrameIndex = FrameIdx;
3950       if ((unsigned)FrameIdx > MaxCSFrameIndex)
3951         MaxCSFrameIndex = FrameIdx;
3952     }
3953     LastReg = Reg;
3954   }
3955 
3956   // Add hazard slot in the case where no FPR CSRs are present.
3957   if (AFI->hasStackHazardSlotIndex() &&
3958       HazardSlotIndex == std::numeric_limits<int>::max()) {
3959     HazardSlotIndex = MFI.CreateStackObject(StackHazardSize, Align(8), true);
3960     LLVM_DEBUG(dbgs() << "Created CSR Hazard at slot " << HazardSlotIndex
3961                       << "\n");
3962     AFI->setStackHazardCSRSlotIndex(HazardSlotIndex);
3963     if ((unsigned)HazardSlotIndex < MinCSFrameIndex)
3964       MinCSFrameIndex = HazardSlotIndex;
3965     if ((unsigned)HazardSlotIndex > MaxCSFrameIndex)
3966       MaxCSFrameIndex = HazardSlotIndex;
3967   }
3968 
3969   return true;
3970 }
3971 
3972 bool AArch64FrameLowering::enableStackSlotScavenging(
3973     const MachineFunction &MF) const {
3974   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3975   // If the function has streaming-mode changes, don't scavenge a
3976   // spillslot in the callee-save area, as that might require an
3977   // 'addvl' in the streaming-mode-changing call-sequence when the
3978   // function doesn't use a FP.
3979   if (AFI->hasStreamingModeChanges() && !hasFP(MF))
3980     return false;
3981   // Don't allow register salvaging with hazard slots, in case it moves objects
3982   // into the wrong place.
3983   if (AFI->hasStackHazardSlotIndex())
3984     return false;
3985   return AFI->hasCalleeSaveStackFreeSpace();
3986 }
3987 
3988 /// returns true if there are any SVE callee saves.
3989 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
3990                                       int &Min, int &Max) {
3991   Min = std::numeric_limits<int>::max();
3992   Max = std::numeric_limits<int>::min();
3993 
3994   if (!MFI.isCalleeSavedInfoValid())
3995     return false;
3996 
3997   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
3998   for (auto &CS : CSI) {
3999     if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
4000         AArch64::PPRRegClass.contains(CS.getReg())) {
4001       assert((Max == std::numeric_limits<int>::min() ||
4002               Max + 1 == CS.getFrameIdx()) &&
4003              "SVE CalleeSaves are not consecutive");
4004 
4005       Min = std::min(Min, CS.getFrameIdx());
4006       Max = std::max(Max, CS.getFrameIdx());
4007     }
4008   }
4009   return Min != std::numeric_limits<int>::max();
4010 }
4011 
4012 // Process all the SVE stack objects and determine offsets for each
4013 // object. If AssignOffsets is true, the offsets get assigned.
4014 // Fills in the first and last callee-saved frame indices into
4015 // Min/MaxCSFrameIndex, respectively.
4016 // Returns the size of the stack.
4017 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
4018                                               int &MinCSFrameIndex,
4019                                               int &MaxCSFrameIndex,
4020                                               bool AssignOffsets) {
4021 #ifndef NDEBUG
4022   // First process all fixed stack objects.
4023   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
4024     assert(MFI.getStackID(I) != TargetStackID::ScalableVector &&
4025            "SVE vectors should never be passed on the stack by value, only by "
4026            "reference.");
4027 #endif
4028 
4029   auto Assign = [&MFI](int FI, int64_t Offset) {
4030     LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
4031     MFI.setObjectOffset(FI, Offset);
4032   };
4033 
4034   int64_t Offset = 0;
4035 
4036   // Then process all callee saved slots.
4037   if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
4038     // Assign offsets to the callee save slots.
4039     for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
4040       Offset += MFI.getObjectSize(I);
4041       Offset = alignTo(Offset, MFI.getObjectAlign(I));
4042       if (AssignOffsets)
4043         Assign(I, -Offset);
4044     }
4045   }
4046 
4047   // Ensure that the Callee-save area is aligned to 16bytes.
4048   Offset = alignTo(Offset, Align(16U));
4049 
4050   // Create a buffer of SVE objects to allocate and sort it.
4051   SmallVector<int, 8> ObjectsToAllocate;
4052   // If we have a stack protector, and we've previously decided that we have SVE
4053   // objects on the stack and thus need it to go in the SVE stack area, then it
4054   // needs to go first.
4055   int StackProtectorFI = -1;
4056   if (MFI.hasStackProtectorIndex()) {
4057     StackProtectorFI = MFI.getStackProtectorIndex();
4058     if (MFI.getStackID(StackProtectorFI) == TargetStackID::ScalableVector)
4059       ObjectsToAllocate.push_back(StackProtectorFI);
4060   }
4061   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
4062     unsigned StackID = MFI.getStackID(I);
4063     if (StackID != TargetStackID::ScalableVector)
4064       continue;
4065     if (I == StackProtectorFI)
4066       continue;
4067     if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
4068       continue;
4069     if (MFI.isDeadObjectIndex(I))
4070       continue;
4071 
4072     ObjectsToAllocate.push_back(I);
4073   }
4074 
4075   // Allocate all SVE locals and spills
4076   for (unsigned FI : ObjectsToAllocate) {
4077     Align Alignment = MFI.getObjectAlign(FI);
4078     // FIXME: Given that the length of SVE vectors is not necessarily a power of
4079     // two, we'd need to align every object dynamically at runtime if the
4080     // alignment is larger than 16. This is not yet supported.
4081     if (Alignment > Align(16))
4082       report_fatal_error(
4083           "Alignment of scalable vectors > 16 bytes is not yet supported");
4084 
4085     Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment);
4086     if (AssignOffsets)
4087       Assign(FI, -Offset);
4088   }
4089 
4090   return Offset;
4091 }
4092 
4093 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
4094     MachineFrameInfo &MFI) const {
4095   int MinCSFrameIndex, MaxCSFrameIndex;
4096   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
4097 }
4098 
4099 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
4100     MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
4101   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
4102                                         true);
4103 }
4104 
4105 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
4106     MachineFunction &MF, RegScavenger *RS) const {
4107   MachineFrameInfo &MFI = MF.getFrameInfo();
4108 
4109   assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
4110          "Upwards growing stack unsupported");
4111 
4112   int MinCSFrameIndex, MaxCSFrameIndex;
4113   int64_t SVEStackSize =
4114       assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
4115 
4116   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
4117   AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
4118   AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
4119 
4120   // If this function isn't doing Win64-style C++ EH, we don't need to do
4121   // anything.
4122   if (!MF.hasEHFunclets())
4123     return;
4124   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
4125   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
4126 
4127   MachineBasicBlock &MBB = MF.front();
4128   auto MBBI = MBB.begin();
4129   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
4130     ++MBBI;
4131 
4132   // Create an UnwindHelp object.
4133   // The UnwindHelp object is allocated at the start of the fixed object area
4134   int64_t FixedObject =
4135       getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false);
4136   int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8,
4137                                            /*SPOffset*/ -FixedObject,
4138                                            /*IsImmutable=*/false);
4139   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
4140 
4141   // We need to store -2 into the UnwindHelp object at the start of the
4142   // function.
4143   DebugLoc DL;
4144   RS->enterBasicBlockEnd(MBB);
4145   RS->backward(MBBI);
4146   Register DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
4147   assert(DstReg && "There must be a free register after frame setup");
4148   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
4149   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
4150       .addReg(DstReg, getKillRegState(true))
4151       .addFrameIndex(UnwindHelpFI)
4152       .addImm(0);
4153 }
4154 
4155 namespace {
4156 struct TagStoreInstr {
4157   MachineInstr *MI;
4158   int64_t Offset, Size;
4159   explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)
4160       : MI(MI), Offset(Offset), Size(Size) {}
4161 };
4162 
4163 class TagStoreEdit {
4164   MachineFunction *MF;
4165   MachineBasicBlock *MBB;
4166   MachineRegisterInfo *MRI;
4167   // Tag store instructions that are being replaced.
4168   SmallVector<TagStoreInstr, 8> TagStores;
4169   // Combined memref arguments of the above instructions.
4170   SmallVector<MachineMemOperand *, 8> CombinedMemRefs;
4171 
4172   // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
4173   // FrameRegOffset + Size) with the address tag of SP.
4174   Register FrameReg;
4175   StackOffset FrameRegOffset;
4176   int64_t Size;
4177   // If not std::nullopt, move FrameReg to (FrameReg + FrameRegUpdate) at the
4178   // end.
4179   std::optional<int64_t> FrameRegUpdate;
4180   // MIFlags for any FrameReg updating instructions.
4181   unsigned FrameRegUpdateFlags;
4182 
4183   // Use zeroing instruction variants.
4184   bool ZeroData;
4185   DebugLoc DL;
4186 
4187   void emitUnrolled(MachineBasicBlock::iterator InsertI);
4188   void emitLoop(MachineBasicBlock::iterator InsertI);
4189 
4190 public:
4191   TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)
4192       : MBB(MBB), ZeroData(ZeroData) {
4193     MF = MBB->getParent();
4194     MRI = &MF->getRegInfo();
4195   }
4196   // Add an instruction to be replaced. Instructions must be added in the
4197   // ascending order of Offset, and have to be adjacent.
4198   void addInstruction(TagStoreInstr I) {
4199     assert((TagStores.empty() ||
4200             TagStores.back().Offset + TagStores.back().Size == I.Offset) &&
4201            "Non-adjacent tag store instructions.");
4202     TagStores.push_back(I);
4203   }
4204   void clear() { TagStores.clear(); }
4205   // Emit equivalent code at the given location, and erase the current set of
4206   // instructions. May skip if the replacement is not profitable. May invalidate
4207   // the input iterator and replace it with a valid one.
4208   void emitCode(MachineBasicBlock::iterator &InsertI,
4209                 const AArch64FrameLowering *TFI, bool TryMergeSPUpdate);
4210 };
4211 
4212 void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {
4213   const AArch64InstrInfo *TII =
4214       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
4215 
4216   const int64_t kMinOffset = -256 * 16;
4217   const int64_t kMaxOffset = 255 * 16;
4218 
4219   Register BaseReg = FrameReg;
4220   int64_t BaseRegOffsetBytes = FrameRegOffset.getFixed();
4221   if (BaseRegOffsetBytes < kMinOffset ||
4222       BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset ||
4223       // BaseReg can be FP, which is not necessarily aligned to 16-bytes. In
4224       // that case, BaseRegOffsetBytes will not be aligned to 16 bytes, which
4225       // is required for the offset of ST2G.
4226       BaseRegOffsetBytes % 16 != 0) {
4227     Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
4228     emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,
4229                     StackOffset::getFixed(BaseRegOffsetBytes), TII);
4230     BaseReg = ScratchReg;
4231     BaseRegOffsetBytes = 0;
4232   }
4233 
4234   MachineInstr *LastI = nullptr;
4235   while (Size) {
4236     int64_t InstrSize = (Size > 16) ? 32 : 16;
4237     unsigned Opcode =
4238         InstrSize == 16
4239             ? (ZeroData ? AArch64::STZGi : AArch64::STGi)
4240             : (ZeroData ? AArch64::STZ2Gi : AArch64::ST2Gi);
4241     assert(BaseRegOffsetBytes % 16 == 0);
4242     MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))
4243                           .addReg(AArch64::SP)
4244                           .addReg(BaseReg)
4245                           .addImm(BaseRegOffsetBytes / 16)
4246                           .setMemRefs(CombinedMemRefs);
4247     // A store to [BaseReg, #0] should go last for an opportunity to fold the
4248     // final SP adjustment in the epilogue.
4249     if (BaseRegOffsetBytes == 0)
4250       LastI = I;
4251     BaseRegOffsetBytes += InstrSize;
4252     Size -= InstrSize;
4253   }
4254 
4255   if (LastI)
4256     MBB->splice(InsertI, MBB, LastI);
4257 }
4258 
4259 void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {
4260   const AArch64InstrInfo *TII =
4261       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
4262 
4263   Register BaseReg = FrameRegUpdate
4264                          ? FrameReg
4265                          : MRI->createVirtualRegister(&AArch64::GPR64RegClass);
4266   Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
4267 
4268   emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);
4269 
4270   int64_t LoopSize = Size;
4271   // If the loop size is not a multiple of 32, split off one 16-byte store at
4272   // the end to fold BaseReg update into.
4273   if (FrameRegUpdate && *FrameRegUpdate)
4274     LoopSize -= LoopSize % 32;
4275   MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,
4276                                 TII->get(ZeroData ? AArch64::STZGloop_wback
4277                                                   : AArch64::STGloop_wback))
4278                             .addDef(SizeReg)
4279                             .addDef(BaseReg)
4280                             .addImm(LoopSize)
4281                             .addReg(BaseReg)
4282                             .setMemRefs(CombinedMemRefs);
4283   if (FrameRegUpdate)
4284     LoopI->setFlags(FrameRegUpdateFlags);
4285 
4286   int64_t ExtraBaseRegUpdate =
4287       FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getFixed() - Size) : 0;
4288   if (LoopSize < Size) {
4289     assert(FrameRegUpdate);
4290     assert(Size - LoopSize == 16);
4291     // Tag 16 more bytes at BaseReg and update BaseReg.
4292     BuildMI(*MBB, InsertI, DL,
4293             TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))
4294         .addDef(BaseReg)
4295         .addReg(BaseReg)
4296         .addReg(BaseReg)
4297         .addImm(1 + ExtraBaseRegUpdate / 16)
4298         .setMemRefs(CombinedMemRefs)
4299         .setMIFlags(FrameRegUpdateFlags);
4300   } else if (ExtraBaseRegUpdate) {
4301     // Update BaseReg.
4302     BuildMI(
4303         *MBB, InsertI, DL,
4304         TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))
4305         .addDef(BaseReg)
4306         .addReg(BaseReg)
4307         .addImm(std::abs(ExtraBaseRegUpdate))
4308         .addImm(0)
4309         .setMIFlags(FrameRegUpdateFlags);
4310   }
4311 }
4312 
4313 // Check if *II is a register update that can be merged into STGloop that ends
4314 // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
4315 // end of the loop.
4316 bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,
4317                        int64_t Size, int64_t *TotalOffset) {
4318   MachineInstr &MI = *II;
4319   if ((MI.getOpcode() == AArch64::ADDXri ||
4320        MI.getOpcode() == AArch64::SUBXri) &&
4321       MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {
4322     unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());
4323     int64_t Offset = MI.getOperand(2).getImm() << Shift;
4324     if (MI.getOpcode() == AArch64::SUBXri)
4325       Offset = -Offset;
4326     int64_t AbsPostOffset = std::abs(Offset - Size);
4327     const int64_t kMaxOffset =
4328         0xFFF; // Max encoding for unshifted ADDXri / SUBXri
4329     if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) {
4330       *TotalOffset = Offset;
4331       return true;
4332     }
4333   }
4334   return false;
4335 }
4336 
4337 void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,
4338                   SmallVectorImpl<MachineMemOperand *> &MemRefs) {
4339   MemRefs.clear();
4340   for (auto &TS : TSE) {
4341     MachineInstr *MI = TS.MI;
4342     // An instruction without memory operands may access anything. Be
4343     // conservative and return an empty list.
4344     if (MI->memoperands_empty()) {
4345       MemRefs.clear();
4346       return;
4347     }
4348     MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());
4349   }
4350 }
4351 
4352 void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,
4353                             const AArch64FrameLowering *TFI,
4354                             bool TryMergeSPUpdate) {
4355   if (TagStores.empty())
4356     return;
4357   TagStoreInstr &FirstTagStore = TagStores[0];
4358   TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];
4359   Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;
4360   DL = TagStores[0].MI->getDebugLoc();
4361 
4362   Register Reg;
4363   FrameRegOffset = TFI->resolveFrameOffsetReference(
4364       *MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg,
4365       /*PreferFP=*/false, /*ForSimm=*/true);
4366   FrameReg = Reg;
4367   FrameRegUpdate = std::nullopt;
4368 
4369   mergeMemRefs(TagStores, CombinedMemRefs);
4370 
4371   LLVM_DEBUG({
4372     dbgs() << "Replacing adjacent STG instructions:\n";
4373     for (const auto &Instr : TagStores) {
4374       dbgs() << "  " << *Instr.MI;
4375     }
4376   });
4377 
4378   // Size threshold where a loop becomes shorter than a linear sequence of
4379   // tagging instructions.
4380   const int kSetTagLoopThreshold = 176;
4381   if (Size < kSetTagLoopThreshold) {
4382     if (TagStores.size() < 2)
4383       return;
4384     emitUnrolled(InsertI);
4385   } else {
4386     MachineInstr *UpdateInstr = nullptr;
4387     int64_t TotalOffset = 0;
4388     if (TryMergeSPUpdate) {
4389       // See if we can merge base register update into the STGloop.
4390       // This is done in AArch64LoadStoreOptimizer for "normal" stores,
4391       // but STGloop is way too unusual for that, and also it only
4392       // realistically happens in function epilogue. Also, STGloop is expanded
4393       // before that pass.
4394       if (InsertI != MBB->end() &&
4395           canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getFixed() + Size,
4396                             &TotalOffset)) {
4397         UpdateInstr = &*InsertI++;
4398         LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n  "
4399                           << *UpdateInstr);
4400       }
4401     }
4402 
4403     if (!UpdateInstr && TagStores.size() < 2)
4404       return;
4405 
4406     if (UpdateInstr) {
4407       FrameRegUpdate = TotalOffset;
4408       FrameRegUpdateFlags = UpdateInstr->getFlags();
4409     }
4410     emitLoop(InsertI);
4411     if (UpdateInstr)
4412       UpdateInstr->eraseFromParent();
4413   }
4414 
4415   for (auto &TS : TagStores)
4416     TS.MI->eraseFromParent();
4417 }
4418 
4419 bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,
4420                                         int64_t &Size, bool &ZeroData) {
4421   MachineFunction &MF = *MI.getParent()->getParent();
4422   const MachineFrameInfo &MFI = MF.getFrameInfo();
4423 
4424   unsigned Opcode = MI.getOpcode();
4425   ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGi ||
4426               Opcode == AArch64::STZ2Gi);
4427 
4428   if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {
4429     if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())
4430       return false;
4431     if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())
4432       return false;
4433     Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());
4434     Size = MI.getOperand(2).getImm();
4435     return true;
4436   }
4437 
4438   if (Opcode == AArch64::STGi || Opcode == AArch64::STZGi)
4439     Size = 16;
4440   else if (Opcode == AArch64::ST2Gi || Opcode == AArch64::STZ2Gi)
4441     Size = 32;
4442   else
4443     return false;
4444 
4445   if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())
4446     return false;
4447 
4448   Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +
4449            16 * MI.getOperand(2).getImm();
4450   return true;
4451 }
4452 
4453 // Detect a run of memory tagging instructions for adjacent stack frame slots,
4454 // and replace them with a shorter instruction sequence:
4455 // * replace STG + STG with ST2G
4456 // * replace STGloop + STGloop with STGloop
4457 // This code needs to run when stack slot offsets are already known, but before
4458 // FrameIndex operands in STG instructions are eliminated.
4459 MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II,
4460                                                 const AArch64FrameLowering *TFI,
4461                                                 RegScavenger *RS) {
4462   bool FirstZeroData;
4463   int64_t Size, Offset;
4464   MachineInstr &MI = *II;
4465   MachineBasicBlock *MBB = MI.getParent();
4466   MachineBasicBlock::iterator NextI = ++II;
4467   if (&MI == &MBB->instr_back())
4468     return II;
4469   if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))
4470     return II;
4471 
4472   SmallVector<TagStoreInstr, 4> Instrs;
4473   Instrs.emplace_back(&MI, Offset, Size);
4474 
4475   constexpr int kScanLimit = 10;
4476   int Count = 0;
4477   for (MachineBasicBlock::iterator E = MBB->end();
4478        NextI != E && Count < kScanLimit; ++NextI) {
4479     MachineInstr &MI = *NextI;
4480     bool ZeroData;
4481     int64_t Size, Offset;
4482     // Collect instructions that update memory tags with a FrameIndex operand
4483     // and (when applicable) constant size, and whose output registers are dead
4484     // (the latter is almost always the case in practice). Since these
4485     // instructions effectively have no inputs or outputs, we are free to skip
4486     // any non-aliasing instructions in between without tracking used registers.
4487     if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {
4488       if (ZeroData != FirstZeroData)
4489         break;
4490       Instrs.emplace_back(&MI, Offset, Size);
4491       continue;
4492     }
4493 
4494     // Only count non-transient, non-tagging instructions toward the scan
4495     // limit.
4496     if (!MI.isTransient())
4497       ++Count;
4498 
4499     // Just in case, stop before the epilogue code starts.
4500     if (MI.getFlag(MachineInstr::FrameSetup) ||
4501         MI.getFlag(MachineInstr::FrameDestroy))
4502       break;
4503 
4504     // Reject anything that may alias the collected instructions.
4505     if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects())
4506       break;
4507   }
4508 
4509   // New code will be inserted after the last tagging instruction we've found.
4510   MachineBasicBlock::iterator InsertI = Instrs.back().MI;
4511 
4512   // All the gathered stack tag instructions are merged and placed after
4513   // last tag store in the list. The check should be made if the nzcv
4514   // flag is live at the point where we are trying to insert. Otherwise
4515   // the nzcv flag might get clobbered if any stg loops are present.
4516 
4517   // FIXME : This approach of bailing out from merge is conservative in
4518   // some ways like even if stg loops are not present after merge the
4519   // insert list, this liveness check is done (which is not needed).
4520   LivePhysRegs LiveRegs(*(MBB->getParent()->getSubtarget().getRegisterInfo()));
4521   LiveRegs.addLiveOuts(*MBB);
4522   for (auto I = MBB->rbegin();; ++I) {
4523     MachineInstr &MI = *I;
4524     if (MI == InsertI)
4525       break;
4526     LiveRegs.stepBackward(*I);
4527   }
4528   InsertI++;
4529   if (LiveRegs.contains(AArch64::NZCV))
4530     return InsertI;
4531 
4532   llvm::stable_sort(Instrs,
4533                     [](const TagStoreInstr &Left, const TagStoreInstr &Right) {
4534                       return Left.Offset < Right.Offset;
4535                     });
4536 
4537   // Make sure that we don't have any overlapping stores.
4538   int64_t CurOffset = Instrs[0].Offset;
4539   for (auto &Instr : Instrs) {
4540     if (CurOffset > Instr.Offset)
4541       return NextI;
4542     CurOffset = Instr.Offset + Instr.Size;
4543   }
4544 
4545   // Find contiguous runs of tagged memory and emit shorter instruction
4546   // sequencies for them when possible.
4547   TagStoreEdit TSE(MBB, FirstZeroData);
4548   std::optional<int64_t> EndOffset;
4549   for (auto &Instr : Instrs) {
4550     if (EndOffset && *EndOffset != Instr.Offset) {
4551       // Found a gap.
4552       TSE.emitCode(InsertI, TFI, /*TryMergeSPUpdate = */ false);
4553       TSE.clear();
4554     }
4555 
4556     TSE.addInstruction(Instr);
4557     EndOffset = Instr.Offset + Instr.Size;
4558   }
4559 
4560   const MachineFunction *MF = MBB->getParent();
4561   // Multiple FP/SP updates in a loop cannot be described by CFI instructions.
4562   TSE.emitCode(
4563       InsertI, TFI, /*TryMergeSPUpdate = */
4564       !MF->getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(*MF));
4565 
4566   return InsertI;
4567 }
4568 } // namespace
4569 
4570 MachineBasicBlock::iterator emitVGSaveRestore(MachineBasicBlock::iterator II,
4571                                               const AArch64FrameLowering *TFI) {
4572   MachineInstr &MI = *II;
4573   MachineBasicBlock *MBB = MI.getParent();
4574   MachineFunction *MF = MBB->getParent();
4575 
4576   if (MI.getOpcode() != AArch64::VGSavePseudo &&
4577       MI.getOpcode() != AArch64::VGRestorePseudo)
4578     return II;
4579 
4580   SMEAttrs FuncAttrs(MF->getFunction());
4581   bool LocallyStreaming =
4582       FuncAttrs.hasStreamingBody() && !FuncAttrs.hasStreamingInterface();
4583   const AArch64FunctionInfo *AFI = MF->getInfo<AArch64FunctionInfo>();
4584   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
4585   const AArch64InstrInfo *TII =
4586       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
4587 
4588   int64_t VGFrameIdx =
4589       LocallyStreaming ? AFI->getStreamingVGIdx() : AFI->getVGIdx();
4590   assert(VGFrameIdx != std::numeric_limits<int>::max() &&
4591          "Expected FrameIdx for VG");
4592 
4593   unsigned CFIIndex;
4594   if (MI.getOpcode() == AArch64::VGSavePseudo) {
4595     const MachineFrameInfo &MFI = MF->getFrameInfo();
4596     int64_t Offset =
4597         MFI.getObjectOffset(VGFrameIdx) - TFI->getOffsetOfLocalArea();
4598     CFIIndex = MF->addFrameInst(MCCFIInstruction::createOffset(
4599         nullptr, TRI->getDwarfRegNum(AArch64::VG, true), Offset));
4600   } else
4601     CFIIndex = MF->addFrameInst(MCCFIInstruction::createRestore(
4602         nullptr, TRI->getDwarfRegNum(AArch64::VG, true)));
4603 
4604   MachineInstr *UnwindInst = BuildMI(*MBB, II, II->getDebugLoc(),
4605                                      TII->get(TargetOpcode::CFI_INSTRUCTION))
4606                                  .addCFIIndex(CFIIndex);
4607 
4608   MI.eraseFromParent();
4609   return UnwindInst->getIterator();
4610 }
4611 
4612 void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(
4613     MachineFunction &MF, RegScavenger *RS = nullptr) const {
4614   for (auto &BB : MF)
4615     for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();) {
4616       if (requiresSaveVG(MF))
4617         II = emitVGSaveRestore(II, this);
4618       if (StackTaggingMergeSetTag)
4619         II = tryMergeAdjacentSTG(II, this, RS);
4620     }
4621 }
4622 
4623 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
4624 /// before the update.  This is easily retrieved as it is exactly the offset
4625 /// that is set in processFunctionBeforeFrameFinalized.
4626 StackOffset AArch64FrameLowering::getFrameIndexReferencePreferSP(
4627     const MachineFunction &MF, int FI, Register &FrameReg,
4628     bool IgnoreSPUpdates) const {
4629   const MachineFrameInfo &MFI = MF.getFrameInfo();
4630   if (IgnoreSPUpdates) {
4631     LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
4632                       << MFI.getObjectOffset(FI) << "\n");
4633     FrameReg = AArch64::SP;
4634     return StackOffset::getFixed(MFI.getObjectOffset(FI));
4635   }
4636 
4637   // Go to common code if we cannot provide sp + offset.
4638   if (MFI.hasVarSizedObjects() ||
4639       MF.getInfo<AArch64FunctionInfo>()->getStackSizeSVE() ||
4640       MF.getSubtarget().getRegisterInfo()->hasStackRealignment(MF))
4641     return getFrameIndexReference(MF, FI, FrameReg);
4642 
4643   FrameReg = AArch64::SP;
4644   return getStackOffset(MF, MFI.getObjectOffset(FI));
4645 }
4646 
4647 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
4648 /// the parent's frame pointer
4649 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
4650     const MachineFunction &MF) const {
4651   return 0;
4652 }
4653 
4654 /// Funclets only need to account for space for the callee saved registers,
4655 /// as the locals are accounted for in the parent's stack frame.
4656 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
4657     const MachineFunction &MF) const {
4658   // This is the size of the pushed CSRs.
4659   unsigned CSSize =
4660       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
4661   // This is the amount of stack a funclet needs to allocate.
4662   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
4663                  getStackAlign());
4664 }
4665 
4666 namespace {
4667 struct FrameObject {
4668   bool IsValid = false;
4669   // Index of the object in MFI.
4670   int ObjectIndex = 0;
4671   // Group ID this object belongs to.
4672   int GroupIndex = -1;
4673   // This object should be placed first (closest to SP).
4674   bool ObjectFirst = false;
4675   // This object's group (which always contains the object with
4676   // ObjectFirst==true) should be placed first.
4677   bool GroupFirst = false;
4678 
4679   // Used to distinguish between FP and GPR accesses. The values are decided so
4680   // that they sort FPR < Hazard < GPR and they can be or'd together.
4681   unsigned Accesses = 0;
4682   enum { AccessFPR = 1, AccessHazard = 2, AccessGPR = 4 };
4683 };
4684 
4685 class GroupBuilder {
4686   SmallVector<int, 8> CurrentMembers;
4687   int NextGroupIndex = 0;
4688   std::vector<FrameObject> &Objects;
4689 
4690 public:
4691   GroupBuilder(std::vector<FrameObject> &Objects) : Objects(Objects) {}
4692   void AddMember(int Index) { CurrentMembers.push_back(Index); }
4693   void EndCurrentGroup() {
4694     if (CurrentMembers.size() > 1) {
4695       // Create a new group with the current member list. This might remove them
4696       // from their pre-existing groups. That's OK, dealing with overlapping
4697       // groups is too hard and unlikely to make a difference.
4698       LLVM_DEBUG(dbgs() << "group:");
4699       for (int Index : CurrentMembers) {
4700         Objects[Index].GroupIndex = NextGroupIndex;
4701         LLVM_DEBUG(dbgs() << " " << Index);
4702       }
4703       LLVM_DEBUG(dbgs() << "\n");
4704       NextGroupIndex++;
4705     }
4706     CurrentMembers.clear();
4707   }
4708 };
4709 
4710 bool FrameObjectCompare(const FrameObject &A, const FrameObject &B) {
4711   // Objects at a lower index are closer to FP; objects at a higher index are
4712   // closer to SP.
4713   //
4714   // For consistency in our comparison, all invalid objects are placed
4715   // at the end. This also allows us to stop walking when we hit the
4716   // first invalid item after it's all sorted.
4717   //
4718   // If we want to include a stack hazard region, order FPR accesses < the
4719   // hazard object < GPRs accesses in order to create a separation between the
4720   // two. For the Accesses field 1 = FPR, 2 = Hazard Object, 4 = GPR.
4721   //
4722   // Otherwise the "first" object goes first (closest to SP), followed by the
4723   // members of the "first" group.
4724   //
4725   // The rest are sorted by the group index to keep the groups together.
4726   // Higher numbered groups are more likely to be around longer (i.e. untagged
4727   // in the function epilogue and not at some earlier point). Place them closer
4728   // to SP.
4729   //
4730   // If all else equal, sort by the object index to keep the objects in the
4731   // original order.
4732   return std::make_tuple(!A.IsValid, A.Accesses, A.ObjectFirst, A.GroupFirst,
4733                          A.GroupIndex, A.ObjectIndex) <
4734          std::make_tuple(!B.IsValid, B.Accesses, B.ObjectFirst, B.GroupFirst,
4735                          B.GroupIndex, B.ObjectIndex);
4736 }
4737 } // namespace
4738 
4739 void AArch64FrameLowering::orderFrameObjects(
4740     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
4741   if (!OrderFrameObjects || ObjectsToAllocate.empty())
4742     return;
4743 
4744   const AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
4745   const MachineFrameInfo &MFI = MF.getFrameInfo();
4746   std::vector<FrameObject> FrameObjects(MFI.getObjectIndexEnd());
4747   for (auto &Obj : ObjectsToAllocate) {
4748     FrameObjects[Obj].IsValid = true;
4749     FrameObjects[Obj].ObjectIndex = Obj;
4750   }
4751 
4752   // Identify FPR vs GPR slots for hazards, and stack slots that are tagged at
4753   // the same time.
4754   GroupBuilder GB(FrameObjects);
4755   for (auto &MBB : MF) {
4756     for (auto &MI : MBB) {
4757       if (MI.isDebugInstr())
4758         continue;
4759 
4760       if (AFI.hasStackHazardSlotIndex()) {
4761         std::optional<int> FI = getLdStFrameID(MI, MFI);
4762         if (FI && *FI >= 0 && *FI < (int)FrameObjects.size()) {
4763           if (MFI.getStackID(*FI) == TargetStackID::ScalableVector ||
4764               AArch64InstrInfo::isFpOrNEON(MI))
4765             FrameObjects[*FI].Accesses |= FrameObject::AccessFPR;
4766           else
4767             FrameObjects[*FI].Accesses |= FrameObject::AccessGPR;
4768         }
4769       }
4770 
4771       int OpIndex;
4772       switch (MI.getOpcode()) {
4773       case AArch64::STGloop:
4774       case AArch64::STZGloop:
4775         OpIndex = 3;
4776         break;
4777       case AArch64::STGi:
4778       case AArch64::STZGi:
4779       case AArch64::ST2Gi:
4780       case AArch64::STZ2Gi:
4781         OpIndex = 1;
4782         break;
4783       default:
4784         OpIndex = -1;
4785       }
4786 
4787       int TaggedFI = -1;
4788       if (OpIndex >= 0) {
4789         const MachineOperand &MO = MI.getOperand(OpIndex);
4790         if (MO.isFI()) {
4791           int FI = MO.getIndex();
4792           if (FI >= 0 && FI < MFI.getObjectIndexEnd() &&
4793               FrameObjects[FI].IsValid)
4794             TaggedFI = FI;
4795         }
4796       }
4797 
4798       // If this is a stack tagging instruction for a slot that is not part of a
4799       // group yet, either start a new group or add it to the current one.
4800       if (TaggedFI >= 0)
4801         GB.AddMember(TaggedFI);
4802       else
4803         GB.EndCurrentGroup();
4804     }
4805     // Groups should never span multiple basic blocks.
4806     GB.EndCurrentGroup();
4807   }
4808 
4809   if (AFI.hasStackHazardSlotIndex()) {
4810     FrameObjects[AFI.getStackHazardSlotIndex()].Accesses =
4811         FrameObject::AccessHazard;
4812     // If a stack object is unknown or both GPR and FPR, sort it into GPR.
4813     for (auto &Obj : FrameObjects)
4814       if (!Obj.Accesses ||
4815           Obj.Accesses == (FrameObject::AccessGPR | FrameObject::AccessFPR))
4816         Obj.Accesses = FrameObject::AccessGPR;
4817   }
4818 
4819   // If the function's tagged base pointer is pinned to a stack slot, we want to
4820   // put that slot first when possible. This will likely place it at SP + 0,
4821   // and save one instruction when generating the base pointer because IRG does
4822   // not allow an immediate offset.
4823   std::optional<int> TBPI = AFI.getTaggedBasePointerIndex();
4824   if (TBPI) {
4825     FrameObjects[*TBPI].ObjectFirst = true;
4826     FrameObjects[*TBPI].GroupFirst = true;
4827     int FirstGroupIndex = FrameObjects[*TBPI].GroupIndex;
4828     if (FirstGroupIndex >= 0)
4829       for (FrameObject &Object : FrameObjects)
4830         if (Object.GroupIndex == FirstGroupIndex)
4831           Object.GroupFirst = true;
4832   }
4833 
4834   llvm::stable_sort(FrameObjects, FrameObjectCompare);
4835 
4836   int i = 0;
4837   for (auto &Obj : FrameObjects) {
4838     // All invalid items are sorted at the end, so it's safe to stop.
4839     if (!Obj.IsValid)
4840       break;
4841     ObjectsToAllocate[i++] = Obj.ObjectIndex;
4842   }
4843 
4844   LLVM_DEBUG({
4845     dbgs() << "Final frame order:\n";
4846     for (auto &Obj : FrameObjects) {
4847       if (!Obj.IsValid)
4848         break;
4849       dbgs() << "  " << Obj.ObjectIndex << ": group " << Obj.GroupIndex;
4850       if (Obj.ObjectFirst)
4851         dbgs() << ", first";
4852       if (Obj.GroupFirst)
4853         dbgs() << ", group-first";
4854       dbgs() << "\n";
4855     }
4856   });
4857 }
4858 
4859 /// Emit a loop to decrement SP until it is equal to TargetReg, with probes at
4860 /// least every ProbeSize bytes. Returns an iterator of the first instruction
4861 /// after the loop. The difference between SP and TargetReg must be an exact
4862 /// multiple of ProbeSize.
4863 MachineBasicBlock::iterator
4864 AArch64FrameLowering::inlineStackProbeLoopExactMultiple(
4865     MachineBasicBlock::iterator MBBI, int64_t ProbeSize,
4866     Register TargetReg) const {
4867   MachineBasicBlock &MBB = *MBBI->getParent();
4868   MachineFunction &MF = *MBB.getParent();
4869   const AArch64InstrInfo *TII =
4870       MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
4871   DebugLoc DL = MBB.findDebugLoc(MBBI);
4872 
4873   MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
4874   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
4875   MF.insert(MBBInsertPoint, LoopMBB);
4876   MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
4877   MF.insert(MBBInsertPoint, ExitMBB);
4878 
4879   // SUB SP, SP, #ProbeSize (or equivalent if ProbeSize is not encodable
4880   // in SUB).
4881   emitFrameOffset(*LoopMBB, LoopMBB->end(), DL, AArch64::SP, AArch64::SP,
4882                   StackOffset::getFixed(-ProbeSize), TII,
4883                   MachineInstr::FrameSetup);
4884   // STR XZR, [SP]
4885   BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::STRXui))
4886       .addReg(AArch64::XZR)
4887       .addReg(AArch64::SP)
4888       .addImm(0)
4889       .setMIFlags(MachineInstr::FrameSetup);
4890   // CMP SP, TargetReg
4891   BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::SUBSXrx64),
4892           AArch64::XZR)
4893       .addReg(AArch64::SP)
4894       .addReg(TargetReg)
4895       .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 0))
4896       .setMIFlags(MachineInstr::FrameSetup);
4897   // B.CC Loop
4898   BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::Bcc))
4899       .addImm(AArch64CC::NE)
4900       .addMBB(LoopMBB)
4901       .setMIFlags(MachineInstr::FrameSetup);
4902 
4903   LoopMBB->addSuccessor(ExitMBB);
4904   LoopMBB->addSuccessor(LoopMBB);
4905   // Synthesize the exit MBB.
4906   ExitMBB->splice(ExitMBB->end(), &MBB, MBBI, MBB.end());
4907   ExitMBB->transferSuccessorsAndUpdatePHIs(&MBB);
4908   MBB.addSuccessor(LoopMBB);
4909   // Update liveins.
4910   fullyRecomputeLiveIns({ExitMBB, LoopMBB});
4911 
4912   return ExitMBB->begin();
4913 }
4914 
4915 void AArch64FrameLowering::inlineStackProbeFixed(
4916     MachineBasicBlock::iterator MBBI, Register ScratchReg, int64_t FrameSize,
4917     StackOffset CFAOffset) const {
4918   MachineBasicBlock *MBB = MBBI->getParent();
4919   MachineFunction &MF = *MBB->getParent();
4920   const AArch64InstrInfo *TII =
4921       MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
4922   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
4923   bool EmitAsyncCFI = AFI->needsAsyncDwarfUnwindInfo(MF);
4924   bool HasFP = hasFP(MF);
4925 
4926   DebugLoc DL;
4927   int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();
4928   int64_t NumBlocks = FrameSize / ProbeSize;
4929   int64_t ResidualSize = FrameSize % ProbeSize;
4930 
4931   LLVM_DEBUG(dbgs() << "Stack probing: total " << FrameSize << " bytes, "
4932                     << NumBlocks << " blocks of " << ProbeSize
4933                     << " bytes, plus " << ResidualSize << " bytes\n");
4934 
4935   // Decrement SP by NumBlock * ProbeSize bytes, with either unrolled or
4936   // ordinary loop.
4937   if (NumBlocks <= AArch64::StackProbeMaxLoopUnroll) {
4938     for (int i = 0; i < NumBlocks; ++i) {
4939       // SUB SP, SP, #ProbeSize (or equivalent if ProbeSize is not
4940       // encodable in a SUB).
4941       emitFrameOffset(*MBB, MBBI, DL, AArch64::SP, AArch64::SP,
4942                       StackOffset::getFixed(-ProbeSize), TII,
4943                       MachineInstr::FrameSetup, false, false, nullptr,
4944                       EmitAsyncCFI && !HasFP, CFAOffset);
4945       CFAOffset += StackOffset::getFixed(ProbeSize);
4946       // STR XZR, [SP]
4947       BuildMI(*MBB, MBBI, DL, TII->get(AArch64::STRXui))
4948           .addReg(AArch64::XZR)
4949           .addReg(AArch64::SP)
4950           .addImm(0)
4951           .setMIFlags(MachineInstr::FrameSetup);
4952     }
4953   } else if (NumBlocks != 0) {
4954     // SUB ScratchReg, SP, #FrameSize (or equivalent if FrameSize is not
4955     // encodable in ADD). ScrathReg may temporarily become the CFA register.
4956     emitFrameOffset(*MBB, MBBI, DL, ScratchReg, AArch64::SP,
4957                     StackOffset::getFixed(-ProbeSize * NumBlocks), TII,
4958                     MachineInstr::FrameSetup, false, false, nullptr,
4959                     EmitAsyncCFI && !HasFP, CFAOffset);
4960     CFAOffset += StackOffset::getFixed(ProbeSize * NumBlocks);
4961     MBBI = inlineStackProbeLoopExactMultiple(MBBI, ProbeSize, ScratchReg);
4962     MBB = MBBI->getParent();
4963     if (EmitAsyncCFI && !HasFP) {
4964       // Set the CFA register back to SP.
4965       const AArch64RegisterInfo &RegInfo =
4966           *MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
4967       unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
4968       unsigned CFIIndex =
4969           MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
4970       BuildMI(*MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
4971           .addCFIIndex(CFIIndex)
4972           .setMIFlags(MachineInstr::FrameSetup);
4973     }
4974   }
4975 
4976   if (ResidualSize != 0) {
4977     // SUB SP, SP, #ResidualSize (or equivalent if ResidualSize is not encodable
4978     // in SUB).
4979     emitFrameOffset(*MBB, MBBI, DL, AArch64::SP, AArch64::SP,
4980                     StackOffset::getFixed(-ResidualSize), TII,
4981                     MachineInstr::FrameSetup, false, false, nullptr,
4982                     EmitAsyncCFI && !HasFP, CFAOffset);
4983     if (ResidualSize > AArch64::StackProbeMaxUnprobedStack) {
4984       // STR XZR, [SP]
4985       BuildMI(*MBB, MBBI, DL, TII->get(AArch64::STRXui))
4986           .addReg(AArch64::XZR)
4987           .addReg(AArch64::SP)
4988           .addImm(0)
4989           .setMIFlags(MachineInstr::FrameSetup);
4990     }
4991   }
4992 }
4993 
4994 void AArch64FrameLowering::inlineStackProbe(MachineFunction &MF,
4995                                             MachineBasicBlock &MBB) const {
4996   // Get the instructions that need to be replaced. We emit at most two of
4997   // these. Remember them in order to avoid complications coming from the need
4998   // to traverse the block while potentially creating more blocks.
4999   SmallVector<MachineInstr *, 4> ToReplace;
5000   for (MachineInstr &MI : MBB)
5001     if (MI.getOpcode() == AArch64::PROBED_STACKALLOC ||
5002         MI.getOpcode() == AArch64::PROBED_STACKALLOC_VAR)
5003       ToReplace.push_back(&MI);
5004 
5005   for (MachineInstr *MI : ToReplace) {
5006     if (MI->getOpcode() == AArch64::PROBED_STACKALLOC) {
5007       Register ScratchReg = MI->getOperand(0).getReg();
5008       int64_t FrameSize = MI->getOperand(1).getImm();
5009       StackOffset CFAOffset = StackOffset::get(MI->getOperand(2).getImm(),
5010                                                MI->getOperand(3).getImm());
5011       inlineStackProbeFixed(MI->getIterator(), ScratchReg, FrameSize,
5012                             CFAOffset);
5013     } else {
5014       assert(MI->getOpcode() == AArch64::PROBED_STACKALLOC_VAR &&
5015              "Stack probe pseudo-instruction expected");
5016       const AArch64InstrInfo *TII =
5017           MI->getMF()->getSubtarget<AArch64Subtarget>().getInstrInfo();
5018       Register TargetReg = MI->getOperand(0).getReg();
5019       (void)TII->probedStackAlloc(MI->getIterator(), TargetReg, true);
5020     }
5021     MI->eraseFromParent();
5022   }
5023 }
5024 
5025 struct StackAccess {
5026   enum AccessType {
5027     NotAccessed = 0, // Stack object not accessed by load/store instructions.
5028     GPR = 1 << 0,    // A general purpose register.
5029     PPR = 1 << 1,    // A predicate register.
5030     FPR = 1 << 2,    // A floating point/Neon/SVE register.
5031   };
5032 
5033   int Idx;
5034   StackOffset Offset;
5035   int64_t Size;
5036   unsigned AccessTypes;
5037 
5038   StackAccess() : Idx(0), Offset(), Size(0), AccessTypes(NotAccessed) {}
5039 
5040   bool operator<(const StackAccess &Rhs) const {
5041     return std::make_tuple(start(), Idx) <
5042            std::make_tuple(Rhs.start(), Rhs.Idx);
5043   }
5044 
5045   bool isCPU() const {
5046     // Predicate register load and store instructions execute on the CPU.
5047     return AccessTypes & (AccessType::GPR | AccessType::PPR);
5048   }
5049   bool isSME() const { return AccessTypes & AccessType::FPR; }
5050   bool isMixed() const { return isCPU() && isSME(); }
5051 
5052   int64_t start() const { return Offset.getFixed() + Offset.getScalable(); }
5053   int64_t end() const { return start() + Size; }
5054 
5055   std::string getTypeString() const {
5056     switch (AccessTypes) {
5057     case AccessType::FPR:
5058       return "FPR";
5059     case AccessType::PPR:
5060       return "PPR";
5061     case AccessType::GPR:
5062       return "GPR";
5063     case AccessType::NotAccessed:
5064       return "NA";
5065     default:
5066       return "Mixed";
5067     }
5068   }
5069 
5070   void print(raw_ostream &OS) const {
5071     OS << getTypeString() << " stack object at [SP"
5072        << (Offset.getFixed() < 0 ? "" : "+") << Offset.getFixed();
5073     if (Offset.getScalable())
5074       OS << (Offset.getScalable() < 0 ? "" : "+") << Offset.getScalable()
5075          << " * vscale";
5076     OS << "]";
5077   }
5078 };
5079 
5080 static inline raw_ostream &operator<<(raw_ostream &OS, const StackAccess &SA) {
5081   SA.print(OS);
5082   return OS;
5083 }
5084 
5085 void AArch64FrameLowering::emitRemarks(
5086     const MachineFunction &MF, MachineOptimizationRemarkEmitter *ORE) const {
5087 
5088   SMEAttrs Attrs(MF.getFunction());
5089   if (Attrs.hasNonStreamingInterfaceAndBody())
5090     return;
5091 
5092   const uint64_t HazardSize =
5093       (StackHazardSize) ? StackHazardSize : StackHazardRemarkSize;
5094 
5095   if (HazardSize == 0)
5096     return;
5097 
5098   const MachineFrameInfo &MFI = MF.getFrameInfo();
5099   // Bail if function has no stack objects.
5100   if (!MFI.hasStackObjects())
5101     return;
5102 
5103   std::vector<StackAccess> StackAccesses(MFI.getNumObjects());
5104 
5105   size_t NumFPLdSt = 0;
5106   size_t NumNonFPLdSt = 0;
5107 
5108   // Collect stack accesses via Load/Store instructions.
5109   for (const MachineBasicBlock &MBB : MF) {
5110     for (const MachineInstr &MI : MBB) {
5111       if (!MI.mayLoadOrStore() || MI.getNumMemOperands() < 1)
5112         continue;
5113       for (MachineMemOperand *MMO : MI.memoperands()) {
5114         std::optional<int> FI = getMMOFrameID(MMO, MFI);
5115         if (FI && !MFI.isDeadObjectIndex(*FI)) {
5116           int FrameIdx = *FI;
5117 
5118           size_t ArrIdx = FrameIdx + MFI.getNumFixedObjects();
5119           if (StackAccesses[ArrIdx].AccessTypes == StackAccess::NotAccessed) {
5120             StackAccesses[ArrIdx].Idx = FrameIdx;
5121             StackAccesses[ArrIdx].Offset =
5122                 getFrameIndexReferenceFromSP(MF, FrameIdx);
5123             StackAccesses[ArrIdx].Size = MFI.getObjectSize(FrameIdx);
5124           }
5125 
5126           unsigned RegTy = StackAccess::AccessType::GPR;
5127           if (MFI.getStackID(FrameIdx) == TargetStackID::ScalableVector) {
5128             if (AArch64::PPRRegClass.contains(MI.getOperand(0).getReg()))
5129               RegTy = StackAccess::PPR;
5130             else
5131               RegTy = StackAccess::FPR;
5132           } else if (AArch64InstrInfo::isFpOrNEON(MI)) {
5133             RegTy = StackAccess::FPR;
5134           }
5135 
5136           StackAccesses[ArrIdx].AccessTypes |= RegTy;
5137 
5138           if (RegTy == StackAccess::FPR)
5139             ++NumFPLdSt;
5140           else
5141             ++NumNonFPLdSt;
5142         }
5143       }
5144     }
5145   }
5146 
5147   if (NumFPLdSt == 0 || NumNonFPLdSt == 0)
5148     return;
5149 
5150   llvm::sort(StackAccesses);
5151   StackAccesses.erase(llvm::remove_if(StackAccesses,
5152                                       [](const StackAccess &S) {
5153                                         return S.AccessTypes ==
5154                                                StackAccess::NotAccessed;
5155                                       }),
5156                       StackAccesses.end());
5157 
5158   SmallVector<const StackAccess *> MixedObjects;
5159   SmallVector<std::pair<const StackAccess *, const StackAccess *>> HazardPairs;
5160 
5161   if (StackAccesses.front().isMixed())
5162     MixedObjects.push_back(&StackAccesses.front());
5163 
5164   for (auto It = StackAccesses.begin(), End = std::prev(StackAccesses.end());
5165        It != End; ++It) {
5166     const auto &First = *It;
5167     const auto &Second = *(It + 1);
5168 
5169     if (Second.isMixed())
5170       MixedObjects.push_back(&Second);
5171 
5172     if ((First.isSME() && Second.isCPU()) ||
5173         (First.isCPU() && Second.isSME())) {
5174       uint64_t Distance = static_cast<uint64_t>(Second.start() - First.end());
5175       if (Distance < HazardSize)
5176         HazardPairs.emplace_back(&First, &Second);
5177     }
5178   }
5179 
5180   auto EmitRemark = [&](llvm::StringRef Str) {
5181     ORE->emit([&]() {
5182       auto R = MachineOptimizationRemarkAnalysis(
5183           "sme", "StackHazard", MF.getFunction().getSubprogram(), &MF.front());
5184       return R << formatv("stack hazard in '{0}': ", MF.getName()).str() << Str;
5185     });
5186   };
5187 
5188   for (const auto &P : HazardPairs)
5189     EmitRemark(formatv("{0} is too close to {1}", *P.first, *P.second).str());
5190 
5191   for (const auto *Obj : MixedObjects)
5192     EmitRemark(
5193         formatv("{0} accessed by both GP and FP instructions", *Obj).str());
5194 }
5195