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