1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the AArch64 implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "AArch64FrameLowering.h"
15 #include "AArch64InstrInfo.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
34 #define DEBUG_TYPE "frame-info"
36 static cl::opt<bool> EnableRedZone("aarch64-redzone",
37 cl::desc("enable use of redzone on AArch64"),
38 cl::init(false), cl::Hidden);
40 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
42 static unsigned estimateStackSize(MachineFunction &MF) {
43 const MachineFrameInfo *FFI = MF.getFrameInfo();
45 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
46 int FixedOff = -FFI->getObjectOffset(i);
47 if (FixedOff > Offset)
50 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
51 if (FFI->isDeadObjectIndex(i))
53 Offset += FFI->getObjectSize(i);
54 unsigned Align = FFI->getObjectAlignment(i);
55 // Adjust to alignment boundary
56 Offset = (Offset + Align - 1) / Align * Align;
58 // This does not include the 16 bytes used for fp and lr.
59 return (unsigned)Offset;
62 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
65 // Don't use the red zone if the function explicitly asks us not to.
66 // This is typically used for kernel code.
67 if (MF.getFunction()->getAttributes().hasAttribute(
68 AttributeSet::FunctionIndex, Attribute::NoRedZone))
71 const MachineFrameInfo *MFI = MF.getFrameInfo();
72 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
73 unsigned NumBytes = AFI->getLocalStackSize();
75 // Note: currently hasFP() is always true for hasCalls(), but that's an
76 // implementation detail of the current code, not a strict requirement,
77 // so stay safe here and check both.
78 if (MFI->hasCalls() || hasFP(MF) || NumBytes > 128)
83 /// hasFP - Return true if the specified function should have a dedicated frame
85 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
86 const MachineFrameInfo *MFI = MF.getFrameInfo();
89 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
90 assert(!RegInfo->needsStackRealignment(MF) &&
91 "No stack realignment on AArch64!");
94 return (MFI->hasCalls() || MFI->hasVarSizedObjects() ||
95 MFI->isFrameAddressTaken() || MFI->hasStackMap() ||
96 MFI->hasPatchPoint());
99 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
100 /// not required, we reserve argument space for call sites in the function
101 /// immediately on entry to the current function. This eliminates the need for
102 /// add/sub sp brackets around call sites. Returns true if the call frame is
103 /// included as part of the stack frame.
105 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
106 return !MF.getFrameInfo()->hasVarSizedObjects();
109 void AArch64FrameLowering::eliminateCallFramePseudoInstr(
110 MachineFunction &MF, MachineBasicBlock &MBB,
111 MachineBasicBlock::iterator I) const {
112 const AArch64InstrInfo *TII =
113 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
114 DebugLoc DL = I->getDebugLoc();
115 int Opc = I->getOpcode();
116 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
117 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
119 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
120 if (!TFI->hasReservedCallFrame(MF)) {
121 unsigned Align = getStackAlignment();
123 int64_t Amount = I->getOperand(0).getImm();
124 Amount = RoundUpToAlignment(Amount, Align);
128 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
129 // doesn't have to pop anything), then the first operand will be zero too so
130 // this adjustment is a no-op.
131 if (CalleePopAmount == 0) {
132 // FIXME: in-function stack adjustment for calls is limited to 24-bits
133 // because there's no guaranteed temporary register available.
135 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
136 // 1) For offset <= 12-bit, we use LSL #0
137 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
138 // LSL #0, and the other uses LSL #12.
140 // Mostly call frames will be allocated at the start of a function so
141 // this is OK, but it is a limitation that needs dealing with.
142 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
143 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
145 } else if (CalleePopAmount != 0) {
146 // If the calling convention demands that the callee pops arguments from the
147 // stack, we want to add it back if we have a reserved call frame.
148 assert(CalleePopAmount < 0xffffff && "call frame too large");
149 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
155 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
156 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
157 unsigned FramePtr) const {
158 MachineFunction &MF = *MBB.getParent();
159 MachineFrameInfo *MFI = MF.getFrameInfo();
160 MachineModuleInfo &MMI = MF.getMMI();
161 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
162 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
163 DebugLoc DL = MBB.findDebugLoc(MBBI);
165 // Add callee saved registers to move list.
166 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
170 const DataLayout *TD = MF.getSubtarget().getDataLayout();
171 bool HasFP = hasFP(MF);
173 // Calculate amount of bytes used for return address storing.
174 int stackGrowth = -TD->getPointerSize(0);
176 // Calculate offsets.
177 int64_t saveAreaOffset = (HasFP ? 2 : 1) * stackGrowth;
178 unsigned TotalSkipped = 0;
179 for (const auto &Info : CSI) {
180 unsigned Reg = Info.getReg();
181 int64_t Offset = MFI->getObjectOffset(Info.getFrameIdx()) -
182 getOffsetOfLocalArea() + saveAreaOffset;
184 // Don't output a new CFI directive if we're re-saving the frame pointer or
185 // link register. This happens when the PrologEpilogInserter has inserted an
186 // extra "STP" of the frame pointer and link register -- the "emitPrologue"
187 // method automatically generates the directives when frame pointers are
188 // used. If we generate CFI directives for the extra "STP"s, the linker will
189 // lose track of the correct values for the frame pointer and link register.
190 if (HasFP && (FramePtr == Reg || Reg == AArch64::LR)) {
191 TotalSkipped += stackGrowth;
195 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
196 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
197 nullptr, DwarfReg, Offset - TotalSkipped));
198 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
199 .addCFIIndex(CFIIndex);
203 void AArch64FrameLowering::emitPrologue(MachineFunction &MF) const {
204 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
205 MachineBasicBlock::iterator MBBI = MBB.begin();
206 const MachineFrameInfo *MFI = MF.getFrameInfo();
207 const Function *Fn = MF.getFunction();
208 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
209 MF.getSubtarget().getRegisterInfo());
210 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
211 MachineModuleInfo &MMI = MF.getMMI();
212 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
213 bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
214 bool HasFP = hasFP(MF);
215 DebugLoc DL = MBB.findDebugLoc(MBBI);
217 int NumBytes = (int)MFI->getStackSize();
218 if (!AFI->hasStackFrame()) {
219 assert(!HasFP && "unexpected function without stack frame but with FP");
221 // All of the stack allocation is for locals.
222 AFI->setLocalStackSize(NumBytes);
224 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
225 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
227 // REDZONE: If the stack size is less than 128 bytes, we don't need
228 // to actually allocate.
229 if (NumBytes && !canUseRedZone(MF)) {
230 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
231 MachineInstr::FrameSetup);
233 // Encode the stack size of the leaf function.
234 unsigned CFIIndex = MMI.addFrameInst(
235 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
236 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
237 .addCFIIndex(CFIIndex);
238 } else if (NumBytes) {
239 ++NumRedZoneFunctions;
245 // Only set up FP if we actually need to.
248 // First instruction must a) allocate the stack and b) have an immediate
249 // that is a multiple of -2.
250 assert((MBBI->getOpcode() == AArch64::STPXpre ||
251 MBBI->getOpcode() == AArch64::STPDpre) &&
252 MBBI->getOperand(3).getReg() == AArch64::SP &&
253 MBBI->getOperand(4).getImm() < 0 &&
254 (MBBI->getOperand(4).getImm() & 1) == 0);
256 // Frame pointer is fp = sp - 16. Since the STPXpre subtracts the space
257 // required for the callee saved register area we get the frame pointer
258 // by addding that offset - 16 = -getImm()*8 - 2*8 = -(getImm() + 2) * 8.
259 FPOffset = -(MBBI->getOperand(4).getImm() + 2) * 8;
260 assert(FPOffset >= 0 && "Bad Framepointer Offset");
263 // Move past the saves of the callee-saved registers.
264 while (MBBI->getOpcode() == AArch64::STPXi ||
265 MBBI->getOpcode() == AArch64::STPDi ||
266 MBBI->getOpcode() == AArch64::STPXpre ||
267 MBBI->getOpcode() == AArch64::STPDpre) {
271 assert(NumBytes >= 0 && "Negative stack allocation size!?");
273 // Issue sub fp, sp, FPOffset or
274 // mov fp,sp when FPOffset is zero.
275 // Note: All stores of callee-saved registers are marked as "FrameSetup".
276 // This code marks the instruction(s) that set the FP also.
277 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
278 MachineInstr::FrameSetup);
281 // All of the remaining stack allocations are for locals.
282 AFI->setLocalStackSize(NumBytes);
284 // Allocate space for the rest of the frame.
286 // If we're a leaf function, try using the red zone.
287 if (!canUseRedZone(MF))
288 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
289 MachineInstr::FrameSetup);
292 // If we need a base pointer, set it up here. It's whatever the value of the
293 // stack pointer is at this point. Any variable size objects will be allocated
294 // after this, so we can still use the base pointer to reference locals.
296 // FIXME: Clarify FrameSetup flags here.
297 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
300 if (RegInfo->hasBasePointer(MF))
301 TII->copyPhysReg(MBB, MBBI, DL, AArch64::X19, AArch64::SP, false);
303 if (needsFrameMoves) {
304 const DataLayout *TD = MF.getSubtarget().getDataLayout();
305 const int StackGrowth = -TD->getPointerSize(0);
306 unsigned FramePtr = RegInfo->getFrameRegister(MF);
308 // An example of the prologue:
315 // .cfi_personality 155, ___gxx_personality_v0
317 // .cfi_lsda 16, Lexception33
319 // stp xa,bx, [sp, -#offset]!
321 // stp x28, x27, [sp, #offset-32]
322 // stp fp, lr, [sp, #offset-16]
323 // add fp, sp, #offset - 16
327 // +-------------------------------------------+
328 // 10000 | ........ | ........ | ........ | ........ |
329 // 10004 | ........ | ........ | ........ | ........ |
330 // +-------------------------------------------+
331 // 10008 | ........ | ........ | ........ | ........ |
332 // 1000c | ........ | ........ | ........ | ........ |
333 // +===========================================+
334 // 10010 | X28 Register |
335 // 10014 | X28 Register |
336 // +-------------------------------------------+
337 // 10018 | X27 Register |
338 // 1001c | X27 Register |
339 // +===========================================+
340 // 10020 | Frame Pointer |
341 // 10024 | Frame Pointer |
342 // +-------------------------------------------+
343 // 10028 | Link Register |
344 // 1002c | Link Register |
345 // +===========================================+
346 // 10030 | ........ | ........ | ........ | ........ |
347 // 10034 | ........ | ........ | ........ | ........ |
348 // +-------------------------------------------+
349 // 10038 | ........ | ........ | ........ | ........ |
350 // 1003c | ........ | ........ | ........ | ........ |
351 // +-------------------------------------------+
353 // [sp] = 10030 :: >>initial value<<
354 // sp = 10020 :: stp fp, lr, [sp, #-16]!
355 // fp = sp == 10020 :: mov fp, sp
356 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
357 // sp == 10010 :: >>final value<<
359 // The frame pointer (w29) points to address 10020. If we use an offset of
360 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
361 // for w27, and -32 for w28:
364 // .cfi_def_cfa w29, 16
366 // .cfi_offset w30, -8
368 // .cfi_offset w29, -16
370 // .cfi_offset w27, -24
372 // .cfi_offset w28, -32
375 // Define the current CFA rule to use the provided FP.
376 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
377 unsigned CFIIndex = MMI.addFrameInst(
378 MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
379 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
380 .addCFIIndex(CFIIndex);
382 // Record the location of the stored LR
383 unsigned LR = RegInfo->getDwarfRegNum(AArch64::LR, true);
384 CFIIndex = MMI.addFrameInst(
385 MCCFIInstruction::createOffset(nullptr, LR, StackGrowth));
386 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
387 .addCFIIndex(CFIIndex);
389 // Record the location of the stored FP
390 CFIIndex = MMI.addFrameInst(
391 MCCFIInstruction::createOffset(nullptr, Reg, 2 * StackGrowth));
392 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
393 .addCFIIndex(CFIIndex);
395 // Encode the stack size of the leaf function.
396 unsigned CFIIndex = MMI.addFrameInst(
397 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI->getStackSize()));
398 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
399 .addCFIIndex(CFIIndex);
402 // Now emit the moves for whatever callee saved regs we have.
403 emitCalleeSavedFrameMoves(MBB, MBBI, FramePtr);
407 static bool isCalleeSavedRegister(unsigned Reg, const MCPhysReg *CSRegs) {
408 for (unsigned i = 0; CSRegs[i]; ++i)
409 if (Reg == CSRegs[i])
414 static bool isCSRestore(MachineInstr *MI, const MCPhysReg *CSRegs) {
416 if (MI->getOpcode() == AArch64::LDPXpost ||
417 MI->getOpcode() == AArch64::LDPDpost)
420 if (MI->getOpcode() == AArch64::LDPXpost ||
421 MI->getOpcode() == AArch64::LDPDpost ||
422 MI->getOpcode() == AArch64::LDPXi || MI->getOpcode() == AArch64::LDPDi) {
423 if (!isCalleeSavedRegister(MI->getOperand(RtIdx).getReg(), CSRegs) ||
424 !isCalleeSavedRegister(MI->getOperand(RtIdx + 1).getReg(), CSRegs) ||
425 MI->getOperand(RtIdx + 2).getReg() != AArch64::SP)
433 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
434 MachineBasicBlock &MBB) const {
435 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
436 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
437 MachineFrameInfo *MFI = MF.getFrameInfo();
438 const AArch64InstrInfo *TII =
439 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
440 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
441 MF.getSubtarget().getRegisterInfo());
442 DebugLoc DL = MBBI->getDebugLoc();
443 unsigned RetOpcode = MBBI->getOpcode();
445 int NumBytes = MFI->getStackSize();
446 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
448 // Initial and residual are named for consitency with the prologue. Note that
449 // in the epilogue, the residual adjustment is executed first.
450 uint64_t ArgumentPopSize = 0;
451 if (RetOpcode == AArch64::TCRETURNdi || RetOpcode == AArch64::TCRETURNri) {
452 MachineOperand &StackAdjust = MBBI->getOperand(1);
454 // For a tail-call in a callee-pops-arguments environment, some or all of
455 // the stack may actually be in use for the call's arguments, this is
456 // calculated during LowerCall and consumed here...
457 ArgumentPopSize = StackAdjust.getImm();
459 // ... otherwise the amount to pop is *all* of the argument space,
460 // conveniently stored in the MachineFunctionInfo by
461 // LowerFormalArguments. This will, of course, be zero for the C calling
463 ArgumentPopSize = AFI->getArgumentStackToRestore();
466 // The stack frame should be like below,
468 // ---------------------- ---
470 // | BytesInStackArgArea| CalleeArgStackSize
471 // | (NumReusableBytes) | (of tail call)
474 // ---------------------| --- |
476 // | CalleeSavedReg | | |
477 // | (NumRestores * 16) | | |
479 // ---------------------| | NumBytes
480 // | | StackSize (StackAdjustUp)
481 // | LocalStackSize | | |
482 // | (covering callee | | |
485 // ---------------------- --- ---
487 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
488 // = StackSize + ArgumentPopSize
490 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
491 // it as the 2nd argument of AArch64ISD::TC_RETURN.
492 NumBytes += ArgumentPopSize;
494 unsigned NumRestores = 0;
495 // Move past the restores of the callee-saved registers.
496 MachineBasicBlock::iterator LastPopI = MBBI;
497 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
498 if (LastPopI != MBB.begin()) {
502 } while (LastPopI != MBB.begin() && isCSRestore(LastPopI, CSRegs));
503 if (!isCSRestore(LastPopI, CSRegs)) {
508 NumBytes -= NumRestores * 16;
509 assert(NumBytes >= 0 && "Negative stack allocation size!?");
512 // If this was a redzone leaf function, we don't need to restore the
514 if (!canUseRedZone(MF))
515 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes,
520 // Restore the original stack pointer.
521 // FIXME: Rather than doing the math here, we should instead just use
522 // non-post-indexed loads for the restores if we aren't actually going to
523 // be able to save any instructions.
524 if (NumBytes || MFI->hasVarSizedObjects())
525 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
526 -(NumRestores - 1) * 16, TII, MachineInstr::NoFlags);
529 /// getFrameIndexOffset - Returns the displacement from the frame register to
530 /// the stack frame of the specified index.
531 int AArch64FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
534 return getFrameIndexReference(MF, FI, FrameReg);
537 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
538 /// debug info. It's the same as what we use for resolving the code-gen
539 /// references for now. FIXME: This can go wrong when references are
540 /// SP-relative and simple call frames aren't used.
541 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
543 unsigned &FrameReg) const {
544 return resolveFrameIndexReference(MF, FI, FrameReg);
547 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
548 int FI, unsigned &FrameReg,
549 bool PreferFP) const {
550 const MachineFrameInfo *MFI = MF.getFrameInfo();
551 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
552 MF.getSubtarget().getRegisterInfo());
553 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
554 int FPOffset = MFI->getObjectOffset(FI) + 16;
555 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
556 bool isFixed = MFI->isFixedObjectIndex(FI);
558 // Use frame pointer to reference fixed objects. Use it for locals if
559 // there are VLAs (and thus the SP isn't reliable as a base).
560 // Make sure useFPForScavengingIndex() does the right thing for the emergency
563 if (AFI->hasStackFrame()) {
564 // Note: Keeping the following as multiple 'if' statements rather than
565 // merging to a single expression for readability.
567 // Argument access should always use the FP.
570 } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF)) {
571 // Use SP or FP, whichever gives us the best chance of the offset
572 // being in range for direct access. If the FPOffset is positive,
573 // that'll always be best, as the SP will be even further away.
574 // If the FPOffset is negative, we have to keep in mind that the
575 // available offset range for negative offsets is smaller than for
576 // positive ones. If we have variable sized objects, we're stuck with
577 // using the FP regardless, though, as the SP offset is unknown
578 // and we don't have a base pointer available. If an offset is
579 // available via the FP and the SP, use whichever is closest.
580 if (PreferFP || MFI->hasVarSizedObjects() || FPOffset >= 0 ||
581 (FPOffset >= -256 && Offset > -FPOffset))
587 FrameReg = RegInfo->getFrameRegister(MF);
591 // Use the base pointer if we have one.
592 if (RegInfo->hasBasePointer(MF))
593 FrameReg = RegInfo->getBaseRegister();
595 FrameReg = AArch64::SP;
596 // If we're using the red zone for this function, the SP won't actually
597 // be adjusted, so the offsets will be negative. They're also all
598 // within range of the signed 9-bit immediate instructions.
599 if (canUseRedZone(MF))
600 Offset -= AFI->getLocalStackSize();
606 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
607 if (Reg != AArch64::LR)
608 return getKillRegState(true);
610 // LR maybe referred to later by an @llvm.returnaddress intrinsic.
611 bool LRLiveIn = MF.getRegInfo().isLiveIn(AArch64::LR);
612 bool LRKill = !(LRLiveIn && MF.getFrameInfo()->isReturnAddressTaken());
613 return getKillRegState(LRKill);
616 bool AArch64FrameLowering::spillCalleeSavedRegisters(
617 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
618 const std::vector<CalleeSavedInfo> &CSI,
619 const TargetRegisterInfo *TRI) const {
620 MachineFunction &MF = *MBB.getParent();
621 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
622 unsigned Count = CSI.size();
624 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
627 DL = MI->getDebugLoc();
629 for (unsigned i = 0; i < Count; i += 2) {
630 unsigned idx = Count - i - 2;
631 unsigned Reg1 = CSI[idx].getReg();
632 unsigned Reg2 = CSI[idx + 1].getReg();
633 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
634 // list to come in sorted by frame index so that we can issue the store
635 // pair instructions directly. Assert if we see anything otherwise.
637 // The order of the registers in the list is controlled by
638 // getCalleeSavedRegs(), so they will always be in-order, as well.
639 assert(CSI[idx].getFrameIdx() + 1 == CSI[idx + 1].getFrameIdx() &&
640 "Out of order callee saved regs!");
642 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
643 assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
644 // Issue sequence of non-sp increment and pi sp spills for cs regs. The
645 // first spill is a pre-increment that allocates the stack.
647 // stp x22, x21, [sp, #-48]! // addImm(-6)
648 // stp x20, x19, [sp, #16] // addImm(+2)
649 // stp fp, lr, [sp, #32] // addImm(+4)
650 // Rationale: This sequence saves uop updates compared to a sequence of
651 // pre-increment spills like stp xi,xj,[sp,#-16]!
652 // Note: Similar rational and sequence for restores in epilog.
653 if (AArch64::GPR64RegClass.contains(Reg1)) {
654 assert(AArch64::GPR64RegClass.contains(Reg2) &&
655 "Expected GPR64 callee-saved register pair!");
656 // For first spill use pre-increment store.
658 StrOpc = AArch64::STPXpre;
660 StrOpc = AArch64::STPXi;
661 } else if (AArch64::FPR64RegClass.contains(Reg1)) {
662 assert(AArch64::FPR64RegClass.contains(Reg2) &&
663 "Expected FPR64 callee-saved register pair!");
664 // For first spill use pre-increment store.
666 StrOpc = AArch64::STPDpre;
668 StrOpc = AArch64::STPDi;
670 llvm_unreachable("Unexpected callee saved register!");
671 DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1) << ", "
672 << TRI->getName(Reg2) << ") -> fi#(" << CSI[idx].getFrameIdx()
673 << ", " << CSI[idx + 1].getFrameIdx() << ")\n");
674 // Compute offset: i = 0 => offset = -Count;
675 // i = 2 => offset = -(Count - 2) + Count = 2 = i; etc.
676 const int Offset = (i == 0) ? -Count : i;
677 assert((Offset >= -64 && Offset <= 63) &&
678 "Offset out of bounds for STP immediate");
679 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
680 if (StrOpc == AArch64::STPDpre || StrOpc == AArch64::STPXpre)
681 MIB.addReg(AArch64::SP, RegState::Define);
683 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2))
684 .addReg(Reg1, getPrologueDeath(MF, Reg1))
686 .addImm(Offset) // [sp, #offset * 8], where factor * 8 is implicit
687 .setMIFlag(MachineInstr::FrameSetup);
692 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
693 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
694 const std::vector<CalleeSavedInfo> &CSI,
695 const TargetRegisterInfo *TRI) const {
696 MachineFunction &MF = *MBB.getParent();
697 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
698 unsigned Count = CSI.size();
700 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
703 DL = MI->getDebugLoc();
705 for (unsigned i = 0; i < Count; i += 2) {
706 unsigned Reg1 = CSI[i].getReg();
707 unsigned Reg2 = CSI[i + 1].getReg();
708 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
709 // list to come in sorted by frame index so that we can issue the store
710 // pair instructions directly. Assert if we see anything otherwise.
711 assert(CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx() &&
712 "Out of order callee saved regs!");
713 // Issue sequence of non-sp increment and sp-pi restores for cs regs. Only
714 // the last load is sp-pi post-increment and de-allocates the stack:
716 // ldp fp, lr, [sp, #32] // addImm(+4)
717 // ldp x20, x19, [sp, #16] // addImm(+2)
718 // ldp x22, x21, [sp], #48 // addImm(+6)
719 // Note: see comment in spillCalleeSavedRegisters()
722 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
723 assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
724 if (AArch64::GPR64RegClass.contains(Reg1)) {
725 assert(AArch64::GPR64RegClass.contains(Reg2) &&
726 "Expected GPR64 callee-saved register pair!");
728 LdrOpc = AArch64::LDPXpost;
730 LdrOpc = AArch64::LDPXi;
731 } else if (AArch64::FPR64RegClass.contains(Reg1)) {
732 assert(AArch64::FPR64RegClass.contains(Reg2) &&
733 "Expected FPR64 callee-saved register pair!");
735 LdrOpc = AArch64::LDPDpost;
737 LdrOpc = AArch64::LDPDi;
739 llvm_unreachable("Unexpected callee saved register!");
740 DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1) << ", "
741 << TRI->getName(Reg2) << ") -> fi#(" << CSI[i].getFrameIdx()
742 << ", " << CSI[i + 1].getFrameIdx() << ")\n");
744 // Compute offset: i = 0 => offset = Count - 2; i = 2 => offset = Count - 4;
746 const int Offset = (i == Count - 2) ? Count : Count - i - 2;
747 assert((Offset >= -64 && Offset <= 63) &&
748 "Offset out of bounds for LDP immediate");
749 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
750 if (LdrOpc == AArch64::LDPXpost || LdrOpc == AArch64::LDPDpost)
751 MIB.addReg(AArch64::SP, RegState::Define);
753 MIB.addReg(Reg2, getDefRegState(true))
754 .addReg(Reg1, getDefRegState(true))
756 .addImm(Offset); // [sp], #offset * 8 or [sp, #offset * 8]
757 // where the factor * 8 is implicit
762 void AArch64FrameLowering::processFunctionBeforeCalleeSavedScan(
763 MachineFunction &MF, RegScavenger *RS) const {
764 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
765 MF.getSubtarget().getRegisterInfo());
766 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
767 MachineRegisterInfo *MRI = &MF.getRegInfo();
768 SmallVector<unsigned, 4> UnspilledCSGPRs;
769 SmallVector<unsigned, 4> UnspilledCSFPRs;
771 // The frame record needs to be created by saving the appropriate registers
773 MRI->setPhysRegUsed(AArch64::FP);
774 MRI->setPhysRegUsed(AArch64::LR);
777 // Spill the BasePtr if it's used. Do this first thing so that the
778 // getCalleeSavedRegs() below will get the right answer.
779 if (RegInfo->hasBasePointer(MF))
780 MRI->setPhysRegUsed(RegInfo->getBaseRegister());
782 // If any callee-saved registers are used, the frame cannot be eliminated.
783 unsigned NumGPRSpilled = 0;
784 unsigned NumFPRSpilled = 0;
785 bool ExtraCSSpill = false;
786 bool CanEliminateFrame = true;
787 DEBUG(dbgs() << "*** processFunctionBeforeCalleeSavedScan\nUsed CSRs:");
788 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
790 // Check pairs of consecutive callee-saved registers.
791 for (unsigned i = 0; CSRegs[i]; i += 2) {
792 assert(CSRegs[i + 1] && "Odd number of callee-saved registers!");
794 const unsigned OddReg = CSRegs[i];
795 const unsigned EvenReg = CSRegs[i + 1];
796 assert((AArch64::GPR64RegClass.contains(OddReg) &&
797 AArch64::GPR64RegClass.contains(EvenReg)) ^
798 (AArch64::FPR64RegClass.contains(OddReg) &&
799 AArch64::FPR64RegClass.contains(EvenReg)) &&
800 "Register class mismatch!");
802 const bool OddRegUsed = MRI->isPhysRegUsed(OddReg);
803 const bool EvenRegUsed = MRI->isPhysRegUsed(EvenReg);
805 // Early exit if none of the registers in the register pair is actually
807 if (!OddRegUsed && !EvenRegUsed) {
808 if (AArch64::GPR64RegClass.contains(OddReg)) {
809 UnspilledCSGPRs.push_back(OddReg);
810 UnspilledCSGPRs.push_back(EvenReg);
812 UnspilledCSFPRs.push_back(OddReg);
813 UnspilledCSFPRs.push_back(EvenReg);
818 unsigned Reg = AArch64::NoRegister;
819 // If only one of the registers of the register pair is used, make sure to
820 // mark the other one as used as well.
821 if (OddRegUsed ^ EvenRegUsed) {
822 // Find out which register is the additional spill.
823 Reg = OddRegUsed ? EvenReg : OddReg;
824 MRI->setPhysRegUsed(Reg);
827 DEBUG(dbgs() << ' ' << PrintReg(OddReg, RegInfo));
828 DEBUG(dbgs() << ' ' << PrintReg(EvenReg, RegInfo));
830 assert(((OddReg == AArch64::LR && EvenReg == AArch64::FP) ||
831 (RegInfo->getEncodingValue(OddReg) + 1 ==
832 RegInfo->getEncodingValue(EvenReg))) &&
833 "Register pair of non-adjacent registers!");
834 if (AArch64::GPR64RegClass.contains(OddReg)) {
836 // If it's not a reserved register, we can use it in lieu of an
837 // emergency spill slot for the register scavenger.
838 // FIXME: It would be better to instead keep looking and choose another
839 // unspilled register that isn't reserved, if there is one.
840 if (Reg != AArch64::NoRegister && !RegInfo->isReservedReg(MF, Reg))
845 CanEliminateFrame = false;
848 // FIXME: Set BigStack if any stack slot references may be out of range.
849 // For now, just conservatively guestimate based on unscaled indexing
850 // range. We'll end up allocating an unnecessary spill slot a lot, but
851 // realistically that's not a big deal at this stage of the game.
852 // The CSR spill slots have not been allocated yet, so estimateStackSize
853 // won't include them.
854 MachineFrameInfo *MFI = MF.getFrameInfo();
855 unsigned CFSize = estimateStackSize(MF) + 8 * (NumGPRSpilled + NumFPRSpilled);
856 DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
857 bool BigStack = (CFSize >= 256);
858 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
859 AFI->setHasStackFrame(true);
861 // Estimate if we might need to scavenge a register at some point in order
862 // to materialize a stack offset. If so, either spill one additional
863 // callee-saved register or reserve a special spill slot to facilitate
864 // register scavenging. If we already spilled an extra callee-saved register
865 // above to keep the number of spills even, we don't need to do anything else
867 if (BigStack && !ExtraCSSpill) {
869 // If we're adding a register to spill here, we have to add two of them
870 // to keep the number of regs to spill even.
871 assert(((UnspilledCSGPRs.size() & 1) == 0) && "Odd number of registers!");
873 while (!UnspilledCSGPRs.empty() && Count < 2) {
874 unsigned Reg = UnspilledCSGPRs.back();
875 UnspilledCSGPRs.pop_back();
876 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, RegInfo)
877 << " to get a scratch register.\n");
878 MRI->setPhysRegUsed(Reg);
883 // If we didn't find an extra callee-saved register to spill, create
884 // an emergency spill slot.
886 const TargetRegisterClass *RC = &AArch64::GPR64RegClass;
887 int FI = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false);
888 RS->addScavengingFrameIndex(FI);
889 DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
890 << " as the emergency spill slot.\n");