1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the AArch64 implementation of TargetFrameLowering class.
11 //
12 // On AArch64, stack frames are structured as follows:
13 //
14 // The stack grows downward.
15 //
16 // All of the individual frame areas on the frame below are optional, i.e. it's
17 // possible to create a function so that the particular area isn't present
18 // in the frame.
19 //
20 // At function entry, the "frame" looks as follows:
21 //
22 // |                                   | Higher address
23 // |-----------------------------------|
24 // |                                   |
25 // | arguments passed on the stack     |
26 // |                                   |
27 // |-----------------------------------| <- sp
28 // |                                   | Lower address
29 //
30 //
31 // After the prologue has run, the frame has the following general structure.
32 // Note that this doesn't depict the case where a red-zone is used. Also,
33 // technically the last frame area (VLAs) doesn't get created until in the
34 // main function body, after the prologue is run. However, it's depicted here
35 // for completeness.
36 //
37 // |                                   | Higher address
38 // |-----------------------------------|
39 // |                                   |
40 // | arguments passed on the stack     |
41 // |                                   |
42 // |-----------------------------------|
43 // |                                   |
44 // | (Win64 only) varargs from reg     |
45 // |                                   |
46 // |-----------------------------------|
47 // |                                   |
48 // | prev_fp, prev_lr                  |
49 // | (a.k.a. "frame record")           |
50 // |-----------------------------------| <- fp(=x29)
51 // |                                   |
52 // | other callee-saved registers      |
53 // |                                   |
54 // |-----------------------------------|
55 // |.empty.space.to.make.part.below....|
56 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
57 // |.the.standard.16-byte.alignment....|  compile time; if present)
58 // |-----------------------------------|
59 // |                                   |
60 // | local variables of fixed size     |
61 // | including spill slots             |
62 // |-----------------------------------| <- bp(not defined by ABI,
63 // |.variable-sized.local.variables....|       LLVM chooses X19)
64 // |.(VLAs)............................| (size of this area is unknown at
65 // |...................................|  compile time)
66 // |-----------------------------------| <- sp
67 // |                                   | Lower address
68 //
69 //
70 // To access the data in a frame, at-compile time, a constant offset must be
71 // computable from one of the pointers (fp, bp, sp) to access it. The size
72 // of the areas with a dotted background cannot be computed at compile-time
73 // if they are present, making it required to have all three of fp, bp and
74 // sp to be set up to be able to access all contents in the frame areas,
75 // assuming all of the frame areas are non-empty.
76 //
77 // For most functions, some of the frame areas are empty. For those functions,
78 // it may not be necessary to set up fp or bp:
79 // * A base pointer is definitely needed when there are both VLAs and local
80 //   variables with more-than-default alignment requirements.
81 // * A frame pointer is definitely needed when there are local variables with
82 //   more-than-default alignment requirements.
83 //
84 // In some cases when a base pointer is not strictly needed, it is generated
85 // anyway when offsets from the frame pointer to access local variables become
86 // so large that the offset can't be encoded in the immediate fields of loads
87 // or stores.
88 //
89 // FIXME: also explain the redzone concept.
90 // FIXME: also explain the concept of reserved call frames.
91 //
92 //===----------------------------------------------------------------------===//
93 
94 #include "AArch64FrameLowering.h"
95 #include "AArch64InstrInfo.h"
96 #include "AArch64MachineFunctionInfo.h"
97 #include "AArch64RegisterInfo.h"
98 #include "AArch64Subtarget.h"
99 #include "AArch64TargetMachine.h"
100 #include "MCTargetDesc/AArch64AddressingModes.h"
101 #include "llvm/ADT/ScopeExit.h"
102 #include "llvm/ADT/SmallVector.h"
103 #include "llvm/ADT/Statistic.h"
104 #include "llvm/CodeGen/LivePhysRegs.h"
105 #include "llvm/CodeGen/MachineBasicBlock.h"
106 #include "llvm/CodeGen/MachineFrameInfo.h"
107 #include "llvm/CodeGen/MachineFunction.h"
108 #include "llvm/CodeGen/MachineInstr.h"
109 #include "llvm/CodeGen/MachineInstrBuilder.h"
110 #include "llvm/CodeGen/MachineMemOperand.h"
111 #include "llvm/CodeGen/MachineModuleInfo.h"
112 #include "llvm/CodeGen/MachineOperand.h"
113 #include "llvm/CodeGen/MachineRegisterInfo.h"
114 #include "llvm/CodeGen/RegisterScavenging.h"
115 #include "llvm/CodeGen/TargetInstrInfo.h"
116 #include "llvm/CodeGen/TargetRegisterInfo.h"
117 #include "llvm/CodeGen/TargetSubtargetInfo.h"
118 #include "llvm/CodeGen/WinEHFuncInfo.h"
119 #include "llvm/IR/Attributes.h"
120 #include "llvm/IR/CallingConv.h"
121 #include "llvm/IR/DataLayout.h"
122 #include "llvm/IR/DebugLoc.h"
123 #include "llvm/IR/Function.h"
124 #include "llvm/MC/MCAsmInfo.h"
125 #include "llvm/MC/MCDwarf.h"
126 #include "llvm/Support/CommandLine.h"
127 #include "llvm/Support/Debug.h"
128 #include "llvm/Support/ErrorHandling.h"
129 #include "llvm/Support/MathExtras.h"
130 #include "llvm/Support/raw_ostream.h"
131 #include "llvm/Target/TargetMachine.h"
132 #include "llvm/Target/TargetOptions.h"
133 #include <cassert>
134 #include <cstdint>
135 #include <iterator>
136 #include <vector>
137 
138 using namespace llvm;
139 
140 #define DEBUG_TYPE "frame-info"
141 
142 static cl::opt<bool> EnableRedZone("aarch64-redzone",
143                                    cl::desc("enable use of redzone on AArch64"),
144                                    cl::init(false), cl::Hidden);
145 
146 static cl::opt<bool>
147     ReverseCSRRestoreSeq("reverse-csr-restore-seq",
148                          cl::desc("reverse the CSR restore sequence"),
149                          cl::init(false), cl::Hidden);
150 
151 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
152 
153 /// This is the biggest offset to the stack pointer we can encode in aarch64
154 /// instructions (without using a separate calculation and a temp register).
155 /// Note that the exception here are vector stores/loads which cannot encode any
156 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
157 static const unsigned DefaultSafeSPDisplacement = 255;
158 
159 /// Look at each instruction that references stack frames and return the stack
160 /// size limit beyond which some of these instructions will require a scratch
161 /// register during their expansion later.
162 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
163   // FIXME: For now, just conservatively guestimate based on unscaled indexing
164   // range. We'll end up allocating an unnecessary spill slot a lot, but
165   // realistically that's not a big deal at this stage of the game.
166   for (MachineBasicBlock &MBB : MF) {
167     for (MachineInstr &MI : MBB) {
168       if (MI.isDebugInstr() || MI.isPseudo() ||
169           MI.getOpcode() == AArch64::ADDXri ||
170           MI.getOpcode() == AArch64::ADDSXri)
171         continue;
172 
173       for (const MachineOperand &MO : MI.operands()) {
174         if (!MO.isFI())
175           continue;
176 
177         int Offset = 0;
178         if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
179             AArch64FrameOffsetCannotUpdate)
180           return 0;
181       }
182     }
183   }
184   return DefaultSafeSPDisplacement;
185 }
186 
187 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
188   if (!EnableRedZone)
189     return false;
190   // Don't use the red zone if the function explicitly asks us not to.
191   // This is typically used for kernel code.
192   if (MF.getFunction().hasFnAttribute(Attribute::NoRedZone))
193     return false;
194 
195   const MachineFrameInfo &MFI = MF.getFrameInfo();
196   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
197   unsigned NumBytes = AFI->getLocalStackSize();
198 
199   return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128);
200 }
201 
202 /// hasFP - Return true if the specified function should have a dedicated frame
203 /// pointer register.
204 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
205   const MachineFrameInfo &MFI = MF.getFrameInfo();
206   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
207   // Win64 EH requires a frame pointer if funclets are present, as the locals
208   // are accessed off the frame pointer in both the parent function and the
209   // funclets.
210   if (MF.hasEHFunclets())
211     return true;
212   // Retain behavior of always omitting the FP for leaf functions when possible.
213   if (MFI.hasCalls() && MF.getTarget().Options.DisableFramePointerElim(MF))
214     return true;
215   if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
216       MFI.hasStackMap() || MFI.hasPatchPoint() ||
217       RegInfo->needsStackRealignment(MF))
218     return true;
219   // With large callframes around we may need to use FP to access the scavenging
220   // emergency spillslot.
221   //
222   // Unfortunately some calls to hasFP() like machine verifier ->
223   // getReservedReg() -> hasFP in the middle of global isel are too early
224   // to know the max call frame size. Hopefully conservatively returning "true"
225   // in those cases is fine.
226   // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
227   if (!MFI.isMaxCallFrameSizeComputed() ||
228       MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
229     return true;
230 
231   return false;
232 }
233 
234 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
235 /// not required, we reserve argument space for call sites in the function
236 /// immediately on entry to the current function.  This eliminates the need for
237 /// add/sub sp brackets around call sites.  Returns true if the call frame is
238 /// included as part of the stack frame.
239 bool
240 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
241   return !MF.getFrameInfo().hasVarSizedObjects();
242 }
243 
244 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
245     MachineFunction &MF, MachineBasicBlock &MBB,
246     MachineBasicBlock::iterator I) const {
247   const AArch64InstrInfo *TII =
248       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
249   DebugLoc DL = I->getDebugLoc();
250   unsigned Opc = I->getOpcode();
251   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
252   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
253 
254   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
255   if (!TFI->hasReservedCallFrame(MF)) {
256     unsigned Align = getStackAlignment();
257 
258     int64_t Amount = I->getOperand(0).getImm();
259     Amount = alignTo(Amount, Align);
260     if (!IsDestroy)
261       Amount = -Amount;
262 
263     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
264     // doesn't have to pop anything), then the first operand will be zero too so
265     // this adjustment is a no-op.
266     if (CalleePopAmount == 0) {
267       // FIXME: in-function stack adjustment for calls is limited to 24-bits
268       // because there's no guaranteed temporary register available.
269       //
270       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
271       // 1) For offset <= 12-bit, we use LSL #0
272       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
273       // LSL #0, and the other uses LSL #12.
274       //
275       // Most call frames will be allocated at the start of a function so
276       // this is OK, but it is a limitation that needs dealing with.
277       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
278       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
279     }
280   } else if (CalleePopAmount != 0) {
281     // If the calling convention demands that the callee pops arguments from the
282     // stack, we want to add it back if we have a reserved call frame.
283     assert(CalleePopAmount < 0xffffff && "call frame too large");
284     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
285                     TII);
286   }
287   return MBB.erase(I);
288 }
289 
290 static bool ShouldSignReturnAddress(MachineFunction &MF) {
291   // The function should be signed in the following situations:
292   // - sign-return-address=all
293   // - sign-return-address=non-leaf and the functions spills the LR
294 
295   const Function &F = MF.getFunction();
296   if (!F.hasFnAttribute("sign-return-address"))
297     return false;
298 
299   StringRef Scope = F.getFnAttribute("sign-return-address").getValueAsString();
300   if (Scope.equals("none"))
301     return false;
302 
303   if (Scope.equals("all"))
304     return true;
305 
306   assert(Scope.equals("non-leaf") && "Expected all, none or non-leaf");
307 
308   for (const auto &Info : MF.getFrameInfo().getCalleeSavedInfo())
309     if (Info.getReg() == AArch64::LR)
310       return true;
311 
312   return false;
313 }
314 
315 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
316     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
317   MachineFunction &MF = *MBB.getParent();
318   MachineFrameInfo &MFI = MF.getFrameInfo();
319   const TargetSubtargetInfo &STI = MF.getSubtarget();
320   const MCRegisterInfo *MRI = STI.getRegisterInfo();
321   const TargetInstrInfo *TII = STI.getInstrInfo();
322   DebugLoc DL = MBB.findDebugLoc(MBBI);
323 
324   // Add callee saved registers to move list.
325   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
326   if (CSI.empty())
327     return;
328 
329   for (const auto &Info : CSI) {
330     unsigned Reg = Info.getReg();
331     int64_t Offset =
332         MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
333     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
334     unsigned CFIIndex = MF.addFrameInst(
335         MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
336     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
337         .addCFIIndex(CFIIndex)
338         .setMIFlags(MachineInstr::FrameSetup);
339   }
340 }
341 
342 // Find a scratch register that we can use at the start of the prologue to
343 // re-align the stack pointer.  We avoid using callee-save registers since they
344 // may appear to be free when this is called from canUseAsPrologue (during
345 // shrink wrapping), but then no longer be free when this is called from
346 // emitPrologue.
347 //
348 // FIXME: This is a bit conservative, since in the above case we could use one
349 // of the callee-save registers as a scratch temp to re-align the stack pointer,
350 // but we would then have to make sure that we were in fact saving at least one
351 // callee-save register in the prologue, which is additional complexity that
352 // doesn't seem worth the benefit.
353 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
354   MachineFunction *MF = MBB->getParent();
355 
356   // If MBB is an entry block, use X9 as the scratch register
357   if (&MF->front() == MBB)
358     return AArch64::X9;
359 
360   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
361   const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
362   LivePhysRegs LiveRegs(TRI);
363   LiveRegs.addLiveIns(*MBB);
364 
365   // Mark callee saved registers as used so we will not choose them.
366   const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
367   for (unsigned i = 0; CSRegs[i]; ++i)
368     LiveRegs.addReg(CSRegs[i]);
369 
370   // Prefer X9 since it was historically used for the prologue scratch reg.
371   const MachineRegisterInfo &MRI = MF->getRegInfo();
372   if (LiveRegs.available(MRI, AArch64::X9))
373     return AArch64::X9;
374 
375   for (unsigned Reg : AArch64::GPR64RegClass) {
376     if (LiveRegs.available(MRI, Reg))
377       return Reg;
378   }
379   return AArch64::NoRegister;
380 }
381 
382 bool AArch64FrameLowering::canUseAsPrologue(
383     const MachineBasicBlock &MBB) const {
384   const MachineFunction *MF = MBB.getParent();
385   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
386   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
387   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
388 
389   // Don't need a scratch register if we're not going to re-align the stack.
390   if (!RegInfo->needsStackRealignment(*MF))
391     return true;
392   // Otherwise, we can use any block as long as it has a scratch register
393   // available.
394   return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
395 }
396 
397 static bool windowsRequiresStackProbe(MachineFunction &MF,
398                                       unsigned StackSizeInBytes) {
399   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
400   if (!Subtarget.isTargetWindows())
401     return false;
402   const Function &F = MF.getFunction();
403   // TODO: When implementing stack protectors, take that into account
404   // for the probe threshold.
405   unsigned StackProbeSize = 4096;
406   if (F.hasFnAttribute("stack-probe-size"))
407     F.getFnAttribute("stack-probe-size")
408         .getValueAsString()
409         .getAsInteger(0, StackProbeSize);
410   return (StackSizeInBytes >= StackProbeSize) &&
411          !F.hasFnAttribute("no-stack-arg-probe");
412 }
413 
414 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
415     MachineFunction &MF, unsigned StackBumpBytes) const {
416   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
417   const MachineFrameInfo &MFI = MF.getFrameInfo();
418   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
419   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
420 
421   if (AFI->getLocalStackSize() == 0)
422     return false;
423 
424   // 512 is the maximum immediate for stp/ldp that will be used for
425   // callee-save save/restores
426   if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
427     return false;
428 
429   if (MFI.hasVarSizedObjects())
430     return false;
431 
432   if (RegInfo->needsStackRealignment(MF))
433     return false;
434 
435   // This isn't strictly necessary, but it simplifies things a bit since the
436   // current RedZone handling code assumes the SP is adjusted by the
437   // callee-save save/restore code.
438   if (canUseRedZone(MF))
439     return false;
440 
441   return true;
442 }
443 
444 // Given a load or a store instruction, generate an appropriate unwinding SEH
445 // code on Windows.
446 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,
447                                              const TargetInstrInfo &TII,
448                                              MachineInstr::MIFlag Flag) {
449   unsigned Opc = MBBI->getOpcode();
450   MachineBasicBlock *MBB = MBBI->getParent();
451   MachineFunction &MF = *MBB->getParent();
452   DebugLoc DL = MBBI->getDebugLoc();
453   unsigned ImmIdx = MBBI->getNumOperands() - 1;
454   int Imm = MBBI->getOperand(ImmIdx).getImm();
455   MachineInstrBuilder MIB;
456   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
457   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
458 
459   switch (Opc) {
460   default:
461     llvm_unreachable("No SEH Opcode for this instruction");
462   case AArch64::LDPDpost:
463     Imm = -Imm;
464     LLVM_FALLTHROUGH;
465   case AArch64::STPDpre: {
466     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
467     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
468     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
469               .addImm(Reg0)
470               .addImm(Reg1)
471               .addImm(Imm * 8)
472               .setMIFlag(Flag);
473     break;
474   }
475   case AArch64::LDPXpost:
476     Imm = -Imm;
477     LLVM_FALLTHROUGH;
478   case AArch64::STPXpre: {
479     unsigned Reg0 = MBBI->getOperand(1).getReg();
480     unsigned Reg1 = MBBI->getOperand(2).getReg();
481     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
482       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
483                 .addImm(Imm * 8)
484                 .setMIFlag(Flag);
485     else
486       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
487                 .addImm(RegInfo->getSEHRegNum(Reg0))
488                 .addImm(RegInfo->getSEHRegNum(Reg1))
489                 .addImm(Imm * 8)
490                 .setMIFlag(Flag);
491     break;
492   }
493   case AArch64::LDRDpost:
494     Imm = -Imm;
495     LLVM_FALLTHROUGH;
496   case AArch64::STRDpre: {
497     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
498     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
499               .addImm(Reg)
500               .addImm(Imm)
501               .setMIFlag(Flag);
502     break;
503   }
504   case AArch64::LDRXpost:
505     Imm = -Imm;
506     LLVM_FALLTHROUGH;
507   case AArch64::STRXpre: {
508     unsigned Reg =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
509     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
510               .addImm(Reg)
511               .addImm(Imm)
512               .setMIFlag(Flag);
513     break;
514   }
515   case AArch64::STPDi:
516   case AArch64::LDPDi: {
517     unsigned Reg0 =  RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
518     unsigned Reg1 =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
519     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
520               .addImm(Reg0)
521               .addImm(Reg1)
522               .addImm(Imm * 8)
523               .setMIFlag(Flag);
524     break;
525   }
526   case AArch64::STPXi:
527   case AArch64::LDPXi: {
528     unsigned Reg0 = MBBI->getOperand(0).getReg();
529     unsigned Reg1 = MBBI->getOperand(1).getReg();
530     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
531       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
532                 .addImm(Imm * 8)
533                 .setMIFlag(Flag);
534     else
535       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
536                 .addImm(RegInfo->getSEHRegNum(Reg0))
537                 .addImm(RegInfo->getSEHRegNum(Reg1))
538                 .addImm(Imm * 8)
539                 .setMIFlag(Flag);
540     break;
541   }
542   case AArch64::STRXui:
543   case AArch64::LDRXui: {
544     int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
545     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
546               .addImm(Reg)
547               .addImm(Imm * 8)
548               .setMIFlag(Flag);
549     break;
550   }
551   case AArch64::STRDui:
552   case AArch64::LDRDui: {
553     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
554     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
555               .addImm(Reg)
556               .addImm(Imm * 8)
557               .setMIFlag(Flag);
558     break;
559   }
560   }
561   auto I = MBB->insertAfter(MBBI, MIB);
562   return I;
563 }
564 
565 // Fix up the SEH opcode associated with the save/restore instruction.
566 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,
567                            unsigned LocalStackSize) {
568   MachineOperand *ImmOpnd = nullptr;
569   unsigned ImmIdx = MBBI->getNumOperands() - 1;
570   switch (MBBI->getOpcode()) {
571   default:
572     llvm_unreachable("Fix the offset in the SEH instruction");
573   case AArch64::SEH_SaveFPLR:
574   case AArch64::SEH_SaveRegP:
575   case AArch64::SEH_SaveReg:
576   case AArch64::SEH_SaveFRegP:
577   case AArch64::SEH_SaveFReg:
578     ImmOpnd = &MBBI->getOperand(ImmIdx);
579     break;
580   }
581   if (ImmOpnd)
582     ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);
583 }
584 
585 // Convert callee-save register save/restore instruction to do stack pointer
586 // decrement/increment to allocate/deallocate the callee-save stack area by
587 // converting store/load to use pre/post increment version.
588 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
589     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
590     const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,
591     bool NeedsWinCFI, bool InProlog = true) {
592   // Ignore instructions that do not operate on SP, i.e. shadow call stack
593   // instructions and associated CFI instruction.
594   while (MBBI->getOpcode() == AArch64::STRXpost ||
595          MBBI->getOpcode() == AArch64::LDRXpre ||
596          MBBI->getOpcode() == AArch64::CFI_INSTRUCTION) {
597     if (MBBI->getOpcode() != AArch64::CFI_INSTRUCTION)
598       assert(MBBI->getOperand(0).getReg() != AArch64::SP);
599     ++MBBI;
600   }
601   unsigned NewOpc;
602   int Scale = 1;
603   switch (MBBI->getOpcode()) {
604   default:
605     llvm_unreachable("Unexpected callee-save save/restore opcode!");
606   case AArch64::STPXi:
607     NewOpc = AArch64::STPXpre;
608     Scale = 8;
609     break;
610   case AArch64::STPDi:
611     NewOpc = AArch64::STPDpre;
612     Scale = 8;
613     break;
614   case AArch64::STPQi:
615     NewOpc = AArch64::STPQpre;
616     Scale = 16;
617     break;
618   case AArch64::STRXui:
619     NewOpc = AArch64::STRXpre;
620     break;
621   case AArch64::STRDui:
622     NewOpc = AArch64::STRDpre;
623     break;
624   case AArch64::STRQui:
625     NewOpc = AArch64::STRQpre;
626     break;
627   case AArch64::LDPXi:
628     NewOpc = AArch64::LDPXpost;
629     Scale = 8;
630     break;
631   case AArch64::LDPDi:
632     NewOpc = AArch64::LDPDpost;
633     Scale = 8;
634     break;
635   case AArch64::LDPQi:
636     NewOpc = AArch64::LDPQpost;
637     Scale = 16;
638     break;
639   case AArch64::LDRXui:
640     NewOpc = AArch64::LDRXpost;
641     break;
642   case AArch64::LDRDui:
643     NewOpc = AArch64::LDRDpost;
644     break;
645   case AArch64::LDRQui:
646     NewOpc = AArch64::LDRQpost;
647     break;
648   }
649   // Get rid of the SEH code associated with the old instruction.
650   if (NeedsWinCFI) {
651     auto SEH = std::next(MBBI);
652     if (AArch64InstrInfo::isSEHInstruction(*SEH))
653       SEH->eraseFromParent();
654   }
655 
656   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
657   MIB.addReg(AArch64::SP, RegState::Define);
658 
659   // Copy all operands other than the immediate offset.
660   unsigned OpndIdx = 0;
661   for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
662        ++OpndIdx)
663     MIB.add(MBBI->getOperand(OpndIdx));
664 
665   assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
666          "Unexpected immediate offset in first/last callee-save save/restore "
667          "instruction!");
668   assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
669          "Unexpected base register in callee-save save/restore instruction!");
670   assert(CSStackSizeInc % Scale == 0);
671   MIB.addImm(CSStackSizeInc / Scale);
672 
673   MIB.setMIFlags(MBBI->getFlags());
674   MIB.setMemRefs(MBBI->memoperands());
675 
676   // Generate a new SEH code that corresponds to the new instruction.
677   if (NeedsWinCFI)
678     InsertSEH(*MIB, *TII,
679               InProlog ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy);
680 
681   return std::prev(MBB.erase(MBBI));
682 }
683 
684 // Fixup callee-save register save/restore instructions to take into account
685 // combined SP bump by adding the local stack size to the stack offsets.
686 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
687                                               unsigned LocalStackSize,
688                                               bool NeedsWinCFI) {
689   if (AArch64InstrInfo::isSEHInstruction(MI))
690     return;
691 
692   unsigned Opc = MI.getOpcode();
693 
694   // Ignore instructions that do not operate on SP, i.e. shadow call stack
695   // instructions and associated CFI instruction.
696   if (Opc == AArch64::STRXpost || Opc == AArch64::LDRXpre ||
697       Opc == AArch64::CFI_INSTRUCTION) {
698     if (Opc != AArch64::CFI_INSTRUCTION)
699       assert(MI.getOperand(0).getReg() != AArch64::SP);
700     return;
701   }
702 
703   unsigned Scale;
704   switch (Opc) {
705   case AArch64::STPXi:
706   case AArch64::STRXui:
707   case AArch64::STPDi:
708   case AArch64::STRDui:
709   case AArch64::LDPXi:
710   case AArch64::LDRXui:
711   case AArch64::LDPDi:
712   case AArch64::LDRDui:
713     Scale = 8;
714     break;
715   case AArch64::STPQi:
716   case AArch64::STRQui:
717   case AArch64::LDPQi:
718   case AArch64::LDRQui:
719     Scale = 16;
720     break;
721   default:
722     llvm_unreachable("Unexpected callee-save save/restore opcode!");
723   }
724 
725   unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
726   assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
727          "Unexpected base register in callee-save save/restore instruction!");
728   // Last operand is immediate offset that needs fixing.
729   MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
730   // All generated opcodes have scaled offsets.
731   assert(LocalStackSize % Scale == 0);
732   OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
733 
734   if (NeedsWinCFI) {
735     auto MBBI = std::next(MachineBasicBlock::iterator(MI));
736     assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");
737     assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&
738            "Expecting a SEH instruction");
739     fixupSEHOpcode(MBBI, LocalStackSize);
740   }
741 }
742 
743 static void adaptForLdStOpt(MachineBasicBlock &MBB,
744                             MachineBasicBlock::iterator FirstSPPopI,
745                             MachineBasicBlock::iterator LastPopI) {
746   // Sometimes (when we restore in the same order as we save), we can end up
747   // with code like this:
748   //
749   // ldp      x26, x25, [sp]
750   // ldp      x24, x23, [sp, #16]
751   // ldp      x22, x21, [sp, #32]
752   // ldp      x20, x19, [sp, #48]
753   // add      sp, sp, #64
754   //
755   // In this case, it is always better to put the first ldp at the end, so
756   // that the load-store optimizer can run and merge the ldp and the add into
757   // a post-index ldp.
758   // If we managed to grab the first pop instruction, move it to the end.
759   if (ReverseCSRRestoreSeq)
760     MBB.splice(FirstSPPopI, &MBB, LastPopI);
761   // We should end up with something like this now:
762   //
763   // ldp      x24, x23, [sp, #16]
764   // ldp      x22, x21, [sp, #32]
765   // ldp      x20, x19, [sp, #48]
766   // ldp      x26, x25, [sp]
767   // add      sp, sp, #64
768   //
769   // and the load-store optimizer can merge the last two instructions into:
770   //
771   // ldp      x26, x25, [sp], #64
772   //
773 }
774 
775 static bool ShouldSignWithAKey(MachineFunction &MF) {
776   const Function &F = MF.getFunction();
777   if (!F.hasFnAttribute("sign-return-address-key"))
778     return true;
779 
780   const StringRef Key =
781       F.getFnAttribute("sign-return-address-key").getValueAsString();
782   assert(Key.equals_lower("a_key") || Key.equals_lower("b_key"));
783   return Key.equals_lower("a_key");
784 }
785 
786 static bool needsWinCFI(const MachineFunction &MF) {
787   const Function &F = MF.getFunction();
788   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
789          F.needsUnwindTableEntry();
790 }
791 
792 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
793                                         MachineBasicBlock &MBB) const {
794   MachineBasicBlock::iterator MBBI = MBB.begin();
795   const MachineFrameInfo &MFI = MF.getFrameInfo();
796   const Function &F = MF.getFunction();
797   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
798   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
799   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
800   MachineModuleInfo &MMI = MF.getMMI();
801   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
802   bool needsFrameMoves = (MMI.hasDebugInfo() || F.needsUnwindTableEntry()) &&
803                          !MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
804   bool HasFP = hasFP(MF);
805   bool NeedsWinCFI = needsWinCFI(MF);
806   MF.setHasWinCFI(NeedsWinCFI);
807   bool IsFunclet = MBB.isEHFuncletEntry();
808 
809   // At this point, we're going to decide whether or not the function uses a
810   // redzone. In most cases, the function doesn't have a redzone so let's
811   // assume that's false and set it to true in the case that there's a redzone.
812   AFI->setHasRedZone(false);
813 
814   // Debug location must be unknown since the first debug location is used
815   // to determine the end of the prologue.
816   DebugLoc DL;
817 
818   if (ShouldSignReturnAddress(MF)) {
819     BuildMI(
820         MBB, MBBI, DL,
821         TII->get(ShouldSignWithAKey(MF) ? AArch64::PACIASP : AArch64::PACIBSP))
822         .setMIFlag(MachineInstr::FrameSetup);
823   }
824 
825   // All calls are tail calls in GHC calling conv, and functions have no
826   // prologue/epilogue.
827   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
828     return;
829 
830   // getStackSize() includes all the locals in its size calculation. We don't
831   // include these locals when computing the stack size of a funclet, as they
832   // are allocated in the parent's stack frame and accessed via the frame
833   // pointer from the funclet.  We only save the callee saved registers in the
834   // funclet, which are really the callee saved registers of the parent
835   // function, including the funclet.
836   int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF)
837                            : (int)MFI.getStackSize();
838   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
839     assert(!HasFP && "unexpected function without stack frame but with FP");
840     // All of the stack allocation is for locals.
841     AFI->setLocalStackSize(NumBytes);
842     if (!NumBytes)
843       return;
844     // REDZONE: If the stack size is less than 128 bytes, we don't need
845     // to actually allocate.
846     if (canUseRedZone(MF)) {
847       AFI->setHasRedZone(true);
848       ++NumRedZoneFunctions;
849     } else {
850       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
851                       MachineInstr::FrameSetup, false, NeedsWinCFI);
852       if (!NeedsWinCFI) {
853         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
854         MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
855         // Encode the stack size of the leaf function.
856         unsigned CFIIndex = MF.addFrameInst(
857             MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
858         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
859             .addCFIIndex(CFIIndex)
860             .setMIFlags(MachineInstr::FrameSetup);
861       }
862     }
863 
864     if (NeedsWinCFI)
865       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
866           .setMIFlag(MachineInstr::FrameSetup);
867 
868     return;
869   }
870 
871   bool IsWin64 =
872       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
873   // Var args are accounted for in the containing function, so don't
874   // include them for funclets.
875   unsigned FixedObject = (IsWin64 && !IsFunclet) ?
876                          alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
877 
878   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
879   // All of the remaining stack allocations are for locals.
880   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
881   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
882   if (CombineSPBump) {
883     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
884                     MachineInstr::FrameSetup, false, NeedsWinCFI);
885     NumBytes = 0;
886   } else if (PrologueSaveSize != 0) {
887     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
888         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI);
889     NumBytes -= PrologueSaveSize;
890   }
891   assert(NumBytes >= 0 && "Negative stack allocation size!?");
892 
893   // Move past the saves of the callee-saved registers, fixing up the offsets
894   // and pre-inc if we decided to combine the callee-save and local stack
895   // pointer bump above.
896   MachineBasicBlock::iterator End = MBB.end();
897   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
898     if (CombineSPBump)
899       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
900                                         NeedsWinCFI);
901     ++MBBI;
902   }
903 
904   // The code below is not applicable to funclets. We have emitted all the SEH
905   // opcodes that we needed to emit.  The FP and BP belong to the containing
906   // function.
907   if (IsFunclet) {
908     if (NeedsWinCFI)
909       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
910           .setMIFlag(MachineInstr::FrameSetup);
911     return;
912   }
913 
914   if (HasFP) {
915     // Only set up FP if we actually need to. Frame pointer is fp =
916     // sp - fixedobject - 16.
917     int FPOffset = AFI->getCalleeSavedStackSize() - 16;
918     if (CombineSPBump)
919       FPOffset += AFI->getLocalStackSize();
920 
921     // Issue    sub fp, sp, FPOffset or
922     //          mov fp,sp          when FPOffset is zero.
923     // Note: All stores of callee-saved registers are marked as "FrameSetup".
924     // This code marks the instruction(s) that set the FP also.
925     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
926                     MachineInstr::FrameSetup, false, NeedsWinCFI);
927   }
928 
929   if (windowsRequiresStackProbe(MF, NumBytes)) {
930     uint32_t NumWords = NumBytes >> 4;
931     if (NeedsWinCFI) {
932       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
933       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
934       // This is at most two instructions, MOVZ follwed by MOVK.
935       // TODO: Fix to use multiple stack alloc unwind codes for stacks
936       // exceeding 256MB in size.
937       if (NumBytes >= (1 << 28))
938         report_fatal_error("Stack size cannot exceed 256MB for stack "
939                             "unwinding purposes");
940 
941       uint32_t LowNumWords = NumWords & 0xFFFF;
942       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
943             .addImm(LowNumWords)
944             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
945             .setMIFlag(MachineInstr::FrameSetup);
946       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
947             .setMIFlag(MachineInstr::FrameSetup);
948       if ((NumWords & 0xFFFF0000) != 0) {
949           BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
950               .addReg(AArch64::X15)
951               .addImm((NumWords & 0xFFFF0000) >> 16) // High half
952               .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
953               .setMIFlag(MachineInstr::FrameSetup);
954           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
955             .setMIFlag(MachineInstr::FrameSetup);
956       }
957     } else {
958       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
959           .addImm(NumWords)
960           .setMIFlags(MachineInstr::FrameSetup);
961     }
962 
963     switch (MF.getTarget().getCodeModel()) {
964     case CodeModel::Tiny:
965     case CodeModel::Small:
966     case CodeModel::Medium:
967     case CodeModel::Kernel:
968       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
969           .addExternalSymbol("__chkstk")
970           .addReg(AArch64::X15, RegState::Implicit)
971           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
972           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
973           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
974           .setMIFlags(MachineInstr::FrameSetup);
975       if (NeedsWinCFI)
976         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
977             .setMIFlag(MachineInstr::FrameSetup);
978       break;
979     case CodeModel::Large:
980       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
981           .addReg(AArch64::X16, RegState::Define)
982           .addExternalSymbol("__chkstk")
983           .addExternalSymbol("__chkstk")
984           .setMIFlags(MachineInstr::FrameSetup);
985       if (NeedsWinCFI)
986         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
987             .setMIFlag(MachineInstr::FrameSetup);
988 
989       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR))
990           .addReg(AArch64::X16, RegState::Kill)
991           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
992           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
993           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
994           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
995           .setMIFlags(MachineInstr::FrameSetup);
996       if (NeedsWinCFI)
997         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
998             .setMIFlag(MachineInstr::FrameSetup);
999       break;
1000     }
1001 
1002     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
1003         .addReg(AArch64::SP, RegState::Kill)
1004         .addReg(AArch64::X15, RegState::Kill)
1005         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
1006         .setMIFlags(MachineInstr::FrameSetup);
1007     if (NeedsWinCFI)
1008        BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1009             .addImm(NumBytes)
1010             .setMIFlag(MachineInstr::FrameSetup);
1011     NumBytes = 0;
1012   }
1013 
1014   // Allocate space for the rest of the frame.
1015   if (NumBytes) {
1016     const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
1017     unsigned scratchSPReg = AArch64::SP;
1018 
1019     if (NeedsRealignment) {
1020       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
1021       assert(scratchSPReg != AArch64::NoRegister);
1022     }
1023 
1024     // If we're a leaf function, try using the red zone.
1025     if (!canUseRedZone(MF))
1026       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1027       // the correct value here, as NumBytes also includes padding bytes,
1028       // which shouldn't be counted here.
1029       emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
1030                       MachineInstr::FrameSetup, false, NeedsWinCFI);
1031 
1032     if (NeedsRealignment) {
1033       const unsigned Alignment = MFI.getMaxAlignment();
1034       const unsigned NrBitsToZero = countTrailingZeros(Alignment);
1035       assert(NrBitsToZero > 1);
1036       assert(scratchSPReg != AArch64::SP);
1037 
1038       // SUB X9, SP, NumBytes
1039       //   -- X9 is temporary register, so shouldn't contain any live data here,
1040       //   -- free to use. This is already produced by emitFrameOffset above.
1041       // AND SP, X9, 0b11111...0000
1042       // The logical immediates have a non-trivial encoding. The following
1043       // formula computes the encoded immediate with all ones but
1044       // NrBitsToZero zero bits as least significant bits.
1045       uint32_t andMaskEncoded = (1 << 12)                         // = N
1046                                 | ((64 - NrBitsToZero) << 6)      // immr
1047                                 | ((64 - NrBitsToZero - 1) << 0); // imms
1048 
1049       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1050           .addReg(scratchSPReg, RegState::Kill)
1051           .addImm(andMaskEncoded);
1052       AFI->setStackRealigned(true);
1053       if (NeedsWinCFI)
1054         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1055             .addImm(NumBytes & andMaskEncoded)
1056             .setMIFlag(MachineInstr::FrameSetup);
1057     }
1058   }
1059 
1060   // If we need a base pointer, set it up here. It's whatever the value of the
1061   // stack pointer is at this point. Any variable size objects will be allocated
1062   // after this, so we can still use the base pointer to reference locals.
1063   //
1064   // FIXME: Clarify FrameSetup flags here.
1065   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1066   // needed.
1067   if (RegInfo->hasBasePointer(MF)) {
1068     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
1069                      false);
1070     if (NeedsWinCFI)
1071       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1072           .setMIFlag(MachineInstr::FrameSetup);
1073   }
1074 
1075   // The very last FrameSetup instruction indicates the end of prologue. Emit a
1076   // SEH opcode indicating the prologue end.
1077   if (NeedsWinCFI)
1078     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1079         .setMIFlag(MachineInstr::FrameSetup);
1080 
1081   if (needsFrameMoves) {
1082     const DataLayout &TD = MF.getDataLayout();
1083     const int StackGrowth = -TD.getPointerSize(0);
1084     unsigned FramePtr = RegInfo->getFrameRegister(MF);
1085     // An example of the prologue:
1086     //
1087     //     .globl __foo
1088     //     .align 2
1089     //  __foo:
1090     // Ltmp0:
1091     //     .cfi_startproc
1092     //     .cfi_personality 155, ___gxx_personality_v0
1093     // Leh_func_begin:
1094     //     .cfi_lsda 16, Lexception33
1095     //
1096     //     stp  xa,bx, [sp, -#offset]!
1097     //     ...
1098     //     stp  x28, x27, [sp, #offset-32]
1099     //     stp  fp, lr, [sp, #offset-16]
1100     //     add  fp, sp, #offset - 16
1101     //     sub  sp, sp, #1360
1102     //
1103     // The Stack:
1104     //       +-------------------------------------------+
1105     // 10000 | ........ | ........ | ........ | ........ |
1106     // 10004 | ........ | ........ | ........ | ........ |
1107     //       +-------------------------------------------+
1108     // 10008 | ........ | ........ | ........ | ........ |
1109     // 1000c | ........ | ........ | ........ | ........ |
1110     //       +===========================================+
1111     // 10010 |                X28 Register               |
1112     // 10014 |                X28 Register               |
1113     //       +-------------------------------------------+
1114     // 10018 |                X27 Register               |
1115     // 1001c |                X27 Register               |
1116     //       +===========================================+
1117     // 10020 |                Frame Pointer              |
1118     // 10024 |                Frame Pointer              |
1119     //       +-------------------------------------------+
1120     // 10028 |                Link Register              |
1121     // 1002c |                Link Register              |
1122     //       +===========================================+
1123     // 10030 | ........ | ........ | ........ | ........ |
1124     // 10034 | ........ | ........ | ........ | ........ |
1125     //       +-------------------------------------------+
1126     // 10038 | ........ | ........ | ........ | ........ |
1127     // 1003c | ........ | ........ | ........ | ........ |
1128     //       +-------------------------------------------+
1129     //
1130     //     [sp] = 10030        ::    >>initial value<<
1131     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
1132     //     fp = sp == 10020    ::  mov fp, sp
1133     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
1134     //     sp == 10010         ::    >>final value<<
1135     //
1136     // The frame pointer (w29) points to address 10020. If we use an offset of
1137     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
1138     // for w27, and -32 for w28:
1139     //
1140     //  Ltmp1:
1141     //     .cfi_def_cfa w29, 16
1142     //  Ltmp2:
1143     //     .cfi_offset w30, -8
1144     //  Ltmp3:
1145     //     .cfi_offset w29, -16
1146     //  Ltmp4:
1147     //     .cfi_offset w27, -24
1148     //  Ltmp5:
1149     //     .cfi_offset w28, -32
1150 
1151     if (HasFP) {
1152       // Define the current CFA rule to use the provided FP.
1153       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
1154       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
1155           nullptr, Reg, 2 * StackGrowth - FixedObject));
1156       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1157           .addCFIIndex(CFIIndex)
1158           .setMIFlags(MachineInstr::FrameSetup);
1159     } else {
1160       // Encode the stack size of the leaf function.
1161       unsigned CFIIndex = MF.addFrameInst(
1162           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
1163       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1164           .addCFIIndex(CFIIndex)
1165           .setMIFlags(MachineInstr::FrameSetup);
1166     }
1167 
1168     // Now emit the moves for whatever callee saved regs we have (including FP,
1169     // LR if those are saved).
1170     emitCalleeSavedFrameMoves(MBB, MBBI);
1171   }
1172 }
1173 
1174 static void InsertReturnAddressAuth(MachineFunction &MF,
1175                                     MachineBasicBlock &MBB) {
1176   if (!ShouldSignReturnAddress(MF))
1177     return;
1178   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1179   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1180 
1181   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1182   DebugLoc DL;
1183   if (MBBI != MBB.end())
1184     DL = MBBI->getDebugLoc();
1185 
1186   // The AUTIASP instruction assembles to a hint instruction before v8.3a so
1187   // this instruction can safely used for any v8a architecture.
1188   // From v8.3a onwards there are optimised authenticate LR and return
1189   // instructions, namely RETA{A,B}, that can be used instead.
1190   if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() &&
1191       MBBI->getOpcode() == AArch64::RET_ReallyLR) {
1192     BuildMI(MBB, MBBI, DL,
1193             TII->get(ShouldSignWithAKey(MF) ? AArch64::RETAA : AArch64::RETAB))
1194         .copyImplicitOps(*MBBI);
1195     MBB.erase(MBBI);
1196   } else {
1197     BuildMI(
1198         MBB, MBBI, DL,
1199         TII->get(ShouldSignWithAKey(MF) ? AArch64::AUTIASP : AArch64::AUTIBSP))
1200         .setMIFlag(MachineInstr::FrameDestroy);
1201   }
1202 }
1203 
1204 static bool isFuncletReturnInstr(const MachineInstr &MI) {
1205   switch (MI.getOpcode()) {
1206   default:
1207     return false;
1208   case AArch64::CATCHRET:
1209   case AArch64::CLEANUPRET:
1210     return true;
1211   }
1212 }
1213 
1214 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
1215                                         MachineBasicBlock &MBB) const {
1216   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1217   MachineFrameInfo &MFI = MF.getFrameInfo();
1218   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1219   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1220   DebugLoc DL;
1221   bool IsTailCallReturn = false;
1222   bool NeedsWinCFI = needsWinCFI(MF);
1223   bool IsFunclet = false;
1224 
1225   if (MBB.end() != MBBI) {
1226     DL = MBBI->getDebugLoc();
1227     unsigned RetOpcode = MBBI->getOpcode();
1228     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
1229                        RetOpcode == AArch64::TCRETURNri ||
1230                        RetOpcode == AArch64::TCRETURNriBTI;
1231     IsFunclet = isFuncletReturnInstr(*MBBI);
1232   }
1233 
1234   int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF)
1235                            : MFI.getStackSize();
1236   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1237 
1238   // All calls are tail calls in GHC calling conv, and functions have no
1239   // prologue/epilogue.
1240   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1241     return;
1242 
1243   // Initial and residual are named for consistency with the prologue. Note that
1244   // in the epilogue, the residual adjustment is executed first.
1245   uint64_t ArgumentPopSize = 0;
1246   if (IsTailCallReturn) {
1247     MachineOperand &StackAdjust = MBBI->getOperand(1);
1248 
1249     // For a tail-call in a callee-pops-arguments environment, some or all of
1250     // the stack may actually be in use for the call's arguments, this is
1251     // calculated during LowerCall and consumed here...
1252     ArgumentPopSize = StackAdjust.getImm();
1253   } else {
1254     // ... otherwise the amount to pop is *all* of the argument space,
1255     // conveniently stored in the MachineFunctionInfo by
1256     // LowerFormalArguments. This will, of course, be zero for the C calling
1257     // convention.
1258     ArgumentPopSize = AFI->getArgumentStackToRestore();
1259   }
1260 
1261   // The stack frame should be like below,
1262   //
1263   //      ----------------------                     ---
1264   //      |                    |                      |
1265   //      | BytesInStackArgArea|              CalleeArgStackSize
1266   //      | (NumReusableBytes) |                (of tail call)
1267   //      |                    |                     ---
1268   //      |                    |                      |
1269   //      ---------------------|        ---           |
1270   //      |                    |         |            |
1271   //      |   CalleeSavedReg   |         |            |
1272   //      | (CalleeSavedStackSize)|      |            |
1273   //      |                    |         |            |
1274   //      ---------------------|         |         NumBytes
1275   //      |                    |     StackSize  (StackAdjustUp)
1276   //      |   LocalStackSize   |         |            |
1277   //      | (covering callee   |         |            |
1278   //      |       args)        |         |            |
1279   //      |                    |         |            |
1280   //      ----------------------        ---          ---
1281   //
1282   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
1283   //             = StackSize + ArgumentPopSize
1284   //
1285   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
1286   // it as the 2nd argument of AArch64ISD::TC_RETURN.
1287 
1288   auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); });
1289 
1290   bool IsWin64 =
1291       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1292   // Var args are accounted for in the containing function, so don't
1293   // include them for funclets.
1294   unsigned FixedObject =
1295       (IsWin64 && !IsFunclet) ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1296 
1297   uint64_t AfterCSRPopSize = ArgumentPopSize;
1298   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1299   // We cannot rely on the local stack size set in emitPrologue if the function
1300   // has funclets, as funclets have different local stack size requirements, and
1301   // the current value set in emitPrologue may be that of the containing
1302   // function.
1303   if (MF.hasEHFunclets())
1304     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1305   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1306   // Assume we can't combine the last pop with the sp restore.
1307 
1308   if (!CombineSPBump && PrologueSaveSize != 0) {
1309     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
1310     while (AArch64InstrInfo::isSEHInstruction(*Pop))
1311       Pop = std::prev(Pop);
1312     // Converting the last ldp to a post-index ldp is valid only if the last
1313     // ldp's offset is 0.
1314     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
1315     // If the offset is 0, convert it to a post-index ldp.
1316     if (OffsetOp.getImm() == 0)
1317       convertCalleeSaveRestoreToSPPrePostIncDec(
1318           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, false);
1319     else {
1320       // If not, make sure to emit an add after the last ldp.
1321       // We're doing this by transfering the size to be restored from the
1322       // adjustment *before* the CSR pops to the adjustment *after* the CSR
1323       // pops.
1324       AfterCSRPopSize += PrologueSaveSize;
1325     }
1326   }
1327 
1328   // Move past the restores of the callee-saved registers.
1329   // If we plan on combining the sp bump of the local stack size and the callee
1330   // save stack size, we might need to adjust the CSR save and restore offsets.
1331   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
1332   MachineBasicBlock::iterator Begin = MBB.begin();
1333   while (LastPopI != Begin) {
1334     --LastPopI;
1335     if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
1336       ++LastPopI;
1337       break;
1338     } else if (CombineSPBump)
1339       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
1340                                         NeedsWinCFI);
1341   }
1342 
1343   if (NeedsWinCFI)
1344     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
1345         .setMIFlag(MachineInstr::FrameDestroy);
1346 
1347   // If there is a single SP update, insert it before the ret and we're done.
1348   if (CombineSPBump) {
1349     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
1350                     NumBytes + AfterCSRPopSize, TII, MachineInstr::FrameDestroy,
1351                     false, NeedsWinCFI);
1352     if (NeedsWinCFI)
1353       BuildMI(MBB, MBB.getFirstTerminator(), DL,
1354               TII->get(AArch64::SEH_EpilogEnd))
1355           .setMIFlag(MachineInstr::FrameDestroy);
1356     return;
1357   }
1358 
1359   NumBytes -= PrologueSaveSize;
1360   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1361 
1362   if (!hasFP(MF)) {
1363     bool RedZone = canUseRedZone(MF);
1364     // If this was a redzone leaf function, we don't need to restore the
1365     // stack pointer (but we may need to pop stack args for fastcc).
1366     if (RedZone && AfterCSRPopSize == 0)
1367       return;
1368 
1369     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
1370     int StackRestoreBytes = RedZone ? 0 : NumBytes;
1371     if (NoCalleeSaveRestore)
1372       StackRestoreBytes += AfterCSRPopSize;
1373 
1374     // If we were able to combine the local stack pop with the argument pop,
1375     // then we're done.
1376     bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0;
1377 
1378     // If we're done after this, make sure to help the load store optimizer.
1379     if (Done)
1380       adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI);
1381 
1382     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1383                     StackRestoreBytes, TII, MachineInstr::FrameDestroy, false,
1384                     NeedsWinCFI);
1385     if (Done) {
1386       if (NeedsWinCFI)
1387         BuildMI(MBB, MBB.getFirstTerminator(), DL,
1388                 TII->get(AArch64::SEH_EpilogEnd))
1389             .setMIFlag(MachineInstr::FrameDestroy);
1390       return;
1391     }
1392 
1393     NumBytes = 0;
1394   }
1395 
1396   // Restore the original stack pointer.
1397   // FIXME: Rather than doing the math here, we should instead just use
1398   // non-post-indexed loads for the restores if we aren't actually going to
1399   // be able to save any instructions.
1400   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned()))
1401     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
1402                     -AFI->getCalleeSavedStackSize() + 16, TII,
1403                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
1404   else if (NumBytes)
1405     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
1406                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
1407 
1408   // This must be placed after the callee-save restore code because that code
1409   // assumes the SP is at the same location as it was after the callee-save save
1410   // code in the prologue.
1411   if (AfterCSRPopSize) {
1412     // Find an insertion point for the first ldp so that it goes before the
1413     // shadow call stack epilog instruction. This ensures that the restore of
1414     // lr from x18 is placed after the restore from sp.
1415     auto FirstSPPopI = MBB.getFirstTerminator();
1416     while (FirstSPPopI != Begin) {
1417       auto Prev = std::prev(FirstSPPopI);
1418       if (Prev->getOpcode() != AArch64::LDRXpre ||
1419           Prev->getOperand(0).getReg() == AArch64::SP)
1420         break;
1421       FirstSPPopI = Prev;
1422     }
1423 
1424     adaptForLdStOpt(MBB, FirstSPPopI, LastPopI);
1425 
1426     emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP,
1427                     AfterCSRPopSize, TII, MachineInstr::FrameDestroy, false,
1428                     NeedsWinCFI);
1429   }
1430   if (NeedsWinCFI)
1431     BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::SEH_EpilogEnd))
1432         .setMIFlag(MachineInstr::FrameDestroy);
1433 }
1434 
1435 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1436 /// debug info.  It's the same as what we use for resolving the code-gen
1437 /// references for now.  FIXME: This can go wrong when references are
1438 /// SP-relative and simple call frames aren't used.
1439 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
1440                                                  int FI,
1441                                                  unsigned &FrameReg) const {
1442   return resolveFrameIndexReference(MF, FI, FrameReg);
1443 }
1444 
1445 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
1446                                                      int FI, unsigned &FrameReg,
1447                                                      bool PreferFP) const {
1448   const MachineFrameInfo &MFI = MF.getFrameInfo();
1449   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
1450       MF.getSubtarget().getRegisterInfo());
1451   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1452   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1453   bool IsWin64 =
1454       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1455   unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1456   int FPOffset = MFI.getObjectOffset(FI) + FixedObject + 16;
1457   int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
1458   bool isFixed = MFI.isFixedObjectIndex(FI);
1459   bool isCSR = !isFixed && MFI.getObjectOffset(FI) >=
1460                                -((int)AFI->getCalleeSavedStackSize());
1461 
1462   // Use frame pointer to reference fixed objects. Use it for locals if
1463   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1464   // reliable as a base). Make sure useFPForScavengingIndex() does the
1465   // right thing for the emergency spill slot.
1466   bool UseFP = false;
1467   if (AFI->hasStackFrame()) {
1468     // Note: Keeping the following as multiple 'if' statements rather than
1469     // merging to a single expression for readability.
1470     //
1471     // Argument access should always use the FP.
1472     if (isFixed) {
1473       UseFP = hasFP(MF);
1474     } else if (isCSR && RegInfo->needsStackRealignment(MF)) {
1475       // References to the CSR area must use FP if we're re-aligning the stack
1476       // since the dynamically-sized alignment padding is between the SP/BP and
1477       // the CSR area.
1478       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1479       UseFP = true;
1480     } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) {
1481       // If the FPOffset is negative, we have to keep in mind that the
1482       // available offset range for negative offsets is smaller than for
1483       // positive ones. If an offset is
1484       // available via the FP and the SP, use whichever is closest.
1485       bool FPOffsetFits = FPOffset >= -256;
1486       PreferFP |= Offset > -FPOffset;
1487 
1488       if (MFI.hasVarSizedObjects()) {
1489         // If we have variable sized objects, we can use either FP or BP, as the
1490         // SP offset is unknown. We can use the base pointer if we have one and
1491         // FP is not preferred. If not, we're stuck with using FP.
1492         bool CanUseBP = RegInfo->hasBasePointer(MF);
1493         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1494           UseFP = PreferFP;
1495         else if (!CanUseBP) // Can't use BP. Forced to use FP.
1496           UseFP = true;
1497         // else we can use BP and FP, but the offset from FP won't fit.
1498         // That will make us scavenge registers which we can probably avoid by
1499         // using BP. If it won't fit for BP either, we'll scavenge anyway.
1500       } else if (FPOffset >= 0) {
1501         // Use SP or FP, whichever gives us the best chance of the offset
1502         // being in range for direct access. If the FPOffset is positive,
1503         // that'll always be best, as the SP will be even further away.
1504         UseFP = true;
1505       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
1506         // Funclets access the locals contained in the parent's stack frame
1507         // via the frame pointer, so we have to use the FP in the parent
1508         // function.
1509         assert(
1510             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
1511             "Funclets should only be present on Win64");
1512         UseFP = true;
1513       } else {
1514         // We have the choice between FP and (SP or BP).
1515         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1516           UseFP = true;
1517       }
1518     }
1519   }
1520 
1521   assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
1522          "In the presence of dynamic stack pointer realignment, "
1523          "non-argument/CSR objects cannot be accessed through the frame pointer");
1524 
1525   if (UseFP) {
1526     FrameReg = RegInfo->getFrameRegister(MF);
1527     return FPOffset;
1528   }
1529 
1530   // Use the base pointer if we have one.
1531   if (RegInfo->hasBasePointer(MF))
1532     FrameReg = RegInfo->getBaseRegister();
1533   else {
1534     assert(!MFI.hasVarSizedObjects() &&
1535            "Can't use SP when we have var sized objects.");
1536     FrameReg = AArch64::SP;
1537     // If we're using the red zone for this function, the SP won't actually
1538     // be adjusted, so the offsets will be negative. They're also all
1539     // within range of the signed 9-bit immediate instructions.
1540     if (canUseRedZone(MF))
1541       Offset -= AFI->getLocalStackSize();
1542   }
1543 
1544   return Offset;
1545 }
1546 
1547 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
1548   // Do not set a kill flag on values that are also marked as live-in. This
1549   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1550   // callee saved registers.
1551   // Omitting the kill flags is conservatively correct even if the live-in
1552   // is not used after all.
1553   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1554   return getKillRegState(!IsLiveIn);
1555 }
1556 
1557 static bool produceCompactUnwindFrame(MachineFunction &MF) {
1558   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1559   AttributeList Attrs = MF.getFunction().getAttributes();
1560   return Subtarget.isTargetMachO() &&
1561          !(Subtarget.getTargetLowering()->supportSwiftError() &&
1562            Attrs.hasAttrSomewhere(Attribute::SwiftError));
1563 }
1564 
1565 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
1566                                              bool NeedsWinCFI) {
1567   // If we are generating register pairs for a Windows function that requires
1568   // EH support, then pair consecutive registers only.  There are no unwind
1569   // opcodes for saves/restores of non-consectuve register pairs.
1570   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x.
1571   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1572 
1573   // TODO: LR can be paired with any register.  We don't support this yet in
1574   // the MCLayer.  We need to add support for the save_lrpair unwind code.
1575   if (!NeedsWinCFI)
1576     return false;
1577   if (Reg2 == Reg1 + 1)
1578     return false;
1579   return true;
1580 }
1581 
1582 namespace {
1583 
1584 struct RegPairInfo {
1585   unsigned Reg1 = AArch64::NoRegister;
1586   unsigned Reg2 = AArch64::NoRegister;
1587   int FrameIdx;
1588   int Offset;
1589   enum RegType { GPR, FPR64, FPR128 } Type;
1590 
1591   RegPairInfo() = default;
1592 
1593   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
1594 };
1595 
1596 } // end anonymous namespace
1597 
1598 static void computeCalleeSaveRegisterPairs(
1599     MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
1600     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
1601     bool &NeedShadowCallStackProlog) {
1602 
1603   if (CSI.empty())
1604     return;
1605 
1606   bool NeedsWinCFI = needsWinCFI(MF);
1607   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1608   MachineFrameInfo &MFI = MF.getFrameInfo();
1609   CallingConv::ID CC = MF.getFunction().getCallingConv();
1610   unsigned Count = CSI.size();
1611   (void)CC;
1612   // MachO's compact unwind format relies on all registers being stored in
1613   // pairs.
1614   assert((!produceCompactUnwindFrame(MF) ||
1615           CC == CallingConv::PreserveMost ||
1616           (Count & 1) == 0) &&
1617          "Odd number of callee-saved regs to spill!");
1618   int Offset = AFI->getCalleeSavedStackSize();
1619   // On Linux, we will have either one or zero non-paired register.  On Windows
1620   // with CFI, we can have multiple unpaired registers in order to utilize the
1621   // available unwind codes.  This flag assures that the alignment fixup is done
1622   // only once, as intened.
1623   bool FixupDone = false;
1624   for (unsigned i = 0; i < Count; ++i) {
1625     RegPairInfo RPI;
1626     RPI.Reg1 = CSI[i].getReg();
1627 
1628     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
1629       RPI.Type = RegPairInfo::GPR;
1630     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
1631       RPI.Type = RegPairInfo::FPR64;
1632     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
1633       RPI.Type = RegPairInfo::FPR128;
1634     else
1635       llvm_unreachable("Unsupported register class.");
1636 
1637     // Add the next reg to the pair if it is in the same register class.
1638     if (i + 1 < Count) {
1639       unsigned NextReg = CSI[i + 1].getReg();
1640       switch (RPI.Type) {
1641       case RegPairInfo::GPR:
1642         if (AArch64::GPR64RegClass.contains(NextReg) &&
1643             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
1644           RPI.Reg2 = NextReg;
1645         break;
1646       case RegPairInfo::FPR64:
1647         if (AArch64::FPR64RegClass.contains(NextReg) &&
1648             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
1649           RPI.Reg2 = NextReg;
1650         break;
1651       case RegPairInfo::FPR128:
1652         if (AArch64::FPR128RegClass.contains(NextReg))
1653           RPI.Reg2 = NextReg;
1654         break;
1655       }
1656     }
1657 
1658     // If either of the registers to be saved is the lr register, it means that
1659     // we also need to save lr in the shadow call stack.
1660     if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
1661         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
1662       if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
1663         report_fatal_error("Must reserve x18 to use shadow call stack");
1664       NeedShadowCallStackProlog = true;
1665     }
1666 
1667     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
1668     // list to come in sorted by frame index so that we can issue the store
1669     // pair instructions directly. Assert if we see anything otherwise.
1670     //
1671     // The order of the registers in the list is controlled by
1672     // getCalleeSavedRegs(), so they will always be in-order, as well.
1673     assert((!RPI.isPaired() ||
1674             (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
1675            "Out of order callee saved regs!");
1676 
1677     // MachO's compact unwind format relies on all registers being stored in
1678     // adjacent register pairs.
1679     assert((!produceCompactUnwindFrame(MF) ||
1680             CC == CallingConv::PreserveMost ||
1681             (RPI.isPaired() &&
1682              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
1683               RPI.Reg1 + 1 == RPI.Reg2))) &&
1684            "Callee-save registers not saved as adjacent register pair!");
1685 
1686     RPI.FrameIdx = CSI[i].getFrameIdx();
1687 
1688     int Scale = RPI.Type == RegPairInfo::FPR128 ? 16 : 8;
1689     Offset -= RPI.isPaired() ? 2 * Scale : Scale;
1690 
1691     // Round up size of non-pair to pair size if we need to pad the
1692     // callee-save area to ensure 16-byte alignment.
1693     if (AFI->hasCalleeSaveStackFreeSpace() && !FixupDone &&
1694         RPI.Type != RegPairInfo::FPR128 && !RPI.isPaired()) {
1695       FixupDone = true;
1696       Offset -= 8;
1697       assert(Offset % 16 == 0);
1698       assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
1699       MFI.setObjectAlignment(RPI.FrameIdx, 16);
1700     }
1701 
1702     assert(Offset % Scale == 0);
1703     RPI.Offset = Offset / Scale;
1704     assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
1705            "Offset out of bounds for LDP/STP immediate");
1706 
1707     RegPairs.push_back(RPI);
1708     if (RPI.isPaired())
1709       ++i;
1710   }
1711 }
1712 
1713 bool AArch64FrameLowering::spillCalleeSavedRegisters(
1714     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1715     const std::vector<CalleeSavedInfo> &CSI,
1716     const TargetRegisterInfo *TRI) const {
1717   MachineFunction &MF = *MBB.getParent();
1718   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1719   bool NeedsWinCFI = needsWinCFI(MF);
1720   DebugLoc DL;
1721   SmallVector<RegPairInfo, 8> RegPairs;
1722 
1723   bool NeedShadowCallStackProlog = false;
1724   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1725                                  NeedShadowCallStackProlog);
1726   const MachineRegisterInfo &MRI = MF.getRegInfo();
1727 
1728   if (NeedShadowCallStackProlog) {
1729     // Shadow call stack prolog: str x30, [x18], #8
1730     BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
1731         .addReg(AArch64::X18, RegState::Define)
1732         .addReg(AArch64::LR)
1733         .addReg(AArch64::X18)
1734         .addImm(8)
1735         .setMIFlag(MachineInstr::FrameSetup);
1736 
1737     if (NeedsWinCFI)
1738       BuildMI(MBB, MI, DL, TII.get(AArch64::SEH_Nop))
1739           .setMIFlag(MachineInstr::FrameSetup);
1740 
1741     if (!MF.getFunction().hasFnAttribute(Attribute::NoUnwind)) {
1742       // Emit a CFI instruction that causes 8 to be subtracted from the value of
1743       // x18 when unwinding past this frame.
1744       static const char CFIInst[] = {
1745           dwarf::DW_CFA_val_expression,
1746           18, // register
1747           2,  // length
1748           static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
1749           static_cast<char>(-8) & 0x7f, // addend (sleb128)
1750       };
1751       unsigned CFIIndex =
1752           MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, CFIInst));
1753       BuildMI(MBB, MI, DL, TII.get(AArch64::CFI_INSTRUCTION))
1754           .addCFIIndex(CFIIndex)
1755           .setMIFlag(MachineInstr::FrameSetup);
1756     }
1757 
1758     // This instruction also makes x18 live-in to the entry block.
1759     MBB.addLiveIn(AArch64::X18);
1760   }
1761 
1762   for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
1763        ++RPII) {
1764     RegPairInfo RPI = *RPII;
1765     unsigned Reg1 = RPI.Reg1;
1766     unsigned Reg2 = RPI.Reg2;
1767     unsigned StrOpc;
1768 
1769     // Issue sequence of spills for cs regs.  The first spill may be converted
1770     // to a pre-decrement store later by emitPrologue if the callee-save stack
1771     // area allocation can't be combined with the local stack area allocation.
1772     // For example:
1773     //    stp     x22, x21, [sp, #0]     // addImm(+0)
1774     //    stp     x20, x19, [sp, #16]    // addImm(+2)
1775     //    stp     fp, lr, [sp, #32]      // addImm(+4)
1776     // Rationale: This sequence saves uop updates compared to a sequence of
1777     // pre-increment spills like stp xi,xj,[sp,#-16]!
1778     // Note: Similar rationale and sequence for restores in epilog.
1779     unsigned Size, Align;
1780     switch (RPI.Type) {
1781     case RegPairInfo::GPR:
1782        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
1783        Size = 8;
1784        Align = 8;
1785        break;
1786     case RegPairInfo::FPR64:
1787        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
1788        Size = 8;
1789        Align = 8;
1790        break;
1791     case RegPairInfo::FPR128:
1792        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
1793        Size = 16;
1794        Align = 16;
1795        break;
1796     }
1797     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
1798                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1799                dbgs() << ") -> fi#(" << RPI.FrameIdx;
1800                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1801                dbgs() << ")\n");
1802 
1803     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
1804            "Windows unwdinding requires a consecutive (FP,LR) pair");
1805     // Windows unwind codes require consecutive registers if registers are
1806     // paired.  Make the switch here, so that the code below will save (x,x+1)
1807     // and not (x+1,x).
1808     unsigned FrameIdxReg1 = RPI.FrameIdx;
1809     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
1810     if (NeedsWinCFI && RPI.isPaired()) {
1811       std::swap(Reg1, Reg2);
1812       std::swap(FrameIdxReg1, FrameIdxReg2);
1813     }
1814     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
1815     if (!MRI.isReserved(Reg1))
1816       MBB.addLiveIn(Reg1);
1817     if (RPI.isPaired()) {
1818       if (!MRI.isReserved(Reg2))
1819         MBB.addLiveIn(Reg2);
1820       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
1821       MIB.addMemOperand(MF.getMachineMemOperand(
1822           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
1823           MachineMemOperand::MOStore, Size, Align));
1824     }
1825     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1826         .addReg(AArch64::SP)
1827         .addImm(RPI.Offset) // [sp, #offset*scale],
1828                             // where factor*scale is implicit
1829         .setMIFlag(MachineInstr::FrameSetup);
1830     MIB.addMemOperand(MF.getMachineMemOperand(
1831         MachinePointerInfo::getFixedStack(MF,FrameIdxReg1),
1832         MachineMemOperand::MOStore, Size, Align));
1833     if (NeedsWinCFI)
1834       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
1835 
1836   }
1837   return true;
1838 }
1839 
1840 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1841     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1842     std::vector<CalleeSavedInfo> &CSI,
1843     const TargetRegisterInfo *TRI) const {
1844   MachineFunction &MF = *MBB.getParent();
1845   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1846   DebugLoc DL;
1847   SmallVector<RegPairInfo, 8> RegPairs;
1848   bool NeedsWinCFI = needsWinCFI(MF);
1849 
1850   if (MI != MBB.end())
1851     DL = MI->getDebugLoc();
1852 
1853   bool NeedShadowCallStackProlog = false;
1854   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1855                                  NeedShadowCallStackProlog);
1856 
1857   auto EmitMI = [&](const RegPairInfo &RPI) {
1858     unsigned Reg1 = RPI.Reg1;
1859     unsigned Reg2 = RPI.Reg2;
1860 
1861     // Issue sequence of restores for cs regs. The last restore may be converted
1862     // to a post-increment load later by emitEpilogue if the callee-save stack
1863     // area allocation can't be combined with the local stack area allocation.
1864     // For example:
1865     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
1866     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
1867     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
1868     // Note: see comment in spillCalleeSavedRegisters()
1869     unsigned LdrOpc;
1870     unsigned Size, Align;
1871     switch (RPI.Type) {
1872     case RegPairInfo::GPR:
1873        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1874        Size = 8;
1875        Align = 8;
1876        break;
1877     case RegPairInfo::FPR64:
1878        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
1879        Size = 8;
1880        Align = 8;
1881        break;
1882     case RegPairInfo::FPR128:
1883        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
1884        Size = 16;
1885        Align = 16;
1886        break;
1887     }
1888     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
1889                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1890                dbgs() << ") -> fi#(" << RPI.FrameIdx;
1891                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1892                dbgs() << ")\n");
1893 
1894     // Windows unwind codes require consecutive registers if registers are
1895     // paired.  Make the switch here, so that the code below will save (x,x+1)
1896     // and not (x+1,x).
1897     unsigned FrameIdxReg1 = RPI.FrameIdx;
1898     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
1899     if (NeedsWinCFI && RPI.isPaired()) {
1900       std::swap(Reg1, Reg2);
1901       std::swap(FrameIdxReg1, FrameIdxReg2);
1902     }
1903     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
1904     if (RPI.isPaired()) {
1905       MIB.addReg(Reg2, getDefRegState(true));
1906       MIB.addMemOperand(MF.getMachineMemOperand(
1907           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
1908           MachineMemOperand::MOLoad, Size, Align));
1909     }
1910     MIB.addReg(Reg1, getDefRegState(true))
1911         .addReg(AArch64::SP)
1912         .addImm(RPI.Offset) // [sp, #offset*scale]
1913                             // where factor*scale is implicit
1914         .setMIFlag(MachineInstr::FrameDestroy);
1915     MIB.addMemOperand(MF.getMachineMemOperand(
1916         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
1917         MachineMemOperand::MOLoad, Size, Align));
1918     if (NeedsWinCFI)
1919       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
1920   };
1921   if (ReverseCSRRestoreSeq)
1922     for (const RegPairInfo &RPI : reverse(RegPairs))
1923       EmitMI(RPI);
1924   else
1925     for (const RegPairInfo &RPI : RegPairs)
1926       EmitMI(RPI);
1927 
1928   if (NeedShadowCallStackProlog) {
1929     // Shadow call stack epilog: ldr x30, [x18, #-8]!
1930     BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
1931         .addReg(AArch64::X18, RegState::Define)
1932         .addReg(AArch64::LR, RegState::Define)
1933         .addReg(AArch64::X18)
1934         .addImm(-8)
1935         .setMIFlag(MachineInstr::FrameDestroy);
1936   }
1937 
1938   return true;
1939 }
1940 
1941 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1942                                                 BitVector &SavedRegs,
1943                                                 RegScavenger *RS) const {
1944   // All calls are tail calls in GHC calling conv, and functions have no
1945   // prologue/epilogue.
1946   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1947     return;
1948 
1949   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1950   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
1951       MF.getSubtarget().getRegisterInfo());
1952   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1953   unsigned UnspilledCSGPR = AArch64::NoRegister;
1954   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
1955 
1956   MachineFrameInfo &MFI = MF.getFrameInfo();
1957   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
1958 
1959   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
1960                                 ? RegInfo->getBaseRegister()
1961                                 : (unsigned)AArch64::NoRegister;
1962 
1963   unsigned ExtraCSSpill = 0;
1964   // Figure out which callee-saved registers to save/restore.
1965   for (unsigned i = 0; CSRegs[i]; ++i) {
1966     const unsigned Reg = CSRegs[i];
1967 
1968     // Add the base pointer register to SavedRegs if it is callee-save.
1969     if (Reg == BasePointerReg)
1970       SavedRegs.set(Reg);
1971 
1972     bool RegUsed = SavedRegs.test(Reg);
1973     unsigned PairedReg = CSRegs[i ^ 1];
1974     if (!RegUsed) {
1975       if (AArch64::GPR64RegClass.contains(Reg) &&
1976           !RegInfo->isReservedReg(MF, Reg)) {
1977         UnspilledCSGPR = Reg;
1978         UnspilledCSGPRPaired = PairedReg;
1979       }
1980       continue;
1981     }
1982 
1983     // MachO's compact unwind format relies on all registers being stored in
1984     // pairs.
1985     // FIXME: the usual format is actually better if unwinding isn't needed.
1986     if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister &&
1987         !SavedRegs.test(PairedReg)) {
1988       SavedRegs.set(PairedReg);
1989       if (AArch64::GPR64RegClass.contains(PairedReg) &&
1990           !RegInfo->isReservedReg(MF, PairedReg))
1991         ExtraCSSpill = PairedReg;
1992     }
1993   }
1994 
1995   // Calculates the callee saved stack size.
1996   unsigned CSStackSize = 0;
1997   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1998   const MachineRegisterInfo &MRI = MF.getRegInfo();
1999   for (unsigned Reg : SavedRegs.set_bits())
2000     CSStackSize += TRI->getRegSizeInBits(Reg, MRI) / 8;
2001 
2002   // Save number of saved regs, so we can easily update CSStackSize later.
2003   unsigned NumSavedRegs = SavedRegs.count();
2004 
2005   // The frame record needs to be created by saving the appropriate registers
2006   unsigned EstimatedStackSize = MFI.estimateStackSize(MF);
2007   if (hasFP(MF) ||
2008       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2009     SavedRegs.set(AArch64::FP);
2010     SavedRegs.set(AArch64::LR);
2011   }
2012 
2013   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
2014              for (unsigned Reg
2015                   : SavedRegs.set_bits()) dbgs()
2016              << ' ' << printReg(Reg, RegInfo);
2017              dbgs() << "\n";);
2018 
2019   // If any callee-saved registers are used, the frame cannot be eliminated.
2020   bool CanEliminateFrame = SavedRegs.count() == 0;
2021 
2022   // The CSR spill slots have not been allocated yet, so estimateStackSize
2023   // won't include them.
2024   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2025   bool BigStack = (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
2026   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2027     AFI->setHasStackFrame(true);
2028 
2029   // Estimate if we might need to scavenge a register at some point in order
2030   // to materialize a stack offset. If so, either spill one additional
2031   // callee-saved register or reserve a special spill slot to facilitate
2032   // register scavenging. If we already spilled an extra callee-saved register
2033   // above to keep the number of spills even, we don't need to do anything else
2034   // here.
2035   if (BigStack) {
2036     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
2037       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2038                         << " to get a scratch register.\n");
2039       SavedRegs.set(UnspilledCSGPR);
2040       // MachO's compact unwind format relies on all registers being stored in
2041       // pairs, so if we need to spill one extra for BigStack, then we need to
2042       // store the pair.
2043       if (produceCompactUnwindFrame(MF))
2044         SavedRegs.set(UnspilledCSGPRPaired);
2045       ExtraCSSpill = UnspilledCSGPRPaired;
2046     }
2047 
2048     // If we didn't find an extra callee-saved register to spill, create
2049     // an emergency spill slot.
2050     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2051       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2052       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2053       unsigned Size = TRI->getSpillSize(RC);
2054       unsigned Align = TRI->getSpillAlignment(RC);
2055       int FI = MFI.CreateStackObject(Size, Align, false);
2056       RS->addScavengingFrameIndex(FI);
2057       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2058                         << " as the emergency spill slot.\n");
2059     }
2060   }
2061 
2062   // Adding the size of additional 64bit GPR saves.
2063   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2064   unsigned AlignedCSStackSize = alignTo(CSStackSize, 16);
2065   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2066                << EstimatedStackSize + AlignedCSStackSize
2067                << " bytes.\n");
2068 
2069   // Round up to register pair alignment to avoid additional SP adjustment
2070   // instructions.
2071   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2072   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2073 }
2074 
2075 bool AArch64FrameLowering::enableStackSlotScavenging(
2076     const MachineFunction &MF) const {
2077   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2078   return AFI->hasCalleeSaveStackFreeSpace();
2079 }
2080 
2081 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
2082     MachineFunction &MF, RegScavenger *RS) const {
2083   // If this function isn't doing Win64-style C++ EH, we don't need to do
2084   // anything.
2085   if (!MF.hasEHFunclets())
2086     return;
2087   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2088   MachineFrameInfo &MFI = MF.getFrameInfo();
2089   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
2090 
2091   MachineBasicBlock &MBB = MF.front();
2092   auto MBBI = MBB.begin();
2093   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2094     ++MBBI;
2095 
2096   if (MBBI->isTerminator())
2097     return;
2098 
2099   // Create an UnwindHelp object.
2100   int UnwindHelpFI =
2101       MFI.CreateStackObject(/*size*/8, /*alignment*/16, false);
2102   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
2103   // We need to store -2 into the UnwindHelp object at the start of the
2104   // function.
2105   DebugLoc DL;
2106   RS->enterBasicBlock(MBB);
2107   unsigned DstReg = RS->scavengeRegister(&AArch64::GPR64RegClass, MBBI, 0);
2108   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
2109   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
2110       .addReg(DstReg, getKillRegState(true))
2111       .addFrameIndex(UnwindHelpFI)
2112       .addImm(0);
2113 }
2114 
2115 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP before
2116 /// the update.  This is easily retrieved as it is exactly the offset that is set
2117 /// in processFunctionBeforeFrameFinalized.
2118 int AArch64FrameLowering::getFrameIndexReferencePreferSP(
2119     const MachineFunction &MF, int FI, unsigned &FrameReg,
2120     bool IgnoreSPUpdates) const {
2121   const MachineFrameInfo &MFI = MF.getFrameInfo();
2122   LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
2123                     << MFI.getObjectOffset(FI) << "\n");
2124   FrameReg = AArch64::SP;
2125   return MFI.getObjectOffset(FI);
2126 }
2127 
2128 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
2129 /// the parent's frame pointer
2130 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
2131     const MachineFunction &MF) const {
2132   return 0;
2133 }
2134 
2135 /// Funclets only need to account for space for the callee saved registers,
2136 /// as the locals are accounted for in the parent's stack frame.
2137 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
2138     const MachineFunction &MF) const {
2139   // This is the size of the pushed CSRs.
2140   unsigned CSSize =
2141       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
2142   // This is the amount of stack a funclet needs to allocate.
2143   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
2144                  getStackAlignment());
2145 }
2146