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