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