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