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