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 "llvm/ADT/SmallVector.h"
101 #include "llvm/ADT/Statistic.h"
102 #include "llvm/CodeGen/LivePhysRegs.h"
103 #include "llvm/CodeGen/MachineBasicBlock.h"
104 #include "llvm/CodeGen/MachineFrameInfo.h"
105 #include "llvm/CodeGen/MachineFunction.h"
106 #include "llvm/CodeGen/MachineInstr.h"
107 #include "llvm/CodeGen/MachineInstrBuilder.h"
108 #include "llvm/CodeGen/MachineMemOperand.h"
109 #include "llvm/CodeGen/MachineModuleInfo.h"
110 #include "llvm/CodeGen/MachineOperand.h"
111 #include "llvm/CodeGen/MachineRegisterInfo.h"
112 #include "llvm/CodeGen/RegisterScavenging.h"
113 #include "llvm/IR/Attributes.h"
114 #include "llvm/IR/CallingConv.h"
115 #include "llvm/IR/DataLayout.h"
116 #include "llvm/IR/DebugLoc.h"
117 #include "llvm/IR/Function.h"
118 #include "llvm/MC/MCDwarf.h"
119 #include "llvm/Support/CommandLine.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/MathExtras.h"
123 #include "llvm/Support/raw_ostream.h"
124 #include "llvm/Target/TargetInstrInfo.h"
125 #include "llvm/Target/TargetMachine.h"
126 #include "llvm/Target/TargetOptions.h"
127 #include "llvm/Target/TargetRegisterInfo.h"
128 #include "llvm/Target/TargetSubtargetInfo.h"
129 #include <cassert>
130 #include <cstdint>
131 #include <iterator>
132 #include <vector>
133 
134 using namespace llvm;
135 
136 #define DEBUG_TYPE "frame-info"
137 
138 static cl::opt<bool> EnableRedZone("aarch64-redzone",
139                                    cl::desc("enable use of redzone on AArch64"),
140                                    cl::init(false), cl::Hidden);
141 
142 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
143 
144 /// Look at each instruction that references stack frames and return the stack
145 /// size limit beyond which some of these instructions will require a scratch
146 /// register during their expansion later.
147 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
148   // FIXME: For now, just conservatively guestimate based on unscaled indexing
149   // range. We'll end up allocating an unnecessary spill slot a lot, but
150   // realistically that's not a big deal at this stage of the game.
151   for (MachineBasicBlock &MBB : MF) {
152     for (MachineInstr &MI : MBB) {
153       if (MI.isDebugValue() || MI.isPseudo() ||
154           MI.getOpcode() == AArch64::ADDXri ||
155           MI.getOpcode() == AArch64::ADDSXri)
156         continue;
157 
158       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
159         if (!MI.getOperand(i).isFI())
160           continue;
161 
162         int Offset = 0;
163         if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
164             AArch64FrameOffsetCannotUpdate)
165           return 0;
166       }
167     }
168   }
169   return 255;
170 }
171 
172 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
173   if (!EnableRedZone)
174     return false;
175   // Don't use the red zone if the function explicitly asks us not to.
176   // This is typically used for kernel code.
177   if (MF.getFunction()->hasFnAttribute(Attribute::NoRedZone))
178     return false;
179 
180   const MachineFrameInfo &MFI = MF.getFrameInfo();
181   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
182   unsigned NumBytes = AFI->getLocalStackSize();
183 
184   return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128);
185 }
186 
187 /// hasFP - Return true if the specified function should have a dedicated frame
188 /// pointer register.
189 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
190   const MachineFrameInfo &MFI = MF.getFrameInfo();
191   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
192   // Retain behavior of always omitting the FP for leaf functions when possible.
193   return (MFI.hasCalls() &&
194           MF.getTarget().Options.DisableFramePointerElim(MF)) ||
195          MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
196          MFI.hasStackMap() || MFI.hasPatchPoint() ||
197          RegInfo->needsStackRealignment(MF);
198 }
199 
200 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
201 /// not required, we reserve argument space for call sites in the function
202 /// immediately on entry to the current function.  This eliminates the need for
203 /// add/sub sp brackets around call sites.  Returns true if the call frame is
204 /// included as part of the stack frame.
205 bool
206 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
207   return !MF.getFrameInfo().hasVarSizedObjects();
208 }
209 
210 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
211     MachineFunction &MF, MachineBasicBlock &MBB,
212     MachineBasicBlock::iterator I) const {
213   const AArch64InstrInfo *TII =
214       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
215   DebugLoc DL = I->getDebugLoc();
216   unsigned Opc = I->getOpcode();
217   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
218   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
219 
220   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
221   if (!TFI->hasReservedCallFrame(MF)) {
222     unsigned Align = getStackAlignment();
223 
224     int64_t Amount = I->getOperand(0).getImm();
225     Amount = alignTo(Amount, Align);
226     if (!IsDestroy)
227       Amount = -Amount;
228 
229     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
230     // doesn't have to pop anything), then the first operand will be zero too so
231     // this adjustment is a no-op.
232     if (CalleePopAmount == 0) {
233       // FIXME: in-function stack adjustment for calls is limited to 24-bits
234       // because there's no guaranteed temporary register available.
235       //
236       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
237       // 1) For offset <= 12-bit, we use LSL #0
238       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
239       // LSL #0, and the other uses LSL #12.
240       //
241       // Most call frames will be allocated at the start of a function so
242       // this is OK, but it is a limitation that needs dealing with.
243       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
244       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
245     }
246   } else if (CalleePopAmount != 0) {
247     // If the calling convention demands that the callee pops arguments from the
248     // stack, we want to add it back if we have a reserved call frame.
249     assert(CalleePopAmount < 0xffffff && "call frame too large");
250     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
251                     TII);
252   }
253   return MBB.erase(I);
254 }
255 
256 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
257     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
258   MachineFunction &MF = *MBB.getParent();
259   MachineFrameInfo &MFI = MF.getFrameInfo();
260   const TargetSubtargetInfo &STI = MF.getSubtarget();
261   const MCRegisterInfo *MRI = STI.getRegisterInfo();
262   const TargetInstrInfo *TII = STI.getInstrInfo();
263   DebugLoc DL = MBB.findDebugLoc(MBBI);
264 
265   // Add callee saved registers to move list.
266   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
267   if (CSI.empty())
268     return;
269 
270   for (const auto &Info : CSI) {
271     unsigned Reg = Info.getReg();
272     int64_t Offset =
273         MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
274     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
275     unsigned CFIIndex = MF.addFrameInst(
276         MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
277     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
278         .addCFIIndex(CFIIndex)
279         .setMIFlags(MachineInstr::FrameSetup);
280   }
281 }
282 
283 // Find a scratch register that we can use at the start of the prologue to
284 // re-align the stack pointer.  We avoid using callee-save registers since they
285 // may appear to be free when this is called from canUseAsPrologue (during
286 // shrink wrapping), but then no longer be free when this is called from
287 // emitPrologue.
288 //
289 // FIXME: This is a bit conservative, since in the above case we could use one
290 // of the callee-save registers as a scratch temp to re-align the stack pointer,
291 // but we would then have to make sure that we were in fact saving at least one
292 // callee-save register in the prologue, which is additional complexity that
293 // doesn't seem worth the benefit.
294 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
295   MachineFunction *MF = MBB->getParent();
296 
297   // If MBB is an entry block, use X9 as the scratch register
298   if (&MF->front() == MBB)
299     return AArch64::X9;
300 
301   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
302   const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
303   LivePhysRegs LiveRegs(TRI);
304   LiveRegs.addLiveIns(*MBB);
305 
306   // Mark callee saved registers as used so we will not choose them.
307   const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(MF);
308   for (unsigned i = 0; CSRegs[i]; ++i)
309     LiveRegs.addReg(CSRegs[i]);
310 
311   // Prefer X9 since it was historically used for the prologue scratch reg.
312   const MachineRegisterInfo &MRI = MF->getRegInfo();
313   if (LiveRegs.available(MRI, AArch64::X9))
314     return AArch64::X9;
315 
316   for (unsigned Reg : AArch64::GPR64RegClass) {
317     if (LiveRegs.available(MRI, Reg))
318       return Reg;
319   }
320   return AArch64::NoRegister;
321 }
322 
323 bool AArch64FrameLowering::canUseAsPrologue(
324     const MachineBasicBlock &MBB) const {
325   const MachineFunction *MF = MBB.getParent();
326   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
327   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
328   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
329 
330   // Don't need a scratch register if we're not going to re-align the stack.
331   if (!RegInfo->needsStackRealignment(*MF))
332     return true;
333   // Otherwise, we can use any block as long as it has a scratch register
334   // available.
335   return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
336 }
337 
338 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
339     MachineFunction &MF, unsigned StackBumpBytes) const {
340   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
341   const MachineFrameInfo &MFI = MF.getFrameInfo();
342   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
343   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
344 
345   if (AFI->getLocalStackSize() == 0)
346     return false;
347 
348   // 512 is the maximum immediate for stp/ldp that will be used for
349   // callee-save save/restores
350   if (StackBumpBytes >= 512)
351     return false;
352 
353   if (MFI.hasVarSizedObjects())
354     return false;
355 
356   if (RegInfo->needsStackRealignment(MF))
357     return false;
358 
359   // This isn't strictly necessary, but it simplifies things a bit since the
360   // current RedZone handling code assumes the SP is adjusted by the
361   // callee-save save/restore code.
362   if (canUseRedZone(MF))
363     return false;
364 
365   return true;
366 }
367 
368 // Convert callee-save register save/restore instruction to do stack pointer
369 // decrement/increment to allocate/deallocate the callee-save stack area by
370 // converting store/load to use pre/post increment version.
371 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
372     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
373     const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc) {
374   unsigned NewOpc;
375   bool NewIsUnscaled = false;
376   switch (MBBI->getOpcode()) {
377   default:
378     llvm_unreachable("Unexpected callee-save save/restore opcode!");
379   case AArch64::STPXi:
380     NewOpc = AArch64::STPXpre;
381     break;
382   case AArch64::STPDi:
383     NewOpc = AArch64::STPDpre;
384     break;
385   case AArch64::STRXui:
386     NewOpc = AArch64::STRXpre;
387     NewIsUnscaled = true;
388     break;
389   case AArch64::STRDui:
390     NewOpc = AArch64::STRDpre;
391     NewIsUnscaled = true;
392     break;
393   case AArch64::LDPXi:
394     NewOpc = AArch64::LDPXpost;
395     break;
396   case AArch64::LDPDi:
397     NewOpc = AArch64::LDPDpost;
398     break;
399   case AArch64::LDRXui:
400     NewOpc = AArch64::LDRXpost;
401     NewIsUnscaled = true;
402     break;
403   case AArch64::LDRDui:
404     NewOpc = AArch64::LDRDpost;
405     NewIsUnscaled = true;
406     break;
407   }
408 
409   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
410   MIB.addReg(AArch64::SP, RegState::Define);
411 
412   // Copy all operands other than the immediate offset.
413   unsigned OpndIdx = 0;
414   for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
415        ++OpndIdx)
416     MIB.add(MBBI->getOperand(OpndIdx));
417 
418   assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
419          "Unexpected immediate offset in first/last callee-save save/restore "
420          "instruction!");
421   assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
422          "Unexpected base register in callee-save save/restore instruction!");
423   // Last operand is immediate offset that needs fixing.
424   assert(CSStackSizeInc % 8 == 0);
425   int64_t CSStackSizeIncImm = CSStackSizeInc;
426   if (!NewIsUnscaled)
427     CSStackSizeIncImm /= 8;
428   MIB.addImm(CSStackSizeIncImm);
429 
430   MIB.setMIFlags(MBBI->getFlags());
431   MIB.setMemRefs(MBBI->memoperands_begin(), MBBI->memoperands_end());
432 
433   return std::prev(MBB.erase(MBBI));
434 }
435 
436 // Fixup callee-save register save/restore instructions to take into account
437 // combined SP bump by adding the local stack size to the stack offsets.
438 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
439                                               unsigned LocalStackSize) {
440   unsigned Opc = MI.getOpcode();
441   (void)Opc;
442   assert((Opc == AArch64::STPXi || Opc == AArch64::STPDi ||
443           Opc == AArch64::STRXui || Opc == AArch64::STRDui ||
444           Opc == AArch64::LDPXi || Opc == AArch64::LDPDi ||
445           Opc == AArch64::LDRXui || Opc == AArch64::LDRDui) &&
446          "Unexpected callee-save save/restore opcode!");
447 
448   unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
449   assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
450          "Unexpected base register in callee-save save/restore instruction!");
451   // Last operand is immediate offset that needs fixing.
452   MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
453   // All generated opcodes have scaled offsets.
454   assert(LocalStackSize % 8 == 0);
455   OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / 8);
456 }
457 
458 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
459                                         MachineBasicBlock &MBB) const {
460   MachineBasicBlock::iterator MBBI = MBB.begin();
461   const MachineFrameInfo &MFI = MF.getFrameInfo();
462   const Function *Fn = MF.getFunction();
463   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
464   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
465   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
466   MachineModuleInfo &MMI = MF.getMMI();
467   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
468   bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
469   bool HasFP = hasFP(MF);
470 
471   // Debug location must be unknown since the first debug location is used
472   // to determine the end of the prologue.
473   DebugLoc DL;
474 
475   // All calls are tail calls in GHC calling conv, and functions have no
476   // prologue/epilogue.
477   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
478     return;
479 
480   int NumBytes = (int)MFI.getStackSize();
481   if (!AFI->hasStackFrame()) {
482     assert(!HasFP && "unexpected function without stack frame but with FP");
483 
484     // All of the stack allocation is for locals.
485     AFI->setLocalStackSize(NumBytes);
486 
487     if (!NumBytes)
488       return;
489     // REDZONE: If the stack size is less than 128 bytes, we don't need
490     // to actually allocate.
491     if (canUseRedZone(MF))
492       ++NumRedZoneFunctions;
493     else {
494       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
495                       MachineInstr::FrameSetup);
496 
497       // Label used to tie together the PROLOG_LABEL and the MachineMoves.
498       MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
499       // Encode the stack size of the leaf function.
500       unsigned CFIIndex = MF.addFrameInst(
501           MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
502       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
503           .addCFIIndex(CFIIndex)
504           .setMIFlags(MachineInstr::FrameSetup);
505     }
506     return;
507   }
508 
509   auto CSStackSize = AFI->getCalleeSavedStackSize();
510   // All of the remaining stack allocations are for locals.
511   AFI->setLocalStackSize(NumBytes - CSStackSize);
512 
513   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
514   if (CombineSPBump) {
515     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
516                     MachineInstr::FrameSetup);
517     NumBytes = 0;
518   } else if (CSStackSize != 0) {
519     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(MBB, MBBI, DL, TII,
520                                                      -CSStackSize);
521     NumBytes -= CSStackSize;
522   }
523   assert(NumBytes >= 0 && "Negative stack allocation size!?");
524 
525   // Move past the saves of the callee-saved registers, fixing up the offsets
526   // and pre-inc if we decided to combine the callee-save and local stack
527   // pointer bump above.
528   MachineBasicBlock::iterator End = MBB.end();
529   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
530     if (CombineSPBump)
531       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize());
532     ++MBBI;
533   }
534   if (HasFP) {
535     // Only set up FP if we actually need to. Frame pointer is fp = sp - 16.
536     int FPOffset = CSStackSize - 16;
537     if (CombineSPBump)
538       FPOffset += AFI->getLocalStackSize();
539 
540     // Issue    sub fp, sp, FPOffset or
541     //          mov fp,sp          when FPOffset is zero.
542     // Note: All stores of callee-saved registers are marked as "FrameSetup".
543     // This code marks the instruction(s) that set the FP also.
544     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
545                     MachineInstr::FrameSetup);
546   }
547 
548   // Allocate space for the rest of the frame.
549   if (NumBytes) {
550     const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
551     unsigned scratchSPReg = AArch64::SP;
552 
553     if (NeedsRealignment) {
554       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
555       assert(scratchSPReg != AArch64::NoRegister);
556     }
557 
558     // If we're a leaf function, try using the red zone.
559     if (!canUseRedZone(MF))
560       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
561       // the correct value here, as NumBytes also includes padding bytes,
562       // which shouldn't be counted here.
563       emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
564                       MachineInstr::FrameSetup);
565 
566     if (NeedsRealignment) {
567       const unsigned Alignment = MFI.getMaxAlignment();
568       const unsigned NrBitsToZero = countTrailingZeros(Alignment);
569       assert(NrBitsToZero > 1);
570       assert(scratchSPReg != AArch64::SP);
571 
572       // SUB X9, SP, NumBytes
573       //   -- X9 is temporary register, so shouldn't contain any live data here,
574       //   -- free to use. This is already produced by emitFrameOffset above.
575       // AND SP, X9, 0b11111...0000
576       // The logical immediates have a non-trivial encoding. The following
577       // formula computes the encoded immediate with all ones but
578       // NrBitsToZero zero bits as least significant bits.
579       uint32_t andMaskEncoded = (1 << 12)                         // = N
580                                 | ((64 - NrBitsToZero) << 6)      // immr
581                                 | ((64 - NrBitsToZero - 1) << 0); // imms
582 
583       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
584           .addReg(scratchSPReg, RegState::Kill)
585           .addImm(andMaskEncoded);
586       AFI->setStackRealigned(true);
587     }
588   }
589 
590   // If we need a base pointer, set it up here. It's whatever the value of the
591   // stack pointer is at this point. Any variable size objects will be allocated
592   // after this, so we can still use the base pointer to reference locals.
593   //
594   // FIXME: Clarify FrameSetup flags here.
595   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
596   // needed.
597   if (RegInfo->hasBasePointer(MF)) {
598     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
599                      false);
600   }
601 
602   if (needsFrameMoves) {
603     const DataLayout &TD = MF.getDataLayout();
604     const int StackGrowth = -TD.getPointerSize(0);
605     unsigned FramePtr = RegInfo->getFrameRegister(MF);
606     // An example of the prologue:
607     //
608     //     .globl __foo
609     //     .align 2
610     //  __foo:
611     // Ltmp0:
612     //     .cfi_startproc
613     //     .cfi_personality 155, ___gxx_personality_v0
614     // Leh_func_begin:
615     //     .cfi_lsda 16, Lexception33
616     //
617     //     stp  xa,bx, [sp, -#offset]!
618     //     ...
619     //     stp  x28, x27, [sp, #offset-32]
620     //     stp  fp, lr, [sp, #offset-16]
621     //     add  fp, sp, #offset - 16
622     //     sub  sp, sp, #1360
623     //
624     // The Stack:
625     //       +-------------------------------------------+
626     // 10000 | ........ | ........ | ........ | ........ |
627     // 10004 | ........ | ........ | ........ | ........ |
628     //       +-------------------------------------------+
629     // 10008 | ........ | ........ | ........ | ........ |
630     // 1000c | ........ | ........ | ........ | ........ |
631     //       +===========================================+
632     // 10010 |                X28 Register               |
633     // 10014 |                X28 Register               |
634     //       +-------------------------------------------+
635     // 10018 |                X27 Register               |
636     // 1001c |                X27 Register               |
637     //       +===========================================+
638     // 10020 |                Frame Pointer              |
639     // 10024 |                Frame Pointer              |
640     //       +-------------------------------------------+
641     // 10028 |                Link Register              |
642     // 1002c |                Link Register              |
643     //       +===========================================+
644     // 10030 | ........ | ........ | ........ | ........ |
645     // 10034 | ........ | ........ | ........ | ........ |
646     //       +-------------------------------------------+
647     // 10038 | ........ | ........ | ........ | ........ |
648     // 1003c | ........ | ........ | ........ | ........ |
649     //       +-------------------------------------------+
650     //
651     //     [sp] = 10030        ::    >>initial value<<
652     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
653     //     fp = sp == 10020    ::  mov fp, sp
654     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
655     //     sp == 10010         ::    >>final value<<
656     //
657     // The frame pointer (w29) points to address 10020. If we use an offset of
658     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
659     // for w27, and -32 for w28:
660     //
661     //  Ltmp1:
662     //     .cfi_def_cfa w29, 16
663     //  Ltmp2:
664     //     .cfi_offset w30, -8
665     //  Ltmp3:
666     //     .cfi_offset w29, -16
667     //  Ltmp4:
668     //     .cfi_offset w27, -24
669     //  Ltmp5:
670     //     .cfi_offset w28, -32
671 
672     if (HasFP) {
673       // Define the current CFA rule to use the provided FP.
674       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
675       unsigned CFIIndex = MF.addFrameInst(
676           MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
677       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
678           .addCFIIndex(CFIIndex)
679           .setMIFlags(MachineInstr::FrameSetup);
680     } else {
681       // Encode the stack size of the leaf function.
682       unsigned CFIIndex = MF.addFrameInst(
683           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
684       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
685           .addCFIIndex(CFIIndex)
686           .setMIFlags(MachineInstr::FrameSetup);
687     }
688 
689     // Now emit the moves for whatever callee saved regs we have (including FP,
690     // LR if those are saved).
691     emitCalleeSavedFrameMoves(MBB, MBBI);
692   }
693 }
694 
695 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
696                                         MachineBasicBlock &MBB) const {
697   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
698   MachineFrameInfo &MFI = MF.getFrameInfo();
699   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
700   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
701   DebugLoc DL;
702   bool IsTailCallReturn = false;
703   if (MBB.end() != MBBI) {
704     DL = MBBI->getDebugLoc();
705     unsigned RetOpcode = MBBI->getOpcode();
706     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
707       RetOpcode == AArch64::TCRETURNri;
708   }
709   int NumBytes = MFI.getStackSize();
710   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
711 
712   // All calls are tail calls in GHC calling conv, and functions have no
713   // prologue/epilogue.
714   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
715     return;
716 
717   // Initial and residual are named for consistency with the prologue. Note that
718   // in the epilogue, the residual adjustment is executed first.
719   uint64_t ArgumentPopSize = 0;
720   if (IsTailCallReturn) {
721     MachineOperand &StackAdjust = MBBI->getOperand(1);
722 
723     // For a tail-call in a callee-pops-arguments environment, some or all of
724     // the stack may actually be in use for the call's arguments, this is
725     // calculated during LowerCall and consumed here...
726     ArgumentPopSize = StackAdjust.getImm();
727   } else {
728     // ... otherwise the amount to pop is *all* of the argument space,
729     // conveniently stored in the MachineFunctionInfo by
730     // LowerFormalArguments. This will, of course, be zero for the C calling
731     // convention.
732     ArgumentPopSize = AFI->getArgumentStackToRestore();
733   }
734 
735   // The stack frame should be like below,
736   //
737   //      ----------------------                     ---
738   //      |                    |                      |
739   //      | BytesInStackArgArea|              CalleeArgStackSize
740   //      | (NumReusableBytes) |                (of tail call)
741   //      |                    |                     ---
742   //      |                    |                      |
743   //      ---------------------|        ---           |
744   //      |                    |         |            |
745   //      |   CalleeSavedReg   |         |            |
746   //      | (CalleeSavedStackSize)|      |            |
747   //      |                    |         |            |
748   //      ---------------------|         |         NumBytes
749   //      |                    |     StackSize  (StackAdjustUp)
750   //      |   LocalStackSize   |         |            |
751   //      | (covering callee   |         |            |
752   //      |       args)        |         |            |
753   //      |                    |         |            |
754   //      ----------------------        ---          ---
755   //
756   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
757   //             = StackSize + ArgumentPopSize
758   //
759   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
760   // it as the 2nd argument of AArch64ISD::TC_RETURN.
761 
762   auto CSStackSize = AFI->getCalleeSavedStackSize();
763   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
764 
765   if (!CombineSPBump && CSStackSize != 0)
766     convertCalleeSaveRestoreToSPPrePostIncDec(
767         MBB, std::prev(MBB.getFirstTerminator()), DL, TII, CSStackSize);
768 
769   // Move past the restores of the callee-saved registers.
770   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
771   MachineBasicBlock::iterator Begin = MBB.begin();
772   while (LastPopI != Begin) {
773     --LastPopI;
774     if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
775       ++LastPopI;
776       break;
777     } else if (CombineSPBump)
778       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize());
779   }
780 
781   // If there is a single SP update, insert it before the ret and we're done.
782   if (CombineSPBump) {
783     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
784                     NumBytes + ArgumentPopSize, TII,
785                     MachineInstr::FrameDestroy);
786     return;
787   }
788 
789   NumBytes -= CSStackSize;
790   assert(NumBytes >= 0 && "Negative stack allocation size!?");
791 
792   if (!hasFP(MF)) {
793     bool RedZone = canUseRedZone(MF);
794     // If this was a redzone leaf function, we don't need to restore the
795     // stack pointer (but we may need to pop stack args for fastcc).
796     if (RedZone && ArgumentPopSize == 0)
797       return;
798 
799     bool NoCalleeSaveRestore = CSStackSize == 0;
800     int StackRestoreBytes = RedZone ? 0 : NumBytes;
801     if (NoCalleeSaveRestore)
802       StackRestoreBytes += ArgumentPopSize;
803     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
804                     StackRestoreBytes, TII, MachineInstr::FrameDestroy);
805     // If we were able to combine the local stack pop with the argument pop,
806     // then we're done.
807     if (NoCalleeSaveRestore || ArgumentPopSize == 0)
808       return;
809     NumBytes = 0;
810   }
811 
812   // Restore the original stack pointer.
813   // FIXME: Rather than doing the math here, we should instead just use
814   // non-post-indexed loads for the restores if we aren't actually going to
815   // be able to save any instructions.
816   if (MFI.hasVarSizedObjects() || AFI->isStackRealigned())
817     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
818                     -CSStackSize + 16, TII, MachineInstr::FrameDestroy);
819   else if (NumBytes)
820     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
821                     MachineInstr::FrameDestroy);
822 
823   // This must be placed after the callee-save restore code because that code
824   // assumes the SP is at the same location as it was after the callee-save save
825   // code in the prologue.
826   if (ArgumentPopSize)
827     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
828                     ArgumentPopSize, TII, MachineInstr::FrameDestroy);
829 }
830 
831 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
832 /// debug info.  It's the same as what we use for resolving the code-gen
833 /// references for now.  FIXME: This can go wrong when references are
834 /// SP-relative and simple call frames aren't used.
835 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
836                                                  int FI,
837                                                  unsigned &FrameReg) const {
838   return resolveFrameIndexReference(MF, FI, FrameReg);
839 }
840 
841 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
842                                                      int FI, unsigned &FrameReg,
843                                                      bool PreferFP) const {
844   const MachineFrameInfo &MFI = MF.getFrameInfo();
845   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
846       MF.getSubtarget().getRegisterInfo());
847   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
848   int FPOffset = MFI.getObjectOffset(FI) + 16;
849   int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
850   bool isFixed = MFI.isFixedObjectIndex(FI);
851 
852   // Use frame pointer to reference fixed objects. Use it for locals if
853   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
854   // reliable as a base). Make sure useFPForScavengingIndex() does the
855   // right thing for the emergency spill slot.
856   bool UseFP = false;
857   if (AFI->hasStackFrame()) {
858     // Note: Keeping the following as multiple 'if' statements rather than
859     // merging to a single expression for readability.
860     //
861     // Argument access should always use the FP.
862     if (isFixed) {
863       UseFP = hasFP(MF);
864     } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) &&
865                !RegInfo->needsStackRealignment(MF)) {
866       // Use SP or FP, whichever gives us the best chance of the offset
867       // being in range for direct access. If the FPOffset is positive,
868       // that'll always be best, as the SP will be even further away.
869       // If the FPOffset is negative, we have to keep in mind that the
870       // available offset range for negative offsets is smaller than for
871       // positive ones. If we have variable sized objects, we're stuck with
872       // using the FP regardless, though, as the SP offset is unknown
873       // and we don't have a base pointer available. If an offset is
874       // available via the FP and the SP, use whichever is closest.
875       if (PreferFP || MFI.hasVarSizedObjects() || FPOffset >= 0 ||
876           (FPOffset >= -256 && Offset > -FPOffset))
877         UseFP = true;
878     }
879   }
880 
881   assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
882          "In the presence of dynamic stack pointer realignment, "
883          "non-argument objects cannot be accessed through the frame pointer");
884 
885   if (UseFP) {
886     FrameReg = RegInfo->getFrameRegister(MF);
887     return FPOffset;
888   }
889 
890   // Use the base pointer if we have one.
891   if (RegInfo->hasBasePointer(MF))
892     FrameReg = RegInfo->getBaseRegister();
893   else {
894     FrameReg = AArch64::SP;
895     // If we're using the red zone for this function, the SP won't actually
896     // be adjusted, so the offsets will be negative. They're also all
897     // within range of the signed 9-bit immediate instructions.
898     if (canUseRedZone(MF))
899       Offset -= AFI->getLocalStackSize();
900   }
901 
902   return Offset;
903 }
904 
905 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
906   // Do not set a kill flag on values that are also marked as live-in. This
907   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
908   // callee saved registers.
909   // Omitting the kill flags is conservatively correct even if the live-in
910   // is not used after all.
911   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
912   return getKillRegState(!IsLiveIn);
913 }
914 
915 static bool produceCompactUnwindFrame(MachineFunction &MF) {
916   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
917   AttributeList Attrs = MF.getFunction()->getAttributes();
918   return Subtarget.isTargetMachO() &&
919          !(Subtarget.getTargetLowering()->supportSwiftError() &&
920            Attrs.hasAttrSomewhere(Attribute::SwiftError));
921 }
922 
923 namespace {
924 
925 struct RegPairInfo {
926   unsigned Reg1 = AArch64::NoRegister;
927   unsigned Reg2 = AArch64::NoRegister;
928   int FrameIdx;
929   int Offset;
930   bool IsGPR;
931 
932   RegPairInfo() = default;
933 
934   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
935 };
936 
937 } // end anonymous namespace
938 
939 static void computeCalleeSaveRegisterPairs(
940     MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
941     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs) {
942 
943   if (CSI.empty())
944     return;
945 
946   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
947   MachineFrameInfo &MFI = MF.getFrameInfo();
948   CallingConv::ID CC = MF.getFunction()->getCallingConv();
949   unsigned Count = CSI.size();
950   (void)CC;
951   // MachO's compact unwind format relies on all registers being stored in
952   // pairs.
953   assert((!produceCompactUnwindFrame(MF) ||
954           CC == CallingConv::PreserveMost ||
955           (Count & 1) == 0) &&
956          "Odd number of callee-saved regs to spill!");
957   int Offset = AFI->getCalleeSavedStackSize();
958 
959   unsigned GPRSaveSize = AFI->getVarArgsGPRSize();
960   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
961   bool IsWin64 = Subtarget.isCallingConvWin64(MF.getFunction()->getCallingConv());
962   if (IsWin64)
963     Offset -= alignTo(GPRSaveSize, 16);
964 
965   for (unsigned i = 0; i < Count; ++i) {
966     RegPairInfo RPI;
967     RPI.Reg1 = CSI[i].getReg();
968 
969     assert(AArch64::GPR64RegClass.contains(RPI.Reg1) ||
970            AArch64::FPR64RegClass.contains(RPI.Reg1));
971     RPI.IsGPR = AArch64::GPR64RegClass.contains(RPI.Reg1);
972 
973     // Add the next reg to the pair if it is in the same register class.
974     if (i + 1 < Count) {
975       unsigned NextReg = CSI[i + 1].getReg();
976       if ((RPI.IsGPR && AArch64::GPR64RegClass.contains(NextReg)) ||
977           (!RPI.IsGPR && AArch64::FPR64RegClass.contains(NextReg)))
978         RPI.Reg2 = NextReg;
979     }
980 
981     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
982     // list to come in sorted by frame index so that we can issue the store
983     // pair instructions directly. Assert if we see anything otherwise.
984     //
985     // The order of the registers in the list is controlled by
986     // getCalleeSavedRegs(), so they will always be in-order, as well.
987     assert((!RPI.isPaired() ||
988             (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
989            "Out of order callee saved regs!");
990 
991     // MachO's compact unwind format relies on all registers being stored in
992     // adjacent register pairs.
993     assert((!produceCompactUnwindFrame(MF) ||
994             CC == CallingConv::PreserveMost ||
995             (RPI.isPaired() &&
996              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
997               RPI.Reg1 + 1 == RPI.Reg2))) &&
998            "Callee-save registers not saved as adjacent register pair!");
999 
1000     RPI.FrameIdx = CSI[i].getFrameIdx();
1001 
1002     if (Count * 8 != AFI->getCalleeSavedStackSize() && !RPI.isPaired()) {
1003       // Round up size of non-pair to pair size if we need to pad the
1004       // callee-save area to ensure 16-byte alignment.
1005       Offset -= 16;
1006       assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
1007       MFI.setObjectAlignment(RPI.FrameIdx, 16);
1008       AFI->setCalleeSaveStackHasFreeSpace(true);
1009     } else
1010       Offset -= RPI.isPaired() ? 16 : 8;
1011     assert(Offset % 8 == 0);
1012     RPI.Offset = Offset / 8;
1013     assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
1014            "Offset out of bounds for LDP/STP immediate");
1015 
1016     RegPairs.push_back(RPI);
1017     if (RPI.isPaired())
1018       ++i;
1019   }
1020 }
1021 
1022 bool AArch64FrameLowering::spillCalleeSavedRegisters(
1023     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1024     const std::vector<CalleeSavedInfo> &CSI,
1025     const TargetRegisterInfo *TRI) const {
1026   MachineFunction &MF = *MBB.getParent();
1027   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1028   DebugLoc DL;
1029   SmallVector<RegPairInfo, 8> RegPairs;
1030 
1031   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
1032   const MachineRegisterInfo &MRI = MF.getRegInfo();
1033 
1034   for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
1035        ++RPII) {
1036     RegPairInfo RPI = *RPII;
1037     unsigned Reg1 = RPI.Reg1;
1038     unsigned Reg2 = RPI.Reg2;
1039     unsigned StrOpc;
1040 
1041     // Issue sequence of spills for cs regs.  The first spill may be converted
1042     // to a pre-decrement store later by emitPrologue if the callee-save stack
1043     // area allocation can't be combined with the local stack area allocation.
1044     // For example:
1045     //    stp     x22, x21, [sp, #0]     // addImm(+0)
1046     //    stp     x20, x19, [sp, #16]    // addImm(+2)
1047     //    stp     fp, lr, [sp, #32]      // addImm(+4)
1048     // Rationale: This sequence saves uop updates compared to a sequence of
1049     // pre-increment spills like stp xi,xj,[sp,#-16]!
1050     // Note: Similar rationale and sequence for restores in epilog.
1051     if (RPI.IsGPR)
1052       StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
1053     else
1054       StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
1055     DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1);
1056           if (RPI.isPaired())
1057             dbgs() << ", " << TRI->getName(Reg2);
1058           dbgs() << ") -> fi#(" << RPI.FrameIdx;
1059           if (RPI.isPaired())
1060             dbgs() << ", " << RPI.FrameIdx+1;
1061           dbgs() << ")\n");
1062 
1063     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
1064     if (!MRI.isReserved(Reg1))
1065       MBB.addLiveIn(Reg1);
1066     if (RPI.isPaired()) {
1067       if (!MRI.isReserved(Reg2))
1068         MBB.addLiveIn(Reg2);
1069       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
1070       MIB.addMemOperand(MF.getMachineMemOperand(
1071           MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1072           MachineMemOperand::MOStore, 8, 8));
1073     }
1074     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1075         .addReg(AArch64::SP)
1076         .addImm(RPI.Offset) // [sp, #offset*8], where factor*8 is implicit
1077         .setMIFlag(MachineInstr::FrameSetup);
1078     MIB.addMemOperand(MF.getMachineMemOperand(
1079         MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1080         MachineMemOperand::MOStore, 8, 8));
1081   }
1082   return true;
1083 }
1084 
1085 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1086     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1087     const std::vector<CalleeSavedInfo> &CSI,
1088     const TargetRegisterInfo *TRI) const {
1089   MachineFunction &MF = *MBB.getParent();
1090   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1091   DebugLoc DL;
1092   SmallVector<RegPairInfo, 8> RegPairs;
1093 
1094   if (MI != MBB.end())
1095     DL = MI->getDebugLoc();
1096 
1097   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
1098 
1099   for (auto RPII = RegPairs.begin(), RPIE = RegPairs.end(); RPII != RPIE;
1100        ++RPII) {
1101     RegPairInfo RPI = *RPII;
1102     unsigned Reg1 = RPI.Reg1;
1103     unsigned Reg2 = RPI.Reg2;
1104 
1105     // Issue sequence of restores for cs regs. The last restore may be converted
1106     // to a post-increment load later by emitEpilogue if the callee-save stack
1107     // area allocation can't be combined with the local stack area allocation.
1108     // For example:
1109     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
1110     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
1111     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
1112     // Note: see comment in spillCalleeSavedRegisters()
1113     unsigned LdrOpc;
1114     if (RPI.IsGPR)
1115       LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1116     else
1117       LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
1118     DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1);
1119           if (RPI.isPaired())
1120             dbgs() << ", " << TRI->getName(Reg2);
1121           dbgs() << ") -> fi#(" << RPI.FrameIdx;
1122           if (RPI.isPaired())
1123             dbgs() << ", " << RPI.FrameIdx+1;
1124           dbgs() << ")\n");
1125 
1126     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
1127     if (RPI.isPaired()) {
1128       MIB.addReg(Reg2, getDefRegState(true));
1129       MIB.addMemOperand(MF.getMachineMemOperand(
1130           MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1131           MachineMemOperand::MOLoad, 8, 8));
1132     }
1133     MIB.addReg(Reg1, getDefRegState(true))
1134         .addReg(AArch64::SP)
1135         .addImm(RPI.Offset) // [sp, #offset*8] where the factor*8 is implicit
1136         .setMIFlag(MachineInstr::FrameDestroy);
1137     MIB.addMemOperand(MF.getMachineMemOperand(
1138         MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1139         MachineMemOperand::MOLoad, 8, 8));
1140   }
1141   return true;
1142 }
1143 
1144 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1145                                                 BitVector &SavedRegs,
1146                                                 RegScavenger *RS) const {
1147   // All calls are tail calls in GHC calling conv, and functions have no
1148   // prologue/epilogue.
1149   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
1150     return;
1151 
1152   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1153   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
1154       MF.getSubtarget().getRegisterInfo());
1155   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1156   unsigned UnspilledCSGPR = AArch64::NoRegister;
1157   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
1158 
1159   // The frame record needs to be created by saving the appropriate registers
1160   if (hasFP(MF)) {
1161     SavedRegs.set(AArch64::FP);
1162     SavedRegs.set(AArch64::LR);
1163   }
1164 
1165   unsigned BasePointerReg = AArch64::NoRegister;
1166   if (RegInfo->hasBasePointer(MF))
1167     BasePointerReg = RegInfo->getBaseRegister();
1168 
1169   unsigned ExtraCSSpill = 0;
1170   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1171   // Figure out which callee-saved registers to save/restore.
1172   for (unsigned i = 0; CSRegs[i]; ++i) {
1173     const unsigned Reg = CSRegs[i];
1174 
1175     // Add the base pointer register to SavedRegs if it is callee-save.
1176     if (Reg == BasePointerReg)
1177       SavedRegs.set(Reg);
1178 
1179     bool RegUsed = SavedRegs.test(Reg);
1180     unsigned PairedReg = CSRegs[i ^ 1];
1181     if (!RegUsed) {
1182       if (AArch64::GPR64RegClass.contains(Reg) &&
1183           !RegInfo->isReservedReg(MF, Reg)) {
1184         UnspilledCSGPR = Reg;
1185         UnspilledCSGPRPaired = PairedReg;
1186       }
1187       continue;
1188     }
1189 
1190     // MachO's compact unwind format relies on all registers being stored in
1191     // pairs.
1192     // FIXME: the usual format is actually better if unwinding isn't needed.
1193     if (produceCompactUnwindFrame(MF) && !SavedRegs.test(PairedReg)) {
1194       SavedRegs.set(PairedReg);
1195       if (AArch64::GPR64RegClass.contains(PairedReg) &&
1196           !RegInfo->isReservedReg(MF, PairedReg))
1197         ExtraCSSpill = PairedReg;
1198     }
1199   }
1200 
1201   DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
1202         for (unsigned Reg : SavedRegs.set_bits())
1203           dbgs() << ' ' << PrintReg(Reg, RegInfo);
1204         dbgs() << "\n";);
1205 
1206   // If any callee-saved registers are used, the frame cannot be eliminated.
1207   unsigned NumRegsSpilled = SavedRegs.count();
1208   bool CanEliminateFrame = NumRegsSpilled == 0;
1209 
1210   // The CSR spill slots have not been allocated yet, so estimateStackSize
1211   // won't include them.
1212   MachineFrameInfo &MFI = MF.getFrameInfo();
1213   unsigned CFSize = MFI.estimateStackSize(MF) + 8 * NumRegsSpilled;
1214   DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
1215   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
1216   bool BigStack = (CFSize > EstimatedStackSizeLimit);
1217   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
1218     AFI->setHasStackFrame(true);
1219 
1220   // Estimate if we might need to scavenge a register at some point in order
1221   // to materialize a stack offset. If so, either spill one additional
1222   // callee-saved register or reserve a special spill slot to facilitate
1223   // register scavenging. If we already spilled an extra callee-saved register
1224   // above to keep the number of spills even, we don't need to do anything else
1225   // here.
1226   if (BigStack) {
1227     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
1228       DEBUG(dbgs() << "Spilling " << PrintReg(UnspilledCSGPR, RegInfo)
1229             << " to get a scratch register.\n");
1230       SavedRegs.set(UnspilledCSGPR);
1231       // MachO's compact unwind format relies on all registers being stored in
1232       // pairs, so if we need to spill one extra for BigStack, then we need to
1233       // store the pair.
1234       if (produceCompactUnwindFrame(MF))
1235         SavedRegs.set(UnspilledCSGPRPaired);
1236       ExtraCSSpill = UnspilledCSGPRPaired;
1237       NumRegsSpilled = SavedRegs.count();
1238     }
1239 
1240     // If we didn't find an extra callee-saved register to spill, create
1241     // an emergency spill slot.
1242     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
1243       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1244       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
1245       unsigned Size = TRI->getSpillSize(RC);
1246       unsigned Align = TRI->getSpillAlignment(RC);
1247       int FI = MFI.CreateStackObject(Size, Align, false);
1248       RS->addScavengingFrameIndex(FI);
1249       DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1250                    << " as the emergency spill slot.\n");
1251     }
1252   }
1253 
1254   // Round up to register pair alignment to avoid additional SP adjustment
1255   // instructions.
1256   AFI->setCalleeSavedStackSize(alignTo(8 * NumRegsSpilled, 16));
1257 }
1258 
1259 bool AArch64FrameLowering::enableStackSlotScavenging(
1260     const MachineFunction &MF) const {
1261   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1262   return AFI->hasCalleeSaveStackFreeSpace();
1263 }
1264