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