1 //===- ARM64FrameLowering.cpp - ARM64 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 ARM64 implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "ARM64FrameLowering.h"
15 #include "ARM64InstrInfo.h"
16 #include "ARM64MachineFunctionInfo.h"
17 #include "ARM64Subtarget.h"
18 #include "ARM64TargetMachine.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/RegisterScavenging.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/raw_ostream.h"
34 #define DEBUG_TYPE "frame-info"
36 static cl::opt<bool> EnableRedZone("arm64-redzone",
37 cl::desc("enable use of redzone on ARM64"),
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 ARM64FrameLowering::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 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
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 ARM64FrameLowering::hasFP(const MachineFunction &MF) const {
86 const MachineFrameInfo *MFI = MF.getFrameInfo();
89 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
90 assert(!RegInfo->needsStackRealignment(MF) &&
91 "No stack realignment on ARM64!");
94 return (MFI->hasCalls() || MFI->hasVarSizedObjects() ||
95 MFI->isFrameAddressTaken());
98 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
99 /// not required, we reserve argument space for call sites in the function
100 /// immediately on entry to the current function. This eliminates the need for
101 /// add/sub sp brackets around call sites. Returns true if the call frame is
102 /// included as part of the stack frame.
103 bool ARM64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
104 return !MF.getFrameInfo()->hasVarSizedObjects();
107 void ARM64FrameLowering::eliminateCallFramePseudoInstr(
108 MachineFunction &MF, MachineBasicBlock &MBB,
109 MachineBasicBlock::iterator I) const {
110 const ARM64InstrInfo *TII =
111 static_cast<const ARM64InstrInfo *>(MF.getTarget().getInstrInfo());
112 DebugLoc DL = I->getDebugLoc();
113 int Opc = I->getOpcode();
114 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
115 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
117 const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
118 if (!TFI->hasReservedCallFrame(MF)) {
119 unsigned Align = getStackAlignment();
121 int64_t Amount = I->getOperand(0).getImm();
122 Amount = RoundUpToAlignment(Amount, Align);
126 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
127 // doesn't have to pop anything), then the first operand will be zero too so
128 // this adjustment is a no-op.
129 if (CalleePopAmount == 0) {
130 // FIXME: in-function stack adjustment for calls is limited to 24-bits
131 // because there's no guaranteed temporary register available.
133 // ADD/SUB (immediate) has only LSL #0 and LSL #12 avaiable.
134 // 1) For offset <= 12-bit, we use LSL #0
135 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
136 // LSL #0, and the other uses LSL #12.
138 // Mostly call frames will be allocated at the start of a function so
139 // this is OK, but it is a limitation that needs dealing with.
140 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
141 emitFrameOffset(MBB, I, DL, ARM64::SP, ARM64::SP, Amount, TII);
143 } else if (CalleePopAmount != 0) {
144 // If the calling convention demands that the callee pops arguments from the
145 // stack, we want to add it back if we have a reserved call frame.
146 assert(CalleePopAmount < 0xffffff && "call frame too large");
147 emitFrameOffset(MBB, I, DL, ARM64::SP, ARM64::SP, -CalleePopAmount, TII);
153 ARM64FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
154 MachineBasicBlock::iterator MBBI,
155 unsigned FramePtr) const {
156 MachineFunction &MF = *MBB.getParent();
157 MachineFrameInfo *MFI = MF.getFrameInfo();
158 MachineModuleInfo &MMI = MF.getMMI();
159 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
160 const ARM64InstrInfo *TII = TM.getInstrInfo();
161 DebugLoc DL = MBB.findDebugLoc(MBBI);
163 // Add callee saved registers to move list.
164 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
168 const DataLayout *TD = MF.getTarget().getDataLayout();
169 bool HasFP = hasFP(MF);
171 // Calculate amount of bytes used for return address storing.
172 int stackGrowth = -TD->getPointerSize(0);
174 // Calculate offsets.
175 int64_t saveAreaOffset = (HasFP ? 2 : 1) * stackGrowth;
176 unsigned TotalSkipped = 0;
177 for (const auto &Info : CSI) {
178 unsigned Reg = Info.getReg();
179 int64_t Offset = MFI->getObjectOffset(Info.getFrameIdx()) -
180 getOffsetOfLocalArea() + saveAreaOffset;
182 // Don't output a new CFI directive if we're re-saving the frame pointer or
183 // link register. This happens when the PrologEpilogInserter has inserted an
184 // extra "STP" of the frame pointer and link register -- the "emitPrologue"
185 // method automatically generates the directives when frame pointers are
186 // used. If we generate CFI directives for the extra "STP"s, the linker will
187 // lose track of the correct values for the frame pointer and link register.
188 if (HasFP && (FramePtr == Reg || Reg == ARM64::LR)) {
189 TotalSkipped += stackGrowth;
193 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
194 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
195 nullptr, DwarfReg, Offset - TotalSkipped));
196 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
197 .addCFIIndex(CFIIndex);
201 void ARM64FrameLowering::emitPrologue(MachineFunction &MF) const {
202 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
203 MachineBasicBlock::iterator MBBI = MBB.begin();
204 const MachineFrameInfo *MFI = MF.getFrameInfo();
205 const Function *Fn = MF.getFunction();
206 const ARM64RegisterInfo *RegInfo = TM.getRegisterInfo();
207 const ARM64InstrInfo *TII = TM.getInstrInfo();
208 MachineModuleInfo &MMI = MF.getMMI();
209 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
210 bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
211 bool HasFP = hasFP(MF);
212 DebugLoc DL = MBB.findDebugLoc(MBBI);
214 int NumBytes = (int)MFI->getStackSize();
215 if (!AFI->hasStackFrame()) {
216 assert(!HasFP && "unexpected function without stack frame but with FP");
218 // All of the stack allocation is for locals.
219 AFI->setLocalStackSize(NumBytes);
221 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
222 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
224 // REDZONE: If the stack size is less than 128 bytes, we don't need
225 // to actually allocate.
226 if (NumBytes && !canUseRedZone(MF)) {
227 emitFrameOffset(MBB, MBBI, DL, ARM64::SP, ARM64::SP, -NumBytes, TII,
228 MachineInstr::FrameSetup);
230 // Encode the stack size of the leaf function.
231 unsigned CFIIndex = MMI.addFrameInst(
232 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
233 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
234 .addCFIIndex(CFIIndex);
235 } else if (NumBytes) {
236 ++NumRedZoneFunctions;
242 // Only set up FP if we actually need to.
245 // First instruction must a) allocate the stack and b) have an immediate
246 // that is a multiple of -2.
247 assert((MBBI->getOpcode() == ARM64::STPXpre ||
248 MBBI->getOpcode() == ARM64::STPDpre) &&
249 MBBI->getOperand(3).getReg() == ARM64::SP &&
250 MBBI->getOperand(4).getImm() < 0 &&
251 (MBBI->getOperand(4).getImm() & 1) == 0);
253 // Frame pointer is fp = sp - 16. Since the STPXpre subtracts the space
254 // required for the callee saved register area we get the frame pointer
255 // by addding that offset - 16 = -getImm()*8 - 2*8 = -(getImm() + 2) * 8.
256 FPOffset = -(MBBI->getOperand(4).getImm() + 2) * 8;
257 assert(FPOffset >= 0 && "Bad Framepointer Offset");
260 // Move past the saves of the callee-saved registers.
261 while (MBBI->getOpcode() == ARM64::STPXi ||
262 MBBI->getOpcode() == ARM64::STPDi ||
263 MBBI->getOpcode() == ARM64::STPXpre ||
264 MBBI->getOpcode() == ARM64::STPDpre) {
268 assert(NumBytes >= 0 && "Negative stack allocation size!?");
270 // Issue sub fp, sp, FPOffset or
271 // mov fp,sp when FPOffset is zero.
272 // Note: All stores of callee-saved registers are marked as "FrameSetup".
273 // This code marks the instruction(s) that set the FP also.
274 emitFrameOffset(MBB, MBBI, DL, ARM64::FP, ARM64::SP, FPOffset, TII,
275 MachineInstr::FrameSetup);
278 // All of the remaining stack allocations are for locals.
279 AFI->setLocalStackSize(NumBytes);
281 // Allocate space for the rest of the frame.
283 // If we're a leaf function, try using the red zone.
284 if (!canUseRedZone(MF))
285 emitFrameOffset(MBB, MBBI, DL, ARM64::SP, ARM64::SP, -NumBytes, TII,
286 MachineInstr::FrameSetup);
289 // If we need a base pointer, set it up here. It's whatever the value of the
290 // stack pointer is at this point. Any variable size objects will be allocated
291 // after this, so we can still use the base pointer to reference locals.
293 // FIXME: Clarify FrameSetup flags here.
294 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
297 if (RegInfo->hasBasePointer(MF))
298 TII->copyPhysReg(MBB, MBBI, DL, ARM64::X19, ARM64::SP, false);
300 if (needsFrameMoves) {
301 const DataLayout *TD = MF.getTarget().getDataLayout();
302 const int StackGrowth = -TD->getPointerSize(0);
303 unsigned FramePtr = RegInfo->getFrameRegister(MF);
305 // An example of the prologue:
312 // .cfi_personality 155, ___gxx_personality_v0
314 // .cfi_lsda 16, Lexception33
316 // stp xa,bx, [sp, -#offset]!
318 // stp x28, x27, [sp, #offset-32]
319 // stp fp, lr, [sp, #offset-16]
320 // add fp, sp, #offset - 16
324 // +-------------------------------------------+
325 // 10000 | ........ | ........ | ........ | ........ |
326 // 10004 | ........ | ........ | ........ | ........ |
327 // +-------------------------------------------+
328 // 10008 | ........ | ........ | ........ | ........ |
329 // 1000c | ........ | ........ | ........ | ........ |
330 // +===========================================+
331 // 10010 | X28 Register |
332 // 10014 | X28 Register |
333 // +-------------------------------------------+
334 // 10018 | X27 Register |
335 // 1001c | X27 Register |
336 // +===========================================+
337 // 10020 | Frame Pointer |
338 // 10024 | Frame Pointer |
339 // +-------------------------------------------+
340 // 10028 | Link Register |
341 // 1002c | Link Register |
342 // +===========================================+
343 // 10030 | ........ | ........ | ........ | ........ |
344 // 10034 | ........ | ........ | ........ | ........ |
345 // +-------------------------------------------+
346 // 10038 | ........ | ........ | ........ | ........ |
347 // 1003c | ........ | ........ | ........ | ........ |
348 // +-------------------------------------------+
350 // [sp] = 10030 :: >>initial value<<
351 // sp = 10020 :: stp fp, lr, [sp, #-16]!
352 // fp = sp == 10020 :: mov fp, sp
353 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
354 // sp == 10010 :: >>final value<<
356 // The frame pointer (w29) points to address 10020. If we use an offset of
357 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
358 // for w27, and -32 for w28:
361 // .cfi_def_cfa w29, 16
363 // .cfi_offset w30, -8
365 // .cfi_offset w29, -16
367 // .cfi_offset w27, -24
369 // .cfi_offset w28, -32
372 // Define the current CFA rule to use the provided FP.
373 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
374 unsigned CFIIndex = MMI.addFrameInst(
375 MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
376 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
377 .addCFIIndex(CFIIndex);
379 // Record the location of the stored LR
380 unsigned LR = RegInfo->getDwarfRegNum(ARM64::LR, true);
381 CFIIndex = MMI.addFrameInst(
382 MCCFIInstruction::createOffset(nullptr, LR, StackGrowth));
383 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
384 .addCFIIndex(CFIIndex);
386 // Record the location of the stored FP
387 CFIIndex = MMI.addFrameInst(
388 MCCFIInstruction::createOffset(nullptr, Reg, 2 * StackGrowth));
389 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
390 .addCFIIndex(CFIIndex);
392 // Encode the stack size of the leaf function.
393 unsigned CFIIndex = MMI.addFrameInst(
394 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI->getStackSize()));
395 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
396 .addCFIIndex(CFIIndex);
399 // Now emit the moves for whatever callee saved regs we have.
400 emitCalleeSavedFrameMoves(MBB, MBBI, FramePtr);
404 static bool isCalleeSavedRegister(unsigned Reg, const MCPhysReg *CSRegs) {
405 for (unsigned i = 0; CSRegs[i]; ++i)
406 if (Reg == CSRegs[i])
411 static bool isCSRestore(MachineInstr *MI, const MCPhysReg *CSRegs) {
413 if (MI->getOpcode() == ARM64::LDPXpost || MI->getOpcode() == ARM64::LDPDpost)
416 if (MI->getOpcode() == ARM64::LDPXpost ||
417 MI->getOpcode() == ARM64::LDPDpost || MI->getOpcode() == ARM64::LDPXi ||
418 MI->getOpcode() == ARM64::LDPDi) {
419 if (!isCalleeSavedRegister(MI->getOperand(RtIdx).getReg(), CSRegs) ||
420 !isCalleeSavedRegister(MI->getOperand(RtIdx + 1).getReg(), CSRegs) ||
421 MI->getOperand(RtIdx + 2).getReg() != ARM64::SP)
429 void ARM64FrameLowering::emitEpilogue(MachineFunction &MF,
430 MachineBasicBlock &MBB) const {
431 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
432 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
433 MachineFrameInfo *MFI = MF.getFrameInfo();
434 const ARM64InstrInfo *TII =
435 static_cast<const ARM64InstrInfo *>(MF.getTarget().getInstrInfo());
436 const ARM64RegisterInfo *RegInfo =
437 static_cast<const ARM64RegisterInfo *>(MF.getTarget().getRegisterInfo());
438 DebugLoc DL = MBBI->getDebugLoc();
439 unsigned RetOpcode = MBBI->getOpcode();
441 int NumBytes = MFI->getStackSize();
442 const ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
444 // Initial and residual are named for consitency with the prologue. Note that
445 // in the epilogue, the residual adjustment is executed first.
446 uint64_t ArgumentPopSize = 0;
447 if (RetOpcode == ARM64::TCRETURNdi || RetOpcode == ARM64::TCRETURNri) {
448 MachineOperand &StackAdjust = MBBI->getOperand(1);
450 // For a tail-call in a callee-pops-arguments environment, some or all of
451 // the stack may actually be in use for the call's arguments, this is
452 // calculated during LowerCall and consumed here...
453 ArgumentPopSize = StackAdjust.getImm();
455 // ... otherwise the amount to pop is *all* of the argument space,
456 // conveniently stored in the MachineFunctionInfo by
457 // LowerFormalArguments. This will, of course, be zero for the C calling
459 ArgumentPopSize = AFI->getArgumentStackToRestore();
462 // The stack frame should be like below,
464 // ---------------------- ---
466 // | BytesInStackArgArea| CalleeArgStackSize
467 // | (NumReusableBytes) | (of tail call)
470 // ---------------------| --- |
472 // | CalleeSavedReg | | |
473 // | (NumRestores * 16) | | |
475 // ---------------------| | NumBytes
476 // | | StackSize (StackAdjustUp)
477 // | LocalStackSize | | |
478 // | (covering callee | | |
481 // ---------------------- --- ---
483 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
484 // = StackSize + ArgumentPopSize
486 // ARM64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
487 // it as the 2nd argument of ARM64ISD::TC_RETURN.
488 NumBytes += ArgumentPopSize;
490 unsigned NumRestores = 0;
491 // Move past the restores of the callee-saved registers.
492 MachineBasicBlock::iterator LastPopI = MBBI;
493 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
494 if (LastPopI != MBB.begin()) {
498 } while (LastPopI != MBB.begin() && isCSRestore(LastPopI, CSRegs));
499 if (!isCSRestore(LastPopI, CSRegs)) {
504 NumBytes -= NumRestores * 16;
505 assert(NumBytes >= 0 && "Negative stack allocation size!?");
508 // If this was a redzone leaf function, we don't need to restore the
510 if (!canUseRedZone(MF))
511 emitFrameOffset(MBB, LastPopI, DL, ARM64::SP, ARM64::SP, NumBytes, TII);
515 // Restore the original stack pointer.
516 // FIXME: Rather than doing the math here, we should instead just use
517 // non-post-indexed loads for the restores if we aren't actually going to
518 // be able to save any instructions.
519 if (NumBytes || MFI->hasVarSizedObjects())
520 emitFrameOffset(MBB, LastPopI, DL, ARM64::SP, ARM64::FP,
521 -(NumRestores - 1) * 16, TII, MachineInstr::NoFlags);
524 /// getFrameIndexOffset - Returns the displacement from the frame register to
525 /// the stack frame of the specified index.
526 int ARM64FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
529 return getFrameIndexReference(MF, FI, FrameReg);
532 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
533 /// debug info. It's the same as what we use for resolving the code-gen
534 /// references for now. FIXME: This can go wrong when references are
535 /// SP-relative and simple call frames aren't used.
536 int ARM64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
538 unsigned &FrameReg) const {
539 return resolveFrameIndexReference(MF, FI, FrameReg);
542 int ARM64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
543 int FI, unsigned &FrameReg,
544 bool PreferFP) const {
545 const MachineFrameInfo *MFI = MF.getFrameInfo();
546 const ARM64RegisterInfo *RegInfo =
547 static_cast<const ARM64RegisterInfo *>(MF.getTarget().getRegisterInfo());
548 const ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
549 int FPOffset = MFI->getObjectOffset(FI) + 16;
550 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
551 bool isFixed = MFI->isFixedObjectIndex(FI);
553 // Use frame pointer to reference fixed objects. Use it for locals if
554 // there are VLAs (and thus the SP isn't reliable as a base).
555 // Make sure useFPForScavengingIndex() does the right thing for the emergency
558 if (AFI->hasStackFrame()) {
559 // Note: Keeping the following as multiple 'if' statements rather than
560 // merging to a single expression for readability.
562 // Argument access should always use the FP.
565 } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF)) {
566 // Use SP or FP, whichever gives us the best chance of the offset
567 // being in range for direct access. If the FPOffset is positive,
568 // that'll always be best, as the SP will be even further away.
569 // If the FPOffset is negative, we have to keep in mind that the
570 // available offset range for negative offsets is smaller than for
571 // positive ones. If we have variable sized objects, we're stuck with
572 // using the FP regardless, though, as the SP offset is unknown
573 // and we don't have a base pointer available. If an offset is
574 // available via the FP and the SP, use whichever is closest.
575 if (PreferFP || MFI->hasVarSizedObjects() || FPOffset >= 0 ||
576 (FPOffset >= -256 && Offset > -FPOffset))
582 FrameReg = RegInfo->getFrameRegister(MF);
586 // Use the base pointer if we have one.
587 if (RegInfo->hasBasePointer(MF))
588 FrameReg = RegInfo->getBaseRegister();
590 FrameReg = ARM64::SP;
591 // If we're using the red zone for this function, the SP won't actually
592 // be adjusted, so the offsets will be negative. They're also all
593 // within range of the signed 9-bit immediate instructions.
594 if (canUseRedZone(MF))
595 Offset -= AFI->getLocalStackSize();
601 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
602 if (Reg != ARM64::LR)
603 return getKillRegState(true);
605 // LR maybe referred to later by an @llvm.returnaddress intrinsic.
606 bool LRLiveIn = MF.getRegInfo().isLiveIn(ARM64::LR);
607 bool LRKill = !(LRLiveIn && MF.getFrameInfo()->isReturnAddressTaken());
608 return getKillRegState(LRKill);
611 bool ARM64FrameLowering::spillCalleeSavedRegisters(
612 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
613 const std::vector<CalleeSavedInfo> &CSI,
614 const TargetRegisterInfo *TRI) const {
615 MachineFunction &MF = *MBB.getParent();
616 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
617 unsigned Count = CSI.size();
619 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
622 DL = MI->getDebugLoc();
624 for (unsigned i = 0; i < Count; i += 2) {
625 unsigned idx = Count - i - 2;
626 unsigned Reg1 = CSI[idx].getReg();
627 unsigned Reg2 = CSI[idx + 1].getReg();
628 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
629 // list to come in sorted by frame index so that we can issue the store
630 // pair instructions directly. Assert if we see anything otherwise.
632 // The order of the registers in the list is controlled by
633 // getCalleeSavedRegs(), so they will always be in-order, as well.
634 assert(CSI[idx].getFrameIdx() + 1 == CSI[idx + 1].getFrameIdx() &&
635 "Out of order callee saved regs!");
637 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
638 assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
639 // Issue sequence of non-sp increment and pi sp spills for cs regs. The
640 // first spill is a pre-increment that allocates the stack.
642 // stp x22, x21, [sp, #-48]! // addImm(-6)
643 // stp x20, x19, [sp, #16] // addImm(+2)
644 // stp fp, lr, [sp, #32] // addImm(+4)
645 // Rationale: This sequence saves uop updates compared to a sequence of
646 // pre-increment spills like stp xi,xj,[sp,#-16]!
647 // Note: Similar rational and sequence for restores in epilog.
648 if (ARM64::GPR64RegClass.contains(Reg1)) {
649 assert(ARM64::GPR64RegClass.contains(Reg2) &&
650 "Expected GPR64 callee-saved register pair!");
651 // For first spill use pre-increment store.
653 StrOpc = ARM64::STPXpre;
655 StrOpc = ARM64::STPXi;
656 } else if (ARM64::FPR64RegClass.contains(Reg1)) {
657 assert(ARM64::FPR64RegClass.contains(Reg2) &&
658 "Expected FPR64 callee-saved register pair!");
659 // For first spill use pre-increment store.
661 StrOpc = ARM64::STPDpre;
663 StrOpc = ARM64::STPDi;
665 llvm_unreachable("Unexpected callee saved register!");
666 DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1) << ", "
667 << TRI->getName(Reg2) << ") -> fi#(" << CSI[idx].getFrameIdx()
668 << ", " << CSI[idx + 1].getFrameIdx() << ")\n");
669 // Compute offset: i = 0 => offset = -Count;
670 // i = 2 => offset = -(Count - 2) + Count = 2 = i; etc.
671 const int Offset = (i == 0) ? -Count : i;
672 assert((Offset >= -64 && Offset <= 63) &&
673 "Offset out of bounds for STP immediate");
674 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
675 if (StrOpc == ARM64::STPDpre || StrOpc == ARM64::STPXpre)
676 MIB.addReg(ARM64::SP, RegState::Define);
678 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2))
679 .addReg(Reg1, getPrologueDeath(MF, Reg1))
681 .addImm(Offset) // [sp, #offset * 8], where factor * 8 is implicit
682 .setMIFlag(MachineInstr::FrameSetup);
687 bool ARM64FrameLowering::restoreCalleeSavedRegisters(
688 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
689 const std::vector<CalleeSavedInfo> &CSI,
690 const TargetRegisterInfo *TRI) const {
691 MachineFunction &MF = *MBB.getParent();
692 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
693 unsigned Count = CSI.size();
695 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
698 DL = MI->getDebugLoc();
700 for (unsigned i = 0; i < Count; i += 2) {
701 unsigned Reg1 = CSI[i].getReg();
702 unsigned Reg2 = CSI[i + 1].getReg();
703 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
704 // list to come in sorted by frame index so that we can issue the store
705 // pair instructions directly. Assert if we see anything otherwise.
706 assert(CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx() &&
707 "Out of order callee saved regs!");
708 // Issue sequence of non-sp increment and sp-pi restores for cs regs. Only
709 // the last load is sp-pi post-increment and de-allocates the stack:
711 // ldp fp, lr, [sp, #32] // addImm(+4)
712 // ldp x20, x19, [sp, #16] // addImm(+2)
713 // ldp x22, x21, [sp], #48 // addImm(+6)
714 // Note: see comment in spillCalleeSavedRegisters()
717 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
718 assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
719 if (ARM64::GPR64RegClass.contains(Reg1)) {
720 assert(ARM64::GPR64RegClass.contains(Reg2) &&
721 "Expected GPR64 callee-saved register pair!");
723 LdrOpc = ARM64::LDPXpost;
725 LdrOpc = ARM64::LDPXi;
726 } else if (ARM64::FPR64RegClass.contains(Reg1)) {
727 assert(ARM64::FPR64RegClass.contains(Reg2) &&
728 "Expected FPR64 callee-saved register pair!");
730 LdrOpc = ARM64::LDPDpost;
732 LdrOpc = ARM64::LDPDi;
734 llvm_unreachable("Unexpected callee saved register!");
735 DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1) << ", "
736 << TRI->getName(Reg2) << ") -> fi#(" << CSI[i].getFrameIdx()
737 << ", " << CSI[i + 1].getFrameIdx() << ")\n");
739 // Compute offset: i = 0 => offset = Count - 2; i = 2 => offset = Count - 4;
741 const int Offset = (i == Count - 2) ? Count : Count - i - 2;
742 assert((Offset >= -64 && Offset <= 63) &&
743 "Offset out of bounds for LDP immediate");
744 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
745 if (LdrOpc == ARM64::LDPXpost || LdrOpc == ARM64::LDPDpost)
746 MIB.addReg(ARM64::SP, RegState::Define);
748 MIB.addReg(Reg2, getDefRegState(true))
749 .addReg(Reg1, getDefRegState(true))
751 .addImm(Offset); // [sp], #offset * 8 or [sp, #offset * 8]
752 // where the factor * 8 is implicit
757 void ARM64FrameLowering::processFunctionBeforeCalleeSavedScan(
758 MachineFunction &MF, RegScavenger *RS) const {
759 const ARM64RegisterInfo *RegInfo =
760 static_cast<const ARM64RegisterInfo *>(MF.getTarget().getRegisterInfo());
761 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
762 MachineRegisterInfo *MRI = &MF.getRegInfo();
763 SmallVector<unsigned, 4> UnspilledCSGPRs;
764 SmallVector<unsigned, 4> UnspilledCSFPRs;
766 // The frame record needs to be created by saving the appropriate registers
768 MRI->setPhysRegUsed(ARM64::FP);
769 MRI->setPhysRegUsed(ARM64::LR);
772 // Spill the BasePtr if it's used. Do this first thing so that the
773 // getCalleeSavedRegs() below will get the right answer.
774 if (RegInfo->hasBasePointer(MF))
775 MRI->setPhysRegUsed(RegInfo->getBaseRegister());
777 // If any callee-saved registers are used, the frame cannot be eliminated.
778 unsigned NumGPRSpilled = 0;
779 unsigned NumFPRSpilled = 0;
780 bool ExtraCSSpill = false;
781 bool CanEliminateFrame = true;
782 DEBUG(dbgs() << "*** processFunctionBeforeCalleeSavedScan\nUsed CSRs:");
783 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
785 // Check pairs of consecutive callee-saved registers.
786 for (unsigned i = 0; CSRegs[i]; i += 2) {
787 assert(CSRegs[i + 1] && "Odd number of callee-saved registers!");
789 const unsigned OddReg = CSRegs[i];
790 const unsigned EvenReg = CSRegs[i + 1];
791 assert((ARM64::GPR64RegClass.contains(OddReg) &&
792 ARM64::GPR64RegClass.contains(EvenReg)) ^
793 (ARM64::FPR64RegClass.contains(OddReg) &&
794 ARM64::FPR64RegClass.contains(EvenReg)) &&
795 "Register class mismatch!");
797 const bool OddRegUsed = MRI->isPhysRegUsed(OddReg);
798 const bool EvenRegUsed = MRI->isPhysRegUsed(EvenReg);
800 // Early exit if none of the registers in the register pair is actually
802 if (!OddRegUsed && !EvenRegUsed) {
803 if (ARM64::GPR64RegClass.contains(OddReg)) {
804 UnspilledCSGPRs.push_back(OddReg);
805 UnspilledCSGPRs.push_back(EvenReg);
807 UnspilledCSFPRs.push_back(OddReg);
808 UnspilledCSFPRs.push_back(EvenReg);
813 unsigned Reg = ARM64::NoRegister;
814 // If only one of the registers of the register pair is used, make sure to
815 // mark the other one as used as well.
816 if (OddRegUsed ^ EvenRegUsed) {
817 // Find out which register is the additional spill.
818 Reg = OddRegUsed ? EvenReg : OddReg;
819 MRI->setPhysRegUsed(Reg);
822 DEBUG(dbgs() << ' ' << PrintReg(OddReg, RegInfo));
823 DEBUG(dbgs() << ' ' << PrintReg(EvenReg, RegInfo));
825 assert(((OddReg == ARM64::LR && EvenReg == ARM64::FP) ||
826 (RegInfo->getEncodingValue(OddReg) + 1 ==
827 RegInfo->getEncodingValue(EvenReg))) &&
828 "Register pair of non-adjacent registers!");
829 if (ARM64::GPR64RegClass.contains(OddReg)) {
831 // If it's not a reserved register, we can use it in lieu of an
832 // emergency spill slot for the register scavenger.
833 // FIXME: It would be better to instead keep looking and choose another
834 // unspilled register that isn't reserved, if there is one.
835 if (Reg != ARM64::NoRegister && !RegInfo->isReservedReg(MF, Reg))
840 CanEliminateFrame = false;
843 // FIXME: Set BigStack if any stack slot references may be out of range.
844 // For now, just conservatively guestimate based on unscaled indexing
845 // range. We'll end up allocating an unnecessary spill slot a lot, but
846 // realistically that's not a big deal at this stage of the game.
847 // The CSR spill slots have not been allocated yet, so estimateStackSize
848 // won't include them.
849 MachineFrameInfo *MFI = MF.getFrameInfo();
850 unsigned CFSize = estimateStackSize(MF) + 8 * (NumGPRSpilled + NumFPRSpilled);
851 DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
852 bool BigStack = (CFSize >= 256);
853 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
854 AFI->setHasStackFrame(true);
856 // Estimate if we might need to scavenge a register at some point in order
857 // to materialize a stack offset. If so, either spill one additional
858 // callee-saved register or reserve a special spill slot to facilitate
859 // register scavenging. If we already spilled an extra callee-saved register
860 // above to keep the number of spills even, we don't need to do anything else
862 if (BigStack && !ExtraCSSpill) {
864 // If we're adding a register to spill here, we have to add two of them
865 // to keep the number of regs to spill even.
866 assert(((UnspilledCSGPRs.size() & 1) == 0) && "Odd number of registers!");
868 while (!UnspilledCSGPRs.empty() && Count < 2) {
869 unsigned Reg = UnspilledCSGPRs.back();
870 UnspilledCSGPRs.pop_back();
871 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, RegInfo)
872 << " to get a scratch register.\n");
873 MRI->setPhysRegUsed(Reg);
878 // If we didn't find an extra callee-saved register to spill, create
879 // an emergency spill slot.
881 const TargetRegisterClass *RC = &ARM64::GPR64RegClass;
882 int FI = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false);
883 RS->addScavengingFrameIndex(FI);
884 DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
885 << " as the emergency spill slot.\n");