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