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