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