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