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 (MI->getOpcode() == ARM::LDMIA_RET ||
97 MI->getOpcode() == ARM::t2LDMIA_RET ||
98 MI->getOpcode() == ARM::LDMIA_UPD ||
99 MI->getOpcode() == ARM::t2LDMIA_UPD ||
100 MI->getOpcode() == ARM::VLDMDIA_UPD) {
101 // The first two operands are predicates. The last two are
102 // imp-def and imp-use of SP. Check everything in between.
103 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
104 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
108 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
109 MI->getOpcode() == ARM::LDR_POST_REG ||
110 MI->getOpcode() == ARM::t2LDR_POST) &&
111 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
112 MI->getOperand(1).getReg() == ARM::SP)
118 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
119 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
120 const ARMBaseInstrInfo &TII, unsigned DestReg,
121 unsigned SrcReg, int NumBytes,
122 unsigned MIFlags = MachineInstr::NoFlags,
123 ARMCC::CondCodes Pred = ARMCC::AL,
124 unsigned PredReg = 0) {
126 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
127 Pred, PredReg, TII, MIFlags);
129 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
130 Pred, PredReg, TII, MIFlags);
133 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
134 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
135 const ARMBaseInstrInfo &TII, int NumBytes,
136 unsigned MIFlags = MachineInstr::NoFlags,
137 ARMCC::CondCodes Pred = ARMCC::AL,
138 unsigned PredReg = 0) {
139 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
140 MIFlags, Pred, PredReg);
143 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
144 MachineBasicBlock &MBB = MF.front();
145 MachineBasicBlock::iterator MBBI = MBB.begin();
146 MachineFrameInfo *MFI = MF.getFrameInfo();
147 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
148 const ARMBaseRegisterInfo *RegInfo =
149 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
150 const ARMBaseInstrInfo &TII =
151 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
152 assert(!AFI->isThumb1OnlyFunction() &&
153 "This emitPrologue does not support Thumb1!");
154 bool isARM = !AFI->isThumbFunction();
155 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
156 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
157 unsigned NumBytes = MFI->getStackSize();
158 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
159 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
160 unsigned FramePtr = RegInfo->getFrameRegister(MF);
162 // Determine the sizes of each callee-save spill areas and record which frame
163 // belongs to which callee-save spill areas.
164 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
165 int FramePtrSpillFI = 0;
168 // All calls are tail calls in GHC calling conv, and functions have no
169 // prologue/epilogue.
170 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
173 // Allocate the vararg register save area. This is not counted in NumBytes.
175 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
176 MachineInstr::FrameSetup);
178 if (!AFI->hasStackFrame()) {
180 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
181 MachineInstr::FrameSetup);
185 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
186 unsigned Reg = CSI[i].getReg();
187 int FI = CSI[i].getFrameIdx();
199 FramePtrSpillFI = FI;
208 FramePtrSpillFI = FI;
209 if (STI.isTargetIOS())
215 // This is a DPR. Exclude the aligned DPRCS2 spills.
218 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
224 if (GPRCS1Size > 0) MBBI++;
226 // Determine starting offsets of spill areas.
227 bool HasFP = hasFP(MF);
228 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
229 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
230 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
232 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
234 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
235 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
236 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
238 // Set FP to point to the stack slot that contains the previous FP.
239 // For iOS, FP is R7, which has now been stored in spill area 1.
240 // Otherwise, if this is not iOS, all the callee-saved registers go
241 // into spill area 1, including the FP in R11. In either case, it is
242 // now safe to emit this assignment.
244 int FramePtrOffset = MFI->getObjectOffset(FramePtrSpillFI) + GPRCS1Size;
245 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, MBBI, dl, TII,
246 FramePtr, ARM::SP, FramePtrOffset,
247 MachineInstr::FrameSetup);
251 if (GPRCS2Size > 0) MBBI++;
256 // Since vpush register list cannot have gaps, there may be multiple vpush
257 // instructions in the prologue.
258 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
262 // Move past the aligned DPRCS2 area.
263 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
264 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
265 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
266 // leaves the stack pointer pointing to the DPRCS2 area.
268 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
269 NumBytes += MFI->getObjectOffset(D8SpillFI);
271 NumBytes = DPRCSOffset;
274 // Adjust SP after all the callee-save spills.
275 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
276 MachineInstr::FrameSetup);
278 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
279 // Note it's not safe to do this in Thumb2 mode because it would have
280 // taken two instructions:
283 // If an interrupt is taken between the two instructions, then sp is in
284 // an inconsistent state (pointing to the middle of callee-saved area).
285 // The interrupt handler can end up clobbering the registers.
286 AFI->setShouldRestoreSPFromFP(true);
289 if (STI.isTargetELF() && hasFP(MF))
290 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
291 AFI->getFramePtrSpillOffset());
293 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
294 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
295 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
297 // If we need dynamic stack realignment, do it here. Be paranoid and make
298 // sure if we also have VLAs, we have a base pointer for frame access.
299 // If aligned NEON registers were spilled, the stack has already been
301 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
302 unsigned MaxAlign = MFI->getMaxAlignment();
303 assert (!AFI->isThumb1OnlyFunction());
304 if (!AFI->isThumbFunction()) {
305 // Emit bic sp, sp, MaxAlign
306 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
307 TII.get(ARM::BICri), ARM::SP)
308 .addReg(ARM::SP, RegState::Kill)
309 .addImm(MaxAlign-1)));
311 // We cannot use sp as source/dest register here, thus we're emitting the
312 // following sequence:
314 // bic r4, r4, MaxAlign
316 // FIXME: It will be better just to find spare register here.
317 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
318 .addReg(ARM::SP, RegState::Kill));
319 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
320 TII.get(ARM::t2BICri), ARM::R4)
321 .addReg(ARM::R4, RegState::Kill)
322 .addImm(MaxAlign-1)));
323 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
324 .addReg(ARM::R4, RegState::Kill));
327 AFI->setShouldRestoreSPFromFP(true);
330 // If we need a base pointer, set it up here. It's whatever the value
331 // of the stack pointer is at this point. Any variable size objects
332 // will be allocated after this, so we can still use the base pointer
333 // to reference locals.
334 // FIXME: Clarify FrameSetup flags here.
335 if (RegInfo->hasBasePointer(MF)) {
337 BuildMI(MBB, MBBI, dl,
338 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
340 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
342 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
343 RegInfo->getBaseRegister())
347 // If the frame has variable sized objects then the epilogue must restore
348 // the sp from fp. We can assume there's an FP here since hasFP already
349 // checks for hasVarSizedObjects.
350 if (MFI->hasVarSizedObjects())
351 AFI->setShouldRestoreSPFromFP(true);
354 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
355 MachineBasicBlock &MBB) const {
356 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
357 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
358 unsigned RetOpcode = MBBI->getOpcode();
359 DebugLoc dl = MBBI->getDebugLoc();
360 MachineFrameInfo *MFI = MF.getFrameInfo();
361 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
362 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
363 const ARMBaseInstrInfo &TII =
364 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
365 assert(!AFI->isThumb1OnlyFunction() &&
366 "This emitEpilogue does not support Thumb1!");
367 bool isARM = !AFI->isThumbFunction();
369 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
370 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
371 int NumBytes = (int)MFI->getStackSize();
372 unsigned FramePtr = RegInfo->getFrameRegister(MF);
374 // All calls are tail calls in GHC calling conv, and functions have no
375 // prologue/epilogue.
376 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
379 if (!AFI->hasStackFrame()) {
381 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
383 // Unwind MBBI to point to first LDR / VLDRD.
384 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
385 if (MBBI != MBB.begin()) {
388 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
389 if (!isCSRestore(MBBI, TII, CSRegs))
393 // Move SP to start of FP callee save spill area.
394 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
395 AFI->getGPRCalleeSavedArea2Size() +
396 AFI->getDPRCalleeSavedAreaSize());
398 // Reset SP based on frame pointer only if the stack frame extends beyond
399 // frame pointer stack slot or target is ELF and the function has FP.
400 if (AFI->shouldRestoreSPFromFP()) {
401 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
404 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
407 // It's not possible to restore SP from FP in a single instruction.
408 // For iOS, this looks like:
411 // This is bad, if an interrupt is taken after the mov, sp is in an
412 // inconsistent state.
413 // Use the first callee-saved register as a scratch register.
414 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
415 "No scratch register to restore SP from FP!");
416 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
418 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
425 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
426 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
428 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
433 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
435 // Increment past our save areas.
436 if (AFI->getDPRCalleeSavedAreaSize()) {
438 // Since vpop register list cannot have gaps, there may be multiple vpop
439 // instructions in the epilogue.
440 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
443 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
444 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
447 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
448 // Tail call return: adjust the stack pointer and jump to callee.
449 MBBI = MBB.getLastNonDebugInstr();
450 MachineOperand &JumpTarget = MBBI->getOperand(0);
452 // Jump to label or value in register.
453 if (RetOpcode == ARM::TCRETURNdi) {
454 unsigned TCOpcode = STI.isThumb() ?
455 (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
457 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
458 if (JumpTarget.isGlobal())
459 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
460 JumpTarget.getTargetFlags());
462 assert(JumpTarget.isSymbol());
463 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
464 JumpTarget.getTargetFlags());
467 // Add the default predicate in Thumb mode.
468 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
469 } else if (RetOpcode == ARM::TCRETURNri) {
470 BuildMI(MBB, MBBI, dl,
471 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
472 addReg(JumpTarget.getReg(), RegState::Kill);
475 MachineInstr *NewMI = prior(MBBI);
476 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
477 NewMI->addOperand(MBBI->getOperand(i));
479 // Delete the pseudo instruction TCRETURN.
485 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
488 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
489 /// debug info. It's the same as what we use for resolving the code-gen
490 /// references for now. FIXME: This can go wrong when references are
491 /// SP-relative and simple call frames aren't used.
493 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
494 unsigned &FrameReg) const {
495 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
499 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
500 int FI, unsigned &FrameReg,
502 const MachineFrameInfo *MFI = MF.getFrameInfo();
503 const ARMBaseRegisterInfo *RegInfo =
504 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
505 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
506 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
507 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
508 bool isFixed = MFI->isFixedObjectIndex(FI);
513 // SP can move around if there are allocas. We may also lose track of SP
514 // when emergency spilling inside a non-reserved call frame setup.
515 bool hasMovingSP = !hasReservedCallFrame(MF);
517 // When dynamically realigning the stack, use the frame pointer for
518 // parameters, and the stack/base pointer for locals.
519 if (RegInfo->needsStackRealignment(MF)) {
520 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
522 FrameReg = RegInfo->getFrameRegister(MF);
524 } else if (hasMovingSP) {
525 assert(RegInfo->hasBasePointer(MF) &&
526 "VLAs and dynamic stack alignment, but missing base pointer!");
527 FrameReg = RegInfo->getBaseRegister();
532 // If there is a frame pointer, use it when we can.
533 if (hasFP(MF) && AFI->hasStackFrame()) {
534 // Use frame pointer to reference fixed objects. Use it for locals if
535 // there are VLAs (and thus the SP isn't reliable as a base).
536 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
537 FrameReg = RegInfo->getFrameRegister(MF);
539 } else if (hasMovingSP) {
540 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
541 if (AFI->isThumb2Function()) {
542 // Try to use the frame pointer if we can, else use the base pointer
543 // since it's available. This is handy for the emergency spill slot, in
545 if (FPOffset >= -255 && FPOffset < 0) {
546 FrameReg = RegInfo->getFrameRegister(MF);
550 } else if (AFI->isThumb2Function()) {
551 // Use add <rd>, sp, #<imm8>
552 // ldr <rd>, [sp, #<imm8>]
553 // if at all possible to save space.
554 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
556 // In Thumb2 mode, the negative offset is very limited. Try to avoid
557 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
558 if (FPOffset >= -255 && FPOffset < 0) {
559 FrameReg = RegInfo->getFrameRegister(MF);
562 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
563 // Otherwise, use SP or FP, whichever is closer to the stack slot.
564 FrameReg = RegInfo->getFrameRegister(MF);
568 // Use the base pointer if we have one.
569 if (RegInfo->hasBasePointer(MF))
570 FrameReg = RegInfo->getBaseRegister();
574 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
577 return getFrameIndexReference(MF, FI, FrameReg);
580 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
581 MachineBasicBlock::iterator MI,
582 const std::vector<CalleeSavedInfo> &CSI,
583 unsigned StmOpc, unsigned StrOpc,
585 bool(*Func)(unsigned, bool),
586 unsigned NumAlignedDPRCS2Regs,
587 unsigned MIFlags) const {
588 MachineFunction &MF = *MBB.getParent();
589 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
592 if (MI != MBB.end()) DL = MI->getDebugLoc();
594 SmallVector<std::pair<unsigned,bool>, 4> Regs;
595 unsigned i = CSI.size();
597 unsigned LastReg = 0;
598 for (; i != 0; --i) {
599 unsigned Reg = CSI[i-1].getReg();
600 if (!(Func)(Reg, STI.isTargetIOS())) continue;
602 // D-registers in the aligned area DPRCS2 are NOT spilled here.
603 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
606 // Add the callee-saved register as live-in unless it's LR and
607 // @llvm.returnaddress is called. If LR is returned for
608 // @llvm.returnaddress then it's already added to the function and
609 // entry block live-in sets.
611 if (Reg == ARM::LR) {
612 if (MF.getFrameInfo()->isReturnAddressTaken() &&
613 MF.getRegInfo().isLiveIn(Reg))
620 // If NoGap is true, push consecutive registers and then leave the rest
621 // for other instructions. e.g.
622 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
623 if (NoGap && LastReg && LastReg != Reg-1)
626 Regs.push_back(std::make_pair(Reg, isKill));
631 if (Regs.size() > 1 || StrOpc== 0) {
632 MachineInstrBuilder MIB =
633 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
634 .addReg(ARM::SP).setMIFlags(MIFlags));
635 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
636 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
637 } else if (Regs.size() == 1) {
638 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
640 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
641 .addReg(ARM::SP).setMIFlags(MIFlags)
649 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
650 MachineBasicBlock::iterator MI,
651 const std::vector<CalleeSavedInfo> &CSI,
652 unsigned LdmOpc, unsigned LdrOpc,
653 bool isVarArg, bool NoGap,
654 bool(*Func)(unsigned, bool),
655 unsigned NumAlignedDPRCS2Regs) const {
656 MachineFunction &MF = *MBB.getParent();
657 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
658 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
659 DebugLoc DL = MI->getDebugLoc();
660 unsigned RetOpcode = MI->getOpcode();
661 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
662 RetOpcode == ARM::TCRETURNri);
664 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
666 SmallVector<unsigned, 4> Regs;
667 unsigned i = CSI.size();
669 unsigned LastReg = 0;
670 bool DeleteRet = false;
671 for (; i != 0; --i) {
672 unsigned Reg = CSI[i-1].getReg();
673 if (!(Func)(Reg, STI.isTargetIOS())) continue;
675 // The aligned reloads from area DPRCS2 are not inserted here.
676 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
679 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
682 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
683 // Fold the return instruction into the LDM.
687 // If NoGap is true, pop consecutive registers and then leave the rest
688 // for other instructions. e.g.
689 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
690 if (NoGap && LastReg && LastReg != Reg-1)
699 if (Regs.size() > 1 || LdrOpc == 0) {
700 MachineInstrBuilder MIB =
701 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
703 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
704 MIB.addReg(Regs[i], getDefRegState(true));
706 MIB.copyImplicitOps(&*MI);
707 MI->eraseFromParent();
710 } else if (Regs.size() == 1) {
711 // If we adjusted the reg to PC from LR above, switch it back here. We
712 // only do that for LDM.
713 if (Regs[0] == ARM::PC)
715 MachineInstrBuilder MIB =
716 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
717 .addReg(ARM::SP, RegState::Define)
719 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
720 // that refactoring is complete (eventually).
721 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
723 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
732 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
733 /// starting from d8. Also insert stack realignment code and leave the stack
734 /// pointer pointing to the d8 spill slot.
735 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
736 MachineBasicBlock::iterator MI,
737 unsigned NumAlignedDPRCS2Regs,
738 const std::vector<CalleeSavedInfo> &CSI,
739 const TargetRegisterInfo *TRI) {
740 MachineFunction &MF = *MBB.getParent();
741 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
742 DebugLoc DL = MI->getDebugLoc();
743 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
744 MachineFrameInfo &MFI = *MF.getFrameInfo();
746 // Mark the D-register spill slots as properly aligned. Since MFI computes
747 // stack slot layout backwards, this can actually mean that the d-reg stack
748 // slot offsets can be wrong. The offset for d8 will always be correct.
749 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
750 unsigned DNum = CSI[i].getReg() - ARM::D8;
753 int FI = CSI[i].getFrameIdx();
754 // The even-numbered registers will be 16-byte aligned, the odd-numbered
755 // registers will be 8-byte aligned.
756 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
758 // The stack slot for D8 needs to be maximally aligned because this is
759 // actually the point where we align the stack pointer. MachineFrameInfo
760 // computes all offsets relative to the incoming stack pointer which is a
761 // bit weird when realigning the stack. Any extra padding for this
762 // over-alignment is not realized because the code inserted below adjusts
763 // the stack pointer by numregs * 8 before aligning the stack pointer.
765 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
768 // Move the stack pointer to the d8 spill slot, and align it at the same
769 // time. Leave the stack slot address in the scratch register r4.
771 // sub r4, sp, #numregs * 8
772 // bic r4, r4, #align - 1
775 bool isThumb = AFI->isThumbFunction();
776 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
777 AFI->setShouldRestoreSPFromFP(true);
779 // sub r4, sp, #numregs * 8
780 // The immediate is <= 64, so it doesn't need any special encoding.
781 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
782 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
784 .addImm(8 * NumAlignedDPRCS2Regs)));
786 // bic r4, r4, #align-1
787 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
788 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
789 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
790 .addReg(ARM::R4, RegState::Kill)
791 .addImm(MaxAlign - 1)));
794 // The stack pointer must be adjusted before spilling anything, otherwise
795 // the stack slots could be clobbered by an interrupt handler.
796 // Leave r4 live, it is used below.
797 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
798 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
800 MIB = AddDefaultPred(MIB);
804 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
805 // r4 holds the stack slot address.
806 unsigned NextReg = ARM::D8;
808 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
809 // The writeback is only needed when emitting two vst1.64 instructions.
810 if (NumAlignedDPRCS2Regs >= 6) {
811 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
813 MBB.addLiveIn(SupReg);
814 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
816 .addReg(ARM::R4, RegState::Kill).addImm(16)
818 .addReg(SupReg, RegState::ImplicitKill));
820 NumAlignedDPRCS2Regs -= 4;
823 // We won't modify r4 beyond this point. It currently points to the next
824 // register to be spilled.
825 unsigned R4BaseReg = NextReg;
827 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
828 if (NumAlignedDPRCS2Regs >= 4) {
829 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
831 MBB.addLiveIn(SupReg);
832 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
833 .addReg(ARM::R4).addImm(16).addReg(NextReg)
834 .addReg(SupReg, RegState::ImplicitKill));
836 NumAlignedDPRCS2Regs -= 4;
839 // 16-byte aligned vst1.64 with 2 d-regs.
840 if (NumAlignedDPRCS2Regs >= 2) {
841 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
843 MBB.addLiveIn(SupReg);
844 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
845 .addReg(ARM::R4).addImm(16).addReg(SupReg));
847 NumAlignedDPRCS2Regs -= 2;
850 // Finally, use a vanilla vstr.64 for the odd last register.
851 if (NumAlignedDPRCS2Regs) {
852 MBB.addLiveIn(NextReg);
853 // vstr.64 uses addrmode5 which has an offset scale of 4.
854 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
856 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
859 // The last spill instruction inserted should kill the scratch register r4.
860 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
863 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
864 /// iterator to the following instruction.
865 static MachineBasicBlock::iterator
866 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
867 unsigned NumAlignedDPRCS2Regs) {
868 // sub r4, sp, #numregs * 8
869 // bic r4, r4, #align - 1
872 assert(MI->mayStore() && "Expecting spill instruction");
874 // These switches all fall through.
875 switch(NumAlignedDPRCS2Regs) {
878 assert(MI->mayStore() && "Expecting spill instruction");
881 assert(MI->mayStore() && "Expecting spill instruction");
885 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
891 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
892 /// starting from d8. These instructions are assumed to execute while the
893 /// stack is still aligned, unlike the code inserted by emitPopInst.
894 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
895 MachineBasicBlock::iterator MI,
896 unsigned NumAlignedDPRCS2Regs,
897 const std::vector<CalleeSavedInfo> &CSI,
898 const TargetRegisterInfo *TRI) {
899 MachineFunction &MF = *MBB.getParent();
900 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
901 DebugLoc DL = MI->getDebugLoc();
902 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
904 // Find the frame index assigned to d8.
906 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
907 if (CSI[i].getReg() == ARM::D8) {
908 D8SpillFI = CSI[i].getFrameIdx();
912 // Materialize the address of the d8 spill slot into the scratch register r4.
913 // This can be fairly complicated if the stack frame is large, so just use
914 // the normal frame index elimination mechanism to do it. This code runs as
915 // the initial part of the epilog where the stack and base pointers haven't
917 bool isThumb = AFI->isThumbFunction();
918 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
920 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
921 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
922 .addFrameIndex(D8SpillFI).addImm(0)));
924 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
925 unsigned NextReg = ARM::D8;
927 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
928 if (NumAlignedDPRCS2Regs >= 6) {
929 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
931 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
932 .addReg(ARM::R4, RegState::Define)
933 .addReg(ARM::R4, RegState::Kill).addImm(16)
934 .addReg(SupReg, RegState::ImplicitDefine));
936 NumAlignedDPRCS2Regs -= 4;
939 // We won't modify r4 beyond this point. It currently points to the next
940 // register to be spilled.
941 unsigned R4BaseReg = NextReg;
943 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
944 if (NumAlignedDPRCS2Regs >= 4) {
945 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
947 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
948 .addReg(ARM::R4).addImm(16)
949 .addReg(SupReg, RegState::ImplicitDefine));
951 NumAlignedDPRCS2Regs -= 4;
954 // 16-byte aligned vld1.64 with 2 d-regs.
955 if (NumAlignedDPRCS2Regs >= 2) {
956 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
958 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
959 .addReg(ARM::R4).addImm(16));
961 NumAlignedDPRCS2Regs -= 2;
964 // Finally, use a vanilla vldr.64 for the remaining odd register.
965 if (NumAlignedDPRCS2Regs)
966 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
967 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
969 // Last store kills r4.
970 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
973 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
974 MachineBasicBlock::iterator MI,
975 const std::vector<CalleeSavedInfo> &CSI,
976 const TargetRegisterInfo *TRI) const {
980 MachineFunction &MF = *MBB.getParent();
981 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
983 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
984 unsigned PushOneOpc = AFI->isThumbFunction() ?
985 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
986 unsigned FltOpc = ARM::VSTMDDB_UPD;
987 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
988 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
989 MachineInstr::FrameSetup);
990 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
991 MachineInstr::FrameSetup);
992 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
993 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
995 // The code above does not insert spill code for the aligned DPRCS2 registers.
996 // The stack realignment code will be inserted between the push instructions
998 if (NumAlignedDPRCS2Regs)
999 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1004 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1005 MachineBasicBlock::iterator MI,
1006 const std::vector<CalleeSavedInfo> &CSI,
1007 const TargetRegisterInfo *TRI) const {
1011 MachineFunction &MF = *MBB.getParent();
1012 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1013 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1014 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1016 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1017 // registers. Do that here instead.
1018 if (NumAlignedDPRCS2Regs)
1019 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1021 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1022 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1023 unsigned FltOpc = ARM::VLDMDIA_UPD;
1024 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1025 NumAlignedDPRCS2Regs);
1026 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1027 &isARMArea2Register, 0);
1028 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1029 &isARMArea1Register, 0);
1034 // FIXME: Make generic?
1035 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1036 const ARMBaseInstrInfo &TII) {
1037 unsigned FnSize = 0;
1038 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
1039 MBBI != E; ++MBBI) {
1040 const MachineBasicBlock &MBB = *MBBI;
1041 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
1043 FnSize += TII.GetInstSizeInBytes(I);
1048 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1049 /// frames and return the stack size limit beyond which some of these
1050 /// instructions will require a scratch register during their expansion later.
1051 // FIXME: Move to TII?
1052 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1053 const TargetFrameLowering *TFI) {
1054 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1055 unsigned Limit = (1 << 12) - 1;
1056 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
1057 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1059 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1060 if (!I->getOperand(i).isFI()) continue;
1062 // When using ADDri to get the address of a stack object, 255 is the
1063 // largest offset guaranteed to fit in the immediate offset.
1064 if (I->getOpcode() == ARM::ADDri) {
1065 Limit = std::min(Limit, (1U << 8) - 1);
1069 // Otherwise check the addressing mode.
1070 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
1071 case ARMII::AddrMode3:
1072 case ARMII::AddrModeT2_i8:
1073 Limit = std::min(Limit, (1U << 8) - 1);
1075 case ARMII::AddrMode5:
1076 case ARMII::AddrModeT2_i8s4:
1077 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1079 case ARMII::AddrModeT2_i12:
1080 // i12 supports only positive offset so these will be converted to
1081 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1082 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1083 Limit = std::min(Limit, (1U << 8) - 1);
1085 case ARMII::AddrMode4:
1086 case ARMII::AddrMode6:
1087 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1088 // immediate offset for stack references.
1093 break; // At most one FI per instruction
1101 // In functions that realign the stack, it can be an advantage to spill the
1102 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1103 // instructions take alignment hints that can improve performance.
1105 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1106 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1107 if (!SpillAlignedNEONRegs)
1110 // Naked functions don't spill callee-saved registers.
1111 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1115 // We are planning to use NEON instructions vst1 / vld1.
1116 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1119 // Don't bother if the default stack alignment is sufficiently high.
1120 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1123 // Aligned spills require stack realignment.
1124 const ARMBaseRegisterInfo *RegInfo =
1125 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1126 if (!RegInfo->canRealignStack(MF))
1129 // We always spill contiguous d-registers starting from d8. Count how many
1130 // needs spilling. The register allocator will almost always use the
1131 // callee-saved registers in order, but it can happen that there are holes in
1132 // the range. Registers above the hole will be spilled to the standard DPRCS
1134 MachineRegisterInfo &MRI = MF.getRegInfo();
1135 unsigned NumSpills = 0;
1136 for (; NumSpills < 8; ++NumSpills)
1137 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1140 // Don't do this for just one d-register. It's not worth it.
1144 // Spill the first NumSpills D-registers after realigning the stack.
1145 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1147 // A scratch register is required for the vst1 / vld1 instructions.
1148 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1152 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1153 RegScavenger *RS) const {
1154 // This tells PEI to spill the FP as if it is any other callee-save register
1155 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1156 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1157 // to combine multiple loads / stores.
1158 bool CanEliminateFrame = true;
1159 bool CS1Spilled = false;
1160 bool LRSpilled = false;
1161 unsigned NumGPRSpills = 0;
1162 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1163 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1164 const ARMBaseRegisterInfo *RegInfo =
1165 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1166 const ARMBaseInstrInfo &TII =
1167 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1168 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1169 MachineFrameInfo *MFI = MF.getFrameInfo();
1170 MachineRegisterInfo &MRI = MF.getRegInfo();
1171 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1173 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1174 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1175 // since it's not always possible to restore sp from fp in a single
1177 // FIXME: It will be better just to find spare register here.
1178 if (AFI->isThumb2Function() &&
1179 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1180 MRI.setPhysRegUsed(ARM::R4);
1182 if (AFI->isThumb1OnlyFunction()) {
1183 // Spill LR if Thumb1 function uses variable length argument lists.
1184 if (AFI->getArgRegsSaveSize() > 0)
1185 MRI.setPhysRegUsed(ARM::LR);
1187 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1188 // for sure what the stack size will be, but for this, an estimate is good
1189 // enough. If there anything changes it, it'll be a spill, which implies
1190 // we've used all the registers and so R4 is already used, so not marking
1191 // it here will be OK.
1192 // FIXME: It will be better just to find spare register here.
1193 unsigned StackSize = MFI->estimateStackSize(MF);
1194 if (MFI->hasVarSizedObjects() || StackSize > 508)
1195 MRI.setPhysRegUsed(ARM::R4);
1198 // See if we can spill vector registers to aligned stack.
1199 checkNumAlignedDPRCS2Regs(MF);
1201 // Spill the BasePtr if it's used.
1202 if (RegInfo->hasBasePointer(MF))
1203 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1205 // Don't spill FP if the frame can be eliminated. This is determined
1206 // by scanning the callee-save registers to see if any is used.
1207 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1208 for (unsigned i = 0; CSRegs[i]; ++i) {
1209 unsigned Reg = CSRegs[i];
1210 bool Spilled = false;
1211 if (MRI.isPhysRegUsed(Reg)) {
1213 CanEliminateFrame = false;
1216 if (!ARM::GPRRegClass.contains(Reg))
1222 if (!STI.isTargetIOS()) {
1229 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1234 case ARM::R0: case ARM::R1:
1235 case ARM::R2: case ARM::R3:
1236 case ARM::R4: case ARM::R5:
1237 case ARM::R6: case ARM::R7:
1244 if (!STI.isTargetIOS()) {
1245 UnspilledCS1GPRs.push_back(Reg);
1250 case ARM::R0: case ARM::R1:
1251 case ARM::R2: case ARM::R3:
1252 case ARM::R4: case ARM::R5:
1253 case ARM::R6: case ARM::R7:
1255 UnspilledCS1GPRs.push_back(Reg);
1258 UnspilledCS2GPRs.push_back(Reg);
1264 bool ForceLRSpill = false;
1265 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1266 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1267 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1268 // use of BL to implement far jump. If it turns out that it's not needed
1269 // then the branch fix up path will undo it.
1270 if (FnSize >= (1 << 11)) {
1271 CanEliminateFrame = false;
1272 ForceLRSpill = true;
1276 // If any of the stack slot references may be out of range of an immediate
1277 // offset, make sure a register (or a spill slot) is available for the
1278 // register scavenger. Note that if we're indexing off the frame pointer, the
1279 // effective stack size is 4 bytes larger since the FP points to the stack
1280 // slot of the previous FP. Also, if we have variable sized objects in the
1281 // function, stack slot references will often be negative, and some of
1282 // our instructions are positive-offset only, so conservatively consider
1283 // that case to want a spill slot (or register) as well. Similarly, if
1284 // the function adjusts the stack pointer during execution and the
1285 // adjustments aren't already part of our stack size estimate, our offset
1286 // calculations may be off, so be conservative.
1287 // FIXME: We could add logic to be more precise about negative offsets
1288 // and which instructions will need a scratch register for them. Is it
1289 // worth the effort and added fragility?
1292 (MFI->estimateStackSize(MF) +
1293 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1294 estimateRSStackSizeLimit(MF, this)))
1295 || MFI->hasVarSizedObjects()
1296 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1298 bool ExtraCSSpill = false;
1299 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1300 AFI->setHasStackFrame(true);
1302 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1303 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1304 if (!LRSpilled && CS1Spilled) {
1305 MRI.setPhysRegUsed(ARM::LR);
1307 SmallVectorImpl<unsigned>::iterator LRPos;
1308 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1310 if (LRPos != UnspilledCS1GPRs.end())
1311 UnspilledCS1GPRs.erase(LRPos);
1313 ForceLRSpill = false;
1314 ExtraCSSpill = true;
1318 MRI.setPhysRegUsed(FramePtr);
1322 // If stack and double are 8-byte aligned and we are spilling an odd number
1323 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1324 // the integer and double callee save areas.
1325 unsigned TargetAlign = getStackAlignment();
1326 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1327 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1328 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1329 unsigned Reg = UnspilledCS1GPRs[i];
1330 // Don't spill high register if the function is thumb1
1331 if (!AFI->isThumb1OnlyFunction() ||
1332 isARMLowRegister(Reg) || Reg == ARM::LR) {
1333 MRI.setPhysRegUsed(Reg);
1334 if (!MRI.isReserved(Reg))
1335 ExtraCSSpill = true;
1339 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1340 unsigned Reg = UnspilledCS2GPRs.front();
1341 MRI.setPhysRegUsed(Reg);
1342 if (!MRI.isReserved(Reg))
1343 ExtraCSSpill = true;
1347 // Estimate if we might need to scavenge a register at some point in order
1348 // to materialize a stack offset. If so, either spill one additional
1349 // callee-saved register or reserve a special spill slot to facilitate
1350 // register scavenging. Thumb1 needs a spill slot for stack pointer
1351 // adjustments also, even when the frame itself is small.
1352 if (BigStack && !ExtraCSSpill) {
1353 // If any non-reserved CS register isn't spilled, just spill one or two
1354 // extra. That should take care of it!
1355 unsigned NumExtras = TargetAlign / 4;
1356 SmallVector<unsigned, 2> Extras;
1357 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1358 unsigned Reg = UnspilledCS1GPRs.back();
1359 UnspilledCS1GPRs.pop_back();
1360 if (!MRI.isReserved(Reg) &&
1361 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1363 Extras.push_back(Reg);
1367 // For non-Thumb1 functions, also check for hi-reg CS registers
1368 if (!AFI->isThumb1OnlyFunction()) {
1369 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1370 unsigned Reg = UnspilledCS2GPRs.back();
1371 UnspilledCS2GPRs.pop_back();
1372 if (!MRI.isReserved(Reg)) {
1373 Extras.push_back(Reg);
1378 if (Extras.size() && NumExtras == 0) {
1379 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1380 MRI.setPhysRegUsed(Extras[i]);
1382 } else if (!AFI->isThumb1OnlyFunction()) {
1383 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1384 // closest to SP or frame pointer.
1385 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1386 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1394 MRI.setPhysRegUsed(ARM::LR);
1395 AFI->setLRIsSpilledForFarJump(true);
1400 void ARMFrameLowering::
1401 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1402 MachineBasicBlock::iterator I) const {
1403 const ARMBaseInstrInfo &TII =
1404 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1405 if (!hasReservedCallFrame(MF)) {
1406 // If we have alloca, convert as follows:
1407 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1408 // ADJCALLSTACKUP -> add, sp, sp, amount
1409 MachineInstr *Old = I;
1410 DebugLoc dl = Old->getDebugLoc();
1411 unsigned Amount = Old->getOperand(0).getImm();
1413 // We need to keep the stack aligned properly. To do this, we round the
1414 // amount of space needed for the outgoing arguments up to the next
1415 // alignment boundary.
1416 unsigned Align = getStackAlignment();
1417 Amount = (Amount+Align-1)/Align*Align;
1419 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1420 assert(!AFI->isThumb1OnlyFunction() &&
1421 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1422 bool isARM = !AFI->isThumbFunction();
1424 // Replace the pseudo instruction with a new instruction...
1425 unsigned Opc = Old->getOpcode();
1426 int PIdx = Old->findFirstPredOperandIdx();
1427 ARMCC::CondCodes Pred = (PIdx == -1)
1428 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1429 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1430 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1431 unsigned PredReg = Old->getOperand(2).getReg();
1432 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1435 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1436 unsigned PredReg = Old->getOperand(3).getReg();
1437 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1438 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,