1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
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 ARM implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "ARMFrameLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "MCTargetDesc/ARMAddressingModes.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/RegisterScavenging.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Target/TargetOptions.h"
32 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
33 cl::desc("Align ARM NEON spills in prolog and epilog"));
35 static MachineBasicBlock::iterator
36 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
37 unsigned NumAlignedDPRCS2Regs);
39 /// hasFP - Return true if the specified function should have a dedicated frame
40 /// pointer register. This is true if the function has variable sized allocas
41 /// or if frame pointer elimination is disabled.
42 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
43 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
45 // iOS requires FP not to be clobbered for backtracing purpose.
46 if (STI.isTargetIOS())
49 const MachineFrameInfo *MFI = MF.getFrameInfo();
50 // Always eliminate non-leaf frame pointers.
51 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
53 RegInfo->needsStackRealignment(MF) ||
54 MFI->hasVarSizedObjects() ||
55 MFI->isFrameAddressTaken());
58 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
59 /// not required, we reserve argument space for call sites in the function
60 /// immediately on entry to the current function. This eliminates the need for
61 /// add/sub sp brackets around call sites. Returns true if the call frame is
62 /// included as part of the stack frame.
63 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
64 const MachineFrameInfo *FFI = MF.getFrameInfo();
65 unsigned CFSize = FFI->getMaxCallFrameSize();
66 // It's not always a good idea to include the call frame as part of the
67 // stack frame. ARM (especially Thumb) has small immediate offset to
68 // address the stack frame. So a large call frame can cause poor codegen
69 // and may even makes it impossible to scavenge a register.
70 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
73 return !MF.getFrameInfo()->hasVarSizedObjects();
76 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
77 /// call frame pseudos can be simplified. Unlike most targets, having a FP
78 /// is not sufficient here since we still may reference some objects via SP
79 /// even when FP is available in Thumb2 mode.
81 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
82 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
85 static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
86 for (unsigned i = 0; CSRegs[i]; ++i)
92 static bool isCSRestore(MachineInstr *MI,
93 const ARMBaseInstrInfo &TII,
94 const uint16_t *CSRegs) {
95 // Integer spill area is handled with "pop".
96 if (isPopOpcode(MI->getOpcode())) {
97 // The first two operands are predicates. The last two are
98 // imp-def and imp-use of SP. Check everything in between.
99 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
100 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
104 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
105 MI->getOpcode() == ARM::LDR_POST_REG ||
106 MI->getOpcode() == ARM::t2LDR_POST) &&
107 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
108 MI->getOperand(1).getReg() == ARM::SP)
114 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
115 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
116 const ARMBaseInstrInfo &TII, unsigned DestReg,
117 unsigned SrcReg, int NumBytes,
118 unsigned MIFlags = MachineInstr::NoFlags,
119 ARMCC::CondCodes Pred = ARMCC::AL,
120 unsigned PredReg = 0) {
122 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
123 Pred, PredReg, TII, MIFlags);
125 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
126 Pred, PredReg, TII, MIFlags);
129 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
130 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
131 const ARMBaseInstrInfo &TII, int NumBytes,
132 unsigned MIFlags = MachineInstr::NoFlags,
133 ARMCC::CondCodes Pred = ARMCC::AL,
134 unsigned PredReg = 0) {
135 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
136 MIFlags, Pred, PredReg);
139 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
140 MachineBasicBlock &MBB = MF.front();
141 MachineBasicBlock::iterator MBBI = MBB.begin();
142 MachineFrameInfo *MFI = MF.getFrameInfo();
143 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
144 const ARMBaseRegisterInfo *RegInfo =
145 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
146 const ARMBaseInstrInfo &TII =
147 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
148 assert(!AFI->isThumb1OnlyFunction() &&
149 "This emitPrologue does not support Thumb1!");
150 bool isARM = !AFI->isThumbFunction();
151 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
152 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
153 unsigned NumBytes = MFI->getStackSize();
154 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
155 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
156 unsigned FramePtr = RegInfo->getFrameRegister(MF);
158 // Determine the sizes of each callee-save spill areas and record which frame
159 // belongs to which callee-save spill areas.
160 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
161 int FramePtrSpillFI = 0;
164 // All calls are tail calls in GHC calling conv, and functions have no
165 // prologue/epilogue.
166 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
169 // Allocate the vararg register save area. This is not counted in NumBytes.
171 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
172 MachineInstr::FrameSetup);
174 if (!AFI->hasStackFrame()) {
176 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
177 MachineInstr::FrameSetup);
181 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
182 unsigned Reg = CSI[i].getReg();
183 int FI = CSI[i].getFrameIdx();
195 FramePtrSpillFI = FI;
204 FramePtrSpillFI = FI;
205 if (STI.isTargetIOS())
211 // This is a DPR. Exclude the aligned DPRCS2 spills.
214 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
220 MachineBasicBlock::iterator LastPush = MBB.end(), FramePtrPush;
222 FramePtrPush = LastPush = MBBI++;
224 // Determine starting offsets of spill areas.
225 bool HasFP = hasFP(MF);
226 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
227 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
228 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
229 int FramePtrOffsetInPush = 0;
231 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI) + GPRCS1Size;
232 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
235 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
236 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
237 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
240 if (GPRCS2Size > 0) {
247 // Since vpush register list cannot have gaps, there may be multiple vpush
248 // instructions in the prologue.
249 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
253 // Move past the aligned DPRCS2 area.
254 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
255 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
256 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
257 // leaves the stack pointer pointing to the DPRCS2 area.
259 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
260 NumBytes += MFI->getObjectOffset(D8SpillFI);
262 NumBytes = DPRCSOffset;
265 // Adjust SP after all the callee-save spills.
266 if (tryFoldSPUpdateIntoPushPop(MF, LastPush, NumBytes))
267 FramePtrOffsetInPush += NumBytes;
269 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
270 MachineInstr::FrameSetup);
273 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
274 // Note it's not safe to do this in Thumb2 mode because it would have
275 // taken two instructions:
278 // If an interrupt is taken between the two instructions, then sp is in
279 // an inconsistent state (pointing to the middle of callee-saved area).
280 // The interrupt handler can end up clobbering the registers.
281 AFI->setShouldRestoreSPFromFP(true);
284 // Set FP to point to the stack slot that contains the previous FP.
285 // For iOS, FP is R7, which has now been stored in spill area 1.
286 // Otherwise, if this is not iOS, all the callee-saved registers go
287 // into spill area 1, including the FP in R11. In either case, it
288 // is in area one and the adjustment needs to take place just after
291 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, ++FramePtrPush, dl, TII,
292 FramePtr, ARM::SP, FramePtrOffsetInPush,
293 MachineInstr::FrameSetup);
296 if (STI.isTargetELF() && hasFP(MF))
297 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
298 AFI->getFramePtrSpillOffset());
300 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
301 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
302 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
304 // If we need dynamic stack realignment, do it here. Be paranoid and make
305 // sure if we also have VLAs, we have a base pointer for frame access.
306 // If aligned NEON registers were spilled, the stack has already been
308 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
309 unsigned MaxAlign = MFI->getMaxAlignment();
310 assert (!AFI->isThumb1OnlyFunction());
311 if (!AFI->isThumbFunction()) {
312 // Emit bic sp, sp, MaxAlign
313 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
314 TII.get(ARM::BICri), ARM::SP)
315 .addReg(ARM::SP, RegState::Kill)
316 .addImm(MaxAlign-1)));
318 // We cannot use sp as source/dest register here, thus we're emitting the
319 // following sequence:
321 // bic r4, r4, MaxAlign
323 // FIXME: It will be better just to find spare register here.
324 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
325 .addReg(ARM::SP, RegState::Kill));
326 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
327 TII.get(ARM::t2BICri), ARM::R4)
328 .addReg(ARM::R4, RegState::Kill)
329 .addImm(MaxAlign-1)));
330 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
331 .addReg(ARM::R4, RegState::Kill));
334 AFI->setShouldRestoreSPFromFP(true);
337 // If we need a base pointer, set it up here. It's whatever the value
338 // of the stack pointer is at this point. Any variable size objects
339 // will be allocated after this, so we can still use the base pointer
340 // to reference locals.
341 // FIXME: Clarify FrameSetup flags here.
342 if (RegInfo->hasBasePointer(MF)) {
344 BuildMI(MBB, MBBI, dl,
345 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
347 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
349 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
350 RegInfo->getBaseRegister())
354 // If the frame has variable sized objects then the epilogue must restore
355 // the sp from fp. We can assume there's an FP here since hasFP already
356 // checks for hasVarSizedObjects.
357 if (MFI->hasVarSizedObjects())
358 AFI->setShouldRestoreSPFromFP(true);
361 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
362 MachineBasicBlock &MBB) const {
363 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
364 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
365 unsigned RetOpcode = MBBI->getOpcode();
366 DebugLoc dl = MBBI->getDebugLoc();
367 MachineFrameInfo *MFI = MF.getFrameInfo();
368 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
369 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
370 const ARMBaseInstrInfo &TII =
371 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
372 assert(!AFI->isThumb1OnlyFunction() &&
373 "This emitEpilogue does not support Thumb1!");
374 bool isARM = !AFI->isThumbFunction();
376 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
377 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
378 int NumBytes = (int)MFI->getStackSize();
379 unsigned FramePtr = RegInfo->getFrameRegister(MF);
381 // All calls are tail calls in GHC calling conv, and functions have no
382 // prologue/epilogue.
383 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
386 if (!AFI->hasStackFrame()) {
388 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
390 MachineBasicBlock::iterator FirstPop = MBBI;
392 // Unwind MBBI to point to first LDR / VLDRD.
393 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
394 if (MBBI != MBB.begin()) {
396 if (isPopOpcode(MBBI->getOpcode()))
400 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
401 if (!isCSRestore(MBBI, TII, CSRegs))
405 // Move SP to start of FP callee save spill area.
406 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
407 AFI->getGPRCalleeSavedArea2Size() +
408 AFI->getDPRCalleeSavedAreaSize());
410 // Reset SP based on frame pointer only if the stack frame extends beyond
411 // frame pointer stack slot or target is ELF and the function has FP.
412 if (AFI->shouldRestoreSPFromFP()) {
413 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
416 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
419 // It's not possible to restore SP from FP in a single instruction.
420 // For iOS, this looks like:
423 // This is bad, if an interrupt is taken after the mov, sp is in an
424 // inconsistent state.
425 // Use the first callee-saved register as a scratch register.
426 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
427 "No scratch register to restore SP from FP!");
428 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
430 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
437 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
438 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
440 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
444 } else if (NumBytes && !tryFoldSPUpdateIntoPushPop(MF, FirstPop, NumBytes))
445 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
447 // Increment past our save areas.
448 if (AFI->getDPRCalleeSavedAreaSize()) {
450 // Since vpop register list cannot have gaps, there may be multiple vpop
451 // instructions in the epilogue.
452 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
455 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
456 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
459 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
460 // Tail call return: adjust the stack pointer and jump to callee.
461 MBBI = MBB.getLastNonDebugInstr();
462 MachineOperand &JumpTarget = MBBI->getOperand(0);
464 // Jump to label or value in register.
465 if (RetOpcode == ARM::TCRETURNdi) {
466 unsigned TCOpcode = STI.isThumb() ?
467 (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
469 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
470 if (JumpTarget.isGlobal())
471 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
472 JumpTarget.getTargetFlags());
474 assert(JumpTarget.isSymbol());
475 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
476 JumpTarget.getTargetFlags());
479 // Add the default predicate in Thumb mode.
480 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
481 } else if (RetOpcode == ARM::TCRETURNri) {
482 BuildMI(MBB, MBBI, dl,
483 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
484 addReg(JumpTarget.getReg(), RegState::Kill);
487 MachineInstr *NewMI = prior(MBBI);
488 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
489 NewMI->addOperand(MBBI->getOperand(i));
491 // Delete the pseudo instruction TCRETURN.
497 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
500 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
501 /// debug info. It's the same as what we use for resolving the code-gen
502 /// references for now. FIXME: This can go wrong when references are
503 /// SP-relative and simple call frames aren't used.
505 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
506 unsigned &FrameReg) const {
507 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
511 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
512 int FI, unsigned &FrameReg,
514 const MachineFrameInfo *MFI = MF.getFrameInfo();
515 const ARMBaseRegisterInfo *RegInfo =
516 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
517 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
518 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
519 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
520 bool isFixed = MFI->isFixedObjectIndex(FI);
525 // SP can move around if there are allocas. We may also lose track of SP
526 // when emergency spilling inside a non-reserved call frame setup.
527 bool hasMovingSP = !hasReservedCallFrame(MF);
529 // When dynamically realigning the stack, use the frame pointer for
530 // parameters, and the stack/base pointer for locals.
531 if (RegInfo->needsStackRealignment(MF)) {
532 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
534 FrameReg = RegInfo->getFrameRegister(MF);
536 } else if (hasMovingSP) {
537 assert(RegInfo->hasBasePointer(MF) &&
538 "VLAs and dynamic stack alignment, but missing base pointer!");
539 FrameReg = RegInfo->getBaseRegister();
544 // If there is a frame pointer, use it when we can.
545 if (hasFP(MF) && AFI->hasStackFrame()) {
546 // Use frame pointer to reference fixed objects. Use it for locals if
547 // there are VLAs (and thus the SP isn't reliable as a base).
548 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
549 FrameReg = RegInfo->getFrameRegister(MF);
551 } else if (hasMovingSP) {
552 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
553 if (AFI->isThumb2Function()) {
554 // Try to use the frame pointer if we can, else use the base pointer
555 // since it's available. This is handy for the emergency spill slot, in
557 if (FPOffset >= -255 && FPOffset < 0) {
558 FrameReg = RegInfo->getFrameRegister(MF);
562 } else if (AFI->isThumb2Function()) {
563 // Use add <rd>, sp, #<imm8>
564 // ldr <rd>, [sp, #<imm8>]
565 // if at all possible to save space.
566 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
568 // In Thumb2 mode, the negative offset is very limited. Try to avoid
569 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
570 if (FPOffset >= -255 && FPOffset < 0) {
571 FrameReg = RegInfo->getFrameRegister(MF);
574 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
575 // Otherwise, use SP or FP, whichever is closer to the stack slot.
576 FrameReg = RegInfo->getFrameRegister(MF);
580 // Use the base pointer if we have one.
581 if (RegInfo->hasBasePointer(MF))
582 FrameReg = RegInfo->getBaseRegister();
586 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
589 return getFrameIndexReference(MF, FI, FrameReg);
592 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
593 MachineBasicBlock::iterator MI,
594 const std::vector<CalleeSavedInfo> &CSI,
595 unsigned StmOpc, unsigned StrOpc,
597 bool(*Func)(unsigned, bool),
598 unsigned NumAlignedDPRCS2Regs,
599 unsigned MIFlags) const {
600 MachineFunction &MF = *MBB.getParent();
601 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
604 if (MI != MBB.end()) DL = MI->getDebugLoc();
606 SmallVector<std::pair<unsigned,bool>, 4> Regs;
607 unsigned i = CSI.size();
609 unsigned LastReg = 0;
610 for (; i != 0; --i) {
611 unsigned Reg = CSI[i-1].getReg();
612 if (!(Func)(Reg, STI.isTargetIOS())) continue;
614 // D-registers in the aligned area DPRCS2 are NOT spilled here.
615 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
618 // Add the callee-saved register as live-in unless it's LR and
619 // @llvm.returnaddress is called. If LR is returned for
620 // @llvm.returnaddress then it's already added to the function and
621 // entry block live-in sets.
623 if (Reg == ARM::LR) {
624 if (MF.getFrameInfo()->isReturnAddressTaken() &&
625 MF.getRegInfo().isLiveIn(Reg))
632 // If NoGap is true, push consecutive registers and then leave the rest
633 // for other instructions. e.g.
634 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
635 if (NoGap && LastReg && LastReg != Reg-1)
638 Regs.push_back(std::make_pair(Reg, isKill));
643 if (Regs.size() > 1 || StrOpc== 0) {
644 MachineInstrBuilder MIB =
645 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
646 .addReg(ARM::SP).setMIFlags(MIFlags));
647 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
648 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
649 } else if (Regs.size() == 1) {
650 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
652 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
653 .addReg(ARM::SP).setMIFlags(MIFlags)
661 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
662 MachineBasicBlock::iterator MI,
663 const std::vector<CalleeSavedInfo> &CSI,
664 unsigned LdmOpc, unsigned LdrOpc,
665 bool isVarArg, bool NoGap,
666 bool(*Func)(unsigned, bool),
667 unsigned NumAlignedDPRCS2Regs) const {
668 MachineFunction &MF = *MBB.getParent();
669 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
670 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
671 DebugLoc DL = MI->getDebugLoc();
672 unsigned RetOpcode = MI->getOpcode();
673 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
674 RetOpcode == ARM::TCRETURNri);
676 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
678 SmallVector<unsigned, 4> Regs;
679 unsigned i = CSI.size();
681 unsigned LastReg = 0;
682 bool DeleteRet = false;
683 for (; i != 0; --i) {
684 unsigned Reg = CSI[i-1].getReg();
685 if (!(Func)(Reg, STI.isTargetIOS())) continue;
687 // The aligned reloads from area DPRCS2 are not inserted here.
688 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
691 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
694 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
695 // Fold the return instruction into the LDM.
699 // If NoGap is true, pop consecutive registers and then leave the rest
700 // for other instructions. e.g.
701 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
702 if (NoGap && LastReg && LastReg != Reg-1)
711 if (Regs.size() > 1 || LdrOpc == 0) {
712 MachineInstrBuilder MIB =
713 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
715 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
716 MIB.addReg(Regs[i], getDefRegState(true));
718 MIB.copyImplicitOps(&*MI);
719 MI->eraseFromParent();
722 } else if (Regs.size() == 1) {
723 // If we adjusted the reg to PC from LR above, switch it back here. We
724 // only do that for LDM.
725 if (Regs[0] == ARM::PC)
727 MachineInstrBuilder MIB =
728 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
729 .addReg(ARM::SP, RegState::Define)
731 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
732 // that refactoring is complete (eventually).
733 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
735 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
744 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
745 /// starting from d8. Also insert stack realignment code and leave the stack
746 /// pointer pointing to the d8 spill slot.
747 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
748 MachineBasicBlock::iterator MI,
749 unsigned NumAlignedDPRCS2Regs,
750 const std::vector<CalleeSavedInfo> &CSI,
751 const TargetRegisterInfo *TRI) {
752 MachineFunction &MF = *MBB.getParent();
753 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
754 DebugLoc DL = MI->getDebugLoc();
755 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
756 MachineFrameInfo &MFI = *MF.getFrameInfo();
758 // Mark the D-register spill slots as properly aligned. Since MFI computes
759 // stack slot layout backwards, this can actually mean that the d-reg stack
760 // slot offsets can be wrong. The offset for d8 will always be correct.
761 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
762 unsigned DNum = CSI[i].getReg() - ARM::D8;
765 int FI = CSI[i].getFrameIdx();
766 // The even-numbered registers will be 16-byte aligned, the odd-numbered
767 // registers will be 8-byte aligned.
768 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
770 // The stack slot for D8 needs to be maximally aligned because this is
771 // actually the point where we align the stack pointer. MachineFrameInfo
772 // computes all offsets relative to the incoming stack pointer which is a
773 // bit weird when realigning the stack. Any extra padding for this
774 // over-alignment is not realized because the code inserted below adjusts
775 // the stack pointer by numregs * 8 before aligning the stack pointer.
777 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
780 // Move the stack pointer to the d8 spill slot, and align it at the same
781 // time. Leave the stack slot address in the scratch register r4.
783 // sub r4, sp, #numregs * 8
784 // bic r4, r4, #align - 1
787 bool isThumb = AFI->isThumbFunction();
788 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
789 AFI->setShouldRestoreSPFromFP(true);
791 // sub r4, sp, #numregs * 8
792 // The immediate is <= 64, so it doesn't need any special encoding.
793 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
794 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
796 .addImm(8 * NumAlignedDPRCS2Regs)));
798 // bic r4, r4, #align-1
799 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
800 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
801 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
802 .addReg(ARM::R4, RegState::Kill)
803 .addImm(MaxAlign - 1)));
806 // The stack pointer must be adjusted before spilling anything, otherwise
807 // the stack slots could be clobbered by an interrupt handler.
808 // Leave r4 live, it is used below.
809 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
810 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
812 MIB = AddDefaultPred(MIB);
816 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
817 // r4 holds the stack slot address.
818 unsigned NextReg = ARM::D8;
820 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
821 // The writeback is only needed when emitting two vst1.64 instructions.
822 if (NumAlignedDPRCS2Regs >= 6) {
823 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
825 MBB.addLiveIn(SupReg);
826 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
828 .addReg(ARM::R4, RegState::Kill).addImm(16)
830 .addReg(SupReg, RegState::ImplicitKill));
832 NumAlignedDPRCS2Regs -= 4;
835 // We won't modify r4 beyond this point. It currently points to the next
836 // register to be spilled.
837 unsigned R4BaseReg = NextReg;
839 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
840 if (NumAlignedDPRCS2Regs >= 4) {
841 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
843 MBB.addLiveIn(SupReg);
844 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
845 .addReg(ARM::R4).addImm(16).addReg(NextReg)
846 .addReg(SupReg, RegState::ImplicitKill));
848 NumAlignedDPRCS2Regs -= 4;
851 // 16-byte aligned vst1.64 with 2 d-regs.
852 if (NumAlignedDPRCS2Regs >= 2) {
853 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
855 MBB.addLiveIn(SupReg);
856 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
857 .addReg(ARM::R4).addImm(16).addReg(SupReg));
859 NumAlignedDPRCS2Regs -= 2;
862 // Finally, use a vanilla vstr.64 for the odd last register.
863 if (NumAlignedDPRCS2Regs) {
864 MBB.addLiveIn(NextReg);
865 // vstr.64 uses addrmode5 which has an offset scale of 4.
866 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
868 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
871 // The last spill instruction inserted should kill the scratch register r4.
872 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
875 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
876 /// iterator to the following instruction.
877 static MachineBasicBlock::iterator
878 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
879 unsigned NumAlignedDPRCS2Regs) {
880 // sub r4, sp, #numregs * 8
881 // bic r4, r4, #align - 1
884 assert(MI->mayStore() && "Expecting spill instruction");
886 // These switches all fall through.
887 switch(NumAlignedDPRCS2Regs) {
890 assert(MI->mayStore() && "Expecting spill instruction");
893 assert(MI->mayStore() && "Expecting spill instruction");
897 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
903 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
904 /// starting from d8. These instructions are assumed to execute while the
905 /// stack is still aligned, unlike the code inserted by emitPopInst.
906 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
907 MachineBasicBlock::iterator MI,
908 unsigned NumAlignedDPRCS2Regs,
909 const std::vector<CalleeSavedInfo> &CSI,
910 const TargetRegisterInfo *TRI) {
911 MachineFunction &MF = *MBB.getParent();
912 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
913 DebugLoc DL = MI->getDebugLoc();
914 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
916 // Find the frame index assigned to d8.
918 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
919 if (CSI[i].getReg() == ARM::D8) {
920 D8SpillFI = CSI[i].getFrameIdx();
924 // Materialize the address of the d8 spill slot into the scratch register r4.
925 // This can be fairly complicated if the stack frame is large, so just use
926 // the normal frame index elimination mechanism to do it. This code runs as
927 // the initial part of the epilog where the stack and base pointers haven't
929 bool isThumb = AFI->isThumbFunction();
930 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
932 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
933 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
934 .addFrameIndex(D8SpillFI).addImm(0)));
936 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
937 unsigned NextReg = ARM::D8;
939 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
940 if (NumAlignedDPRCS2Regs >= 6) {
941 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
943 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
944 .addReg(ARM::R4, RegState::Define)
945 .addReg(ARM::R4, RegState::Kill).addImm(16)
946 .addReg(SupReg, RegState::ImplicitDefine));
948 NumAlignedDPRCS2Regs -= 4;
951 // We won't modify r4 beyond this point. It currently points to the next
952 // register to be spilled.
953 unsigned R4BaseReg = NextReg;
955 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
956 if (NumAlignedDPRCS2Regs >= 4) {
957 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
959 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
960 .addReg(ARM::R4).addImm(16)
961 .addReg(SupReg, RegState::ImplicitDefine));
963 NumAlignedDPRCS2Regs -= 4;
966 // 16-byte aligned vld1.64 with 2 d-regs.
967 if (NumAlignedDPRCS2Regs >= 2) {
968 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
970 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
971 .addReg(ARM::R4).addImm(16));
973 NumAlignedDPRCS2Regs -= 2;
976 // Finally, use a vanilla vldr.64 for the remaining odd register.
977 if (NumAlignedDPRCS2Regs)
978 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
979 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
981 // Last store kills r4.
982 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
985 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
986 MachineBasicBlock::iterator MI,
987 const std::vector<CalleeSavedInfo> &CSI,
988 const TargetRegisterInfo *TRI) const {
992 MachineFunction &MF = *MBB.getParent();
993 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
995 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
996 unsigned PushOneOpc = AFI->isThumbFunction() ?
997 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
998 unsigned FltOpc = ARM::VSTMDDB_UPD;
999 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1000 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1001 MachineInstr::FrameSetup);
1002 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1003 MachineInstr::FrameSetup);
1004 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1005 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1007 // The code above does not insert spill code for the aligned DPRCS2 registers.
1008 // The stack realignment code will be inserted between the push instructions
1009 // and these spills.
1010 if (NumAlignedDPRCS2Regs)
1011 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1016 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1017 MachineBasicBlock::iterator MI,
1018 const std::vector<CalleeSavedInfo> &CSI,
1019 const TargetRegisterInfo *TRI) const {
1023 MachineFunction &MF = *MBB.getParent();
1024 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1025 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1026 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1028 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1029 // registers. Do that here instead.
1030 if (NumAlignedDPRCS2Regs)
1031 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1033 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1034 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1035 unsigned FltOpc = ARM::VLDMDIA_UPD;
1036 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1037 NumAlignedDPRCS2Regs);
1038 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1039 &isARMArea2Register, 0);
1040 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1041 &isARMArea1Register, 0);
1046 // FIXME: Make generic?
1047 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1048 const ARMBaseInstrInfo &TII) {
1049 unsigned FnSize = 0;
1050 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
1051 MBBI != E; ++MBBI) {
1052 const MachineBasicBlock &MBB = *MBBI;
1053 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
1055 FnSize += TII.GetInstSizeInBytes(I);
1060 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1061 /// frames and return the stack size limit beyond which some of these
1062 /// instructions will require a scratch register during their expansion later.
1063 // FIXME: Move to TII?
1064 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1065 const TargetFrameLowering *TFI) {
1066 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1067 unsigned Limit = (1 << 12) - 1;
1068 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
1069 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1071 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1072 if (!I->getOperand(i).isFI()) continue;
1074 // When using ADDri to get the address of a stack object, 255 is the
1075 // largest offset guaranteed to fit in the immediate offset.
1076 if (I->getOpcode() == ARM::ADDri) {
1077 Limit = std::min(Limit, (1U << 8) - 1);
1081 // Otherwise check the addressing mode.
1082 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
1083 case ARMII::AddrMode3:
1084 case ARMII::AddrModeT2_i8:
1085 Limit = std::min(Limit, (1U << 8) - 1);
1087 case ARMII::AddrMode5:
1088 case ARMII::AddrModeT2_i8s4:
1089 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1091 case ARMII::AddrModeT2_i12:
1092 // i12 supports only positive offset so these will be converted to
1093 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1094 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1095 Limit = std::min(Limit, (1U << 8) - 1);
1097 case ARMII::AddrMode4:
1098 case ARMII::AddrMode6:
1099 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1100 // immediate offset for stack references.
1105 break; // At most one FI per instruction
1113 // In functions that realign the stack, it can be an advantage to spill the
1114 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1115 // instructions take alignment hints that can improve performance.
1117 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1118 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1119 if (!SpillAlignedNEONRegs)
1122 // Naked functions don't spill callee-saved registers.
1123 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1127 // We are planning to use NEON instructions vst1 / vld1.
1128 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1131 // Don't bother if the default stack alignment is sufficiently high.
1132 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1135 // Aligned spills require stack realignment.
1136 const ARMBaseRegisterInfo *RegInfo =
1137 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1138 if (!RegInfo->canRealignStack(MF))
1141 // We always spill contiguous d-registers starting from d8. Count how many
1142 // needs spilling. The register allocator will almost always use the
1143 // callee-saved registers in order, but it can happen that there are holes in
1144 // the range. Registers above the hole will be spilled to the standard DPRCS
1146 MachineRegisterInfo &MRI = MF.getRegInfo();
1147 unsigned NumSpills = 0;
1148 for (; NumSpills < 8; ++NumSpills)
1149 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1152 // Don't do this for just one d-register. It's not worth it.
1156 // Spill the first NumSpills D-registers after realigning the stack.
1157 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1159 // A scratch register is required for the vst1 / vld1 instructions.
1160 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1164 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1165 RegScavenger *RS) const {
1166 // This tells PEI to spill the FP as if it is any other callee-save register
1167 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1168 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1169 // to combine multiple loads / stores.
1170 bool CanEliminateFrame = true;
1171 bool CS1Spilled = false;
1172 bool LRSpilled = false;
1173 unsigned NumGPRSpills = 0;
1174 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1175 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1176 const ARMBaseRegisterInfo *RegInfo =
1177 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1178 const ARMBaseInstrInfo &TII =
1179 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1180 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1181 MachineFrameInfo *MFI = MF.getFrameInfo();
1182 MachineRegisterInfo &MRI = MF.getRegInfo();
1183 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1185 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1186 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1187 // since it's not always possible to restore sp from fp in a single
1189 // FIXME: It will be better just to find spare register here.
1190 if (AFI->isThumb2Function() &&
1191 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1192 MRI.setPhysRegUsed(ARM::R4);
1194 if (AFI->isThumb1OnlyFunction()) {
1195 // Spill LR if Thumb1 function uses variable length argument lists.
1196 if (AFI->getArgRegsSaveSize() > 0)
1197 MRI.setPhysRegUsed(ARM::LR);
1199 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1200 // for sure what the stack size will be, but for this, an estimate is good
1201 // enough. If there anything changes it, it'll be a spill, which implies
1202 // we've used all the registers and so R4 is already used, so not marking
1203 // it here will be OK.
1204 // FIXME: It will be better just to find spare register here.
1205 unsigned StackSize = MFI->estimateStackSize(MF);
1206 if (MFI->hasVarSizedObjects() || StackSize > 508)
1207 MRI.setPhysRegUsed(ARM::R4);
1210 // See if we can spill vector registers to aligned stack.
1211 checkNumAlignedDPRCS2Regs(MF);
1213 // Spill the BasePtr if it's used.
1214 if (RegInfo->hasBasePointer(MF))
1215 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1217 // Don't spill FP if the frame can be eliminated. This is determined
1218 // by scanning the callee-save registers to see if any is used.
1219 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1220 for (unsigned i = 0; CSRegs[i]; ++i) {
1221 unsigned Reg = CSRegs[i];
1222 bool Spilled = false;
1223 if (MRI.isPhysRegUsed(Reg)) {
1225 CanEliminateFrame = false;
1228 if (!ARM::GPRRegClass.contains(Reg))
1234 if (!STI.isTargetIOS()) {
1241 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1246 case ARM::R0: case ARM::R1:
1247 case ARM::R2: case ARM::R3:
1248 case ARM::R4: case ARM::R5:
1249 case ARM::R6: case ARM::R7:
1256 if (!STI.isTargetIOS()) {
1257 UnspilledCS1GPRs.push_back(Reg);
1262 case ARM::R0: case ARM::R1:
1263 case ARM::R2: case ARM::R3:
1264 case ARM::R4: case ARM::R5:
1265 case ARM::R6: case ARM::R7:
1267 UnspilledCS1GPRs.push_back(Reg);
1270 UnspilledCS2GPRs.push_back(Reg);
1276 bool ForceLRSpill = false;
1277 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1278 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1279 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1280 // use of BL to implement far jump. If it turns out that it's not needed
1281 // then the branch fix up path will undo it.
1282 if (FnSize >= (1 << 11)) {
1283 CanEliminateFrame = false;
1284 ForceLRSpill = true;
1288 // If any of the stack slot references may be out of range of an immediate
1289 // offset, make sure a register (or a spill slot) is available for the
1290 // register scavenger. Note that if we're indexing off the frame pointer, the
1291 // effective stack size is 4 bytes larger since the FP points to the stack
1292 // slot of the previous FP. Also, if we have variable sized objects in the
1293 // function, stack slot references will often be negative, and some of
1294 // our instructions are positive-offset only, so conservatively consider
1295 // that case to want a spill slot (or register) as well. Similarly, if
1296 // the function adjusts the stack pointer during execution and the
1297 // adjustments aren't already part of our stack size estimate, our offset
1298 // calculations may be off, so be conservative.
1299 // FIXME: We could add logic to be more precise about negative offsets
1300 // and which instructions will need a scratch register for them. Is it
1301 // worth the effort and added fragility?
1304 (MFI->estimateStackSize(MF) +
1305 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1306 estimateRSStackSizeLimit(MF, this)))
1307 || MFI->hasVarSizedObjects()
1308 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1310 bool ExtraCSSpill = false;
1311 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1312 AFI->setHasStackFrame(true);
1314 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1315 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1316 if (!LRSpilled && CS1Spilled) {
1317 MRI.setPhysRegUsed(ARM::LR);
1319 SmallVectorImpl<unsigned>::iterator LRPos;
1320 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1322 if (LRPos != UnspilledCS1GPRs.end())
1323 UnspilledCS1GPRs.erase(LRPos);
1325 ForceLRSpill = false;
1326 ExtraCSSpill = true;
1330 MRI.setPhysRegUsed(FramePtr);
1334 // If stack and double are 8-byte aligned and we are spilling an odd number
1335 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1336 // the integer and double callee save areas.
1337 unsigned TargetAlign = getStackAlignment();
1338 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1339 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1340 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1341 unsigned Reg = UnspilledCS1GPRs[i];
1342 // Don't spill high register if the function is thumb1
1343 if (!AFI->isThumb1OnlyFunction() ||
1344 isARMLowRegister(Reg) || Reg == ARM::LR) {
1345 MRI.setPhysRegUsed(Reg);
1346 if (!MRI.isReserved(Reg))
1347 ExtraCSSpill = true;
1351 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1352 unsigned Reg = UnspilledCS2GPRs.front();
1353 MRI.setPhysRegUsed(Reg);
1354 if (!MRI.isReserved(Reg))
1355 ExtraCSSpill = true;
1359 // Estimate if we might need to scavenge a register at some point in order
1360 // to materialize a stack offset. If so, either spill one additional
1361 // callee-saved register or reserve a special spill slot to facilitate
1362 // register scavenging. Thumb1 needs a spill slot for stack pointer
1363 // adjustments also, even when the frame itself is small.
1364 if (BigStack && !ExtraCSSpill) {
1365 // If any non-reserved CS register isn't spilled, just spill one or two
1366 // extra. That should take care of it!
1367 unsigned NumExtras = TargetAlign / 4;
1368 SmallVector<unsigned, 2> Extras;
1369 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1370 unsigned Reg = UnspilledCS1GPRs.back();
1371 UnspilledCS1GPRs.pop_back();
1372 if (!MRI.isReserved(Reg) &&
1373 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1375 Extras.push_back(Reg);
1379 // For non-Thumb1 functions, also check for hi-reg CS registers
1380 if (!AFI->isThumb1OnlyFunction()) {
1381 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1382 unsigned Reg = UnspilledCS2GPRs.back();
1383 UnspilledCS2GPRs.pop_back();
1384 if (!MRI.isReserved(Reg)) {
1385 Extras.push_back(Reg);
1390 if (Extras.size() && NumExtras == 0) {
1391 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1392 MRI.setPhysRegUsed(Extras[i]);
1394 } else if (!AFI->isThumb1OnlyFunction()) {
1395 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1396 // closest to SP or frame pointer.
1397 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1398 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1406 MRI.setPhysRegUsed(ARM::LR);
1407 AFI->setLRIsSpilledForFarJump(true);
1412 void ARMFrameLowering::
1413 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1414 MachineBasicBlock::iterator I) const {
1415 const ARMBaseInstrInfo &TII =
1416 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1417 if (!hasReservedCallFrame(MF)) {
1418 // If we have alloca, convert as follows:
1419 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1420 // ADJCALLSTACKUP -> add, sp, sp, amount
1421 MachineInstr *Old = I;
1422 DebugLoc dl = Old->getDebugLoc();
1423 unsigned Amount = Old->getOperand(0).getImm();
1425 // We need to keep the stack aligned properly. To do this, we round the
1426 // amount of space needed for the outgoing arguments up to the next
1427 // alignment boundary.
1428 unsigned Align = getStackAlignment();
1429 Amount = (Amount+Align-1)/Align*Align;
1431 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1432 assert(!AFI->isThumb1OnlyFunction() &&
1433 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1434 bool isARM = !AFI->isThumbFunction();
1436 // Replace the pseudo instruction with a new instruction...
1437 unsigned Opc = Old->getOpcode();
1438 int PIdx = Old->findFirstPredOperandIdx();
1439 ARMCC::CondCodes Pred = (PIdx == -1)
1440 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1441 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1442 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1443 unsigned PredReg = Old->getOperand(2).getReg();
1444 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1447 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1448 unsigned PredReg = Old->getOperand(3).getReg();
1449 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1450 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,