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