1 //=======- ARMFrameLowering.cpp - ARM Frame Information --------*- C++ -*-====//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the ARM implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "ARMFrameLowering.h"
15 #include "ARMAddressingModes.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMMachineFunctionInfo.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/Target/TargetOptions.h"
28 /// hasFP - Return true if the specified function should have a dedicated frame
29 /// pointer register. This is true if the function has variable sized allocas
30 /// or if frame pointer elimination is disabled.
31 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
32 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
34 // Mac OS X requires FP not to be clobbered for backtracing purpose.
35 if (STI.isTargetDarwin())
38 const MachineFrameInfo *MFI = MF.getFrameInfo();
39 // Always eliminate non-leaf frame pointers.
40 return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
41 RegInfo->needsStackRealignment(MF) ||
42 MFI->hasVarSizedObjects() ||
43 MFI->isFrameAddressTaken());
46 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
47 /// not required, we reserve argument space for call sites in the function
48 /// immediately on entry to the current function. This eliminates the need for
49 /// add/sub sp brackets around call sites. Returns true if the call frame is
50 /// included as part of the stack frame.
51 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
52 const MachineFrameInfo *FFI = MF.getFrameInfo();
53 unsigned CFSize = FFI->getMaxCallFrameSize();
54 // It's not always a good idea to include the call frame as part of the
55 // stack frame. ARM (especially Thumb) has small immediate offset to
56 // address the stack frame. So a large call frame can cause poor codegen
57 // and may even makes it impossible to scavenge a register.
58 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
61 return !MF.getFrameInfo()->hasVarSizedObjects();
64 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
65 /// call frame pseudos can be simplified. Unlike most targets, having a FP
66 /// is not sufficient here since we still may reference some objects via SP
67 /// even when FP is available in Thumb2 mode.
69 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
70 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
73 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
74 for (unsigned i = 0; CSRegs[i]; ++i)
80 static bool isCSRestore(MachineInstr *MI,
81 const ARMBaseInstrInfo &TII,
82 const unsigned *CSRegs) {
83 // Integer spill area is handled with "pop".
84 if (MI->getOpcode() == ARM::LDMIA_RET ||
85 MI->getOpcode() == ARM::t2LDMIA_RET ||
86 MI->getOpcode() == ARM::LDMIA_UPD ||
87 MI->getOpcode() == ARM::t2LDMIA_UPD ||
88 MI->getOpcode() == ARM::VLDMDIA_UPD) {
89 // The first two operands are predicates. The last two are
90 // imp-def and imp-use of SP. Check everything in between.
91 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
92 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
96 if ((MI->getOpcode() == ARM::LDR_POST ||
97 MI->getOpcode() == ARM::t2LDR_POST) &&
98 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
99 MI->getOperand(1).getReg() == ARM::SP)
106 emitSPUpdate(bool isARM,
107 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
108 DebugLoc dl, const ARMBaseInstrInfo &TII,
110 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
112 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
115 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
119 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
120 MachineBasicBlock &MBB = MF.front();
121 MachineBasicBlock::iterator MBBI = MBB.begin();
122 MachineFrameInfo *MFI = MF.getFrameInfo();
123 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
124 const ARMBaseRegisterInfo *RegInfo =
125 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
126 const ARMBaseInstrInfo &TII =
127 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
128 assert(!AFI->isThumb1OnlyFunction() &&
129 "This emitPrologue does not support Thumb1!");
130 bool isARM = !AFI->isThumbFunction();
131 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
132 unsigned NumBytes = MFI->getStackSize();
133 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
134 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
135 unsigned FramePtr = RegInfo->getFrameRegister(MF);
137 // Determine the sizes of each callee-save spill areas and record which frame
138 // belongs to which callee-save spill areas.
139 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
140 int FramePtrSpillFI = 0;
142 // Allocate the vararg register save area. This is not counted in NumBytes.
144 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
146 if (!AFI->hasStackFrame()) {
148 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
152 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
153 unsigned Reg = CSI[i].getReg();
154 int FI = CSI[i].getFrameIdx();
162 FramePtrSpillFI = FI;
163 AFI->addGPRCalleeSavedArea1Frame(FI);
171 FramePtrSpillFI = FI;
172 if (STI.isTargetDarwin()) {
173 AFI->addGPRCalleeSavedArea2Frame(FI);
176 AFI->addGPRCalleeSavedArea1Frame(FI);
181 AFI->addDPRCalleeSavedAreaFrame(FI);
187 if (GPRCS1Size > 0) MBBI++;
189 // Set FP to point to the stack slot that contains the previous FP.
190 // For Darwin, FP is R7, which has now been stored in spill area 1.
191 // Otherwise, if this is not Darwin, all the callee-saved registers go
192 // into spill area 1, including the FP in R11. In either case, it is
193 // now safe to emit this assignment.
194 bool HasFP = hasFP(MF);
196 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
197 MachineInstrBuilder MIB =
198 BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
199 .addFrameIndex(FramePtrSpillFI).addImm(0);
200 AddDefaultCC(AddDefaultPred(MIB));
204 if (GPRCS2Size > 0) MBBI++;
206 // Determine starting offsets of spill areas.
207 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
208 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
209 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
211 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
213 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
214 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
215 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
220 // Since vpush register list cannot have gaps, there may be multiple vpush
221 // instructions in the epilogue.
222 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
226 NumBytes = DPRCSOffset;
228 // Adjust SP after all the callee-save spills.
229 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
231 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
232 // Note it's not safe to do this in Thumb2 mode because it would have
233 // taken two instructions:
236 // If an interrupt is taken between the two instructions, then sp is in
237 // an inconsistent state (pointing to the middle of callee-saved area).
238 // The interrupt handler can end up clobbering the registers.
239 AFI->setShouldRestoreSPFromFP(true);
242 if (STI.isTargetELF() && hasFP(MF))
243 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
244 AFI->getFramePtrSpillOffset());
246 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
247 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
248 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
250 // If we need dynamic stack realignment, do it here. Be paranoid and make
251 // sure if we also have VLAs, we have a base pointer for frame access.
252 if (RegInfo->needsStackRealignment(MF)) {
253 unsigned MaxAlign = MFI->getMaxAlignment();
254 assert (!AFI->isThumb1OnlyFunction());
255 if (!AFI->isThumbFunction()) {
256 // Emit bic sp, sp, MaxAlign
257 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
258 TII.get(ARM::BICri), ARM::SP)
259 .addReg(ARM::SP, RegState::Kill)
260 .addImm(MaxAlign-1)));
262 // We cannot use sp as source/dest register here, thus we're emitting the
263 // following sequence:
265 // bic r4, r4, MaxAlign
267 // FIXME: It will be better just to find spare register here.
268 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
269 .addReg(ARM::SP, RegState::Kill);
270 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
271 TII.get(ARM::t2BICri), ARM::R4)
272 .addReg(ARM::R4, RegState::Kill)
273 .addImm(MaxAlign-1)));
274 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
275 .addReg(ARM::R4, RegState::Kill);
278 AFI->setShouldRestoreSPFromFP(true);
281 // If we need a base pointer, set it up here. It's whatever the value
282 // of the stack pointer is at this point. Any variable size objects
283 // will be allocated after this, so we can still use the base pointer
284 // to reference locals.
285 if (RegInfo->hasBasePointer(MF)) {
287 BuildMI(MBB, MBBI, dl,
288 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
290 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
292 BuildMI(MBB, MBBI, dl,
293 TII.get(ARM::tMOVgpr2gpr), RegInfo->getBaseRegister())
297 // If the frame has variable sized objects then the epilogue must restore
298 // the sp from fp. We can assume there's an FP here since hasFP already
299 // checks for hasVarSizedObjects.
300 if (MFI->hasVarSizedObjects())
301 AFI->setShouldRestoreSPFromFP(true);
304 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
305 MachineBasicBlock &MBB) const {
306 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
307 assert(MBBI->getDesc().isReturn() &&
308 "Can only insert epilog into returning blocks");
309 unsigned RetOpcode = MBBI->getOpcode();
310 DebugLoc dl = MBBI->getDebugLoc();
311 MachineFrameInfo *MFI = MF.getFrameInfo();
312 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
313 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
314 const ARMBaseInstrInfo &TII =
315 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
316 assert(!AFI->isThumb1OnlyFunction() &&
317 "This emitEpilogue does not support Thumb1!");
318 bool isARM = !AFI->isThumbFunction();
320 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
321 int NumBytes = (int)MFI->getStackSize();
322 unsigned FramePtr = RegInfo->getFrameRegister(MF);
324 if (!AFI->hasStackFrame()) {
326 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
328 // Unwind MBBI to point to first LDR / VLDRD.
329 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
330 if (MBBI != MBB.begin()) {
333 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
334 if (!isCSRestore(MBBI, TII, CSRegs))
338 // Move SP to start of FP callee save spill area.
339 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
340 AFI->getGPRCalleeSavedArea2Size() +
341 AFI->getDPRCalleeSavedAreaSize());
343 // Reset SP based on frame pointer only if the stack frame extends beyond
344 // frame pointer stack slot or target is ELF and the function has FP.
345 if (AFI->shouldRestoreSPFromFP()) {
346 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
349 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
352 // It's not possible to restore SP from FP in a single instruction.
353 // For Darwin, this looks like:
356 // This is bad, if an interrupt is taken after the mov, sp is in an
357 // inconsistent state.
358 // Use the first callee-saved register as a scratch register.
359 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
360 "No scratch register to restore SP from FP!");
361 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
363 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
369 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
370 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
372 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
376 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
378 // Increment past our save areas.
379 if (AFI->getDPRCalleeSavedAreaSize()) {
381 // Since vpop register list cannot have gaps, there may be multiple vpop
382 // instructions in the epilogue.
383 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
386 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
387 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
390 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
391 RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
392 // Tail call return: adjust the stack pointer and jump to callee.
393 MBBI = MBB.getLastNonDebugInstr();
394 MachineOperand &JumpTarget = MBBI->getOperand(0);
396 // Jump to label or value in register.
397 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND) {
398 unsigned TCOpcode = (RetOpcode == ARM::TCRETURNdi)
399 ? (STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)
400 : (STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND);
401 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
402 if (JumpTarget.isGlobal())
403 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
404 JumpTarget.getTargetFlags());
406 assert(JumpTarget.isSymbol());
407 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
408 JumpTarget.getTargetFlags());
410 } else if (RetOpcode == ARM::TCRETURNri) {
411 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
412 addReg(JumpTarget.getReg(), RegState::Kill);
413 } else if (RetOpcode == ARM::TCRETURNriND) {
414 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
415 addReg(JumpTarget.getReg(), RegState::Kill);
418 MachineInstr *NewMI = prior(MBBI);
419 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
420 NewMI->addOperand(MBBI->getOperand(i));
422 // Delete the pseudo instruction TCRETURN.
427 emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
430 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
431 /// debug info. It's the same as what we use for resolving the code-gen
432 /// references for now. FIXME: This can go wrong when references are
433 /// SP-relative and simple call frames aren't used.
435 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
436 unsigned &FrameReg) const {
437 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
441 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
445 const MachineFrameInfo *MFI = MF.getFrameInfo();
446 const ARMBaseRegisterInfo *RegInfo =
447 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
448 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
449 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
450 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
451 bool isFixed = MFI->isFixedObjectIndex(FI);
455 if (AFI->isGPRCalleeSavedArea1Frame(FI))
456 return Offset - AFI->getGPRCalleeSavedArea1Offset();
457 else if (AFI->isGPRCalleeSavedArea2Frame(FI))
458 return Offset - AFI->getGPRCalleeSavedArea2Offset();
459 else if (AFI->isDPRCalleeSavedAreaFrame(FI))
460 return Offset - AFI->getDPRCalleeSavedAreaOffset();
462 // When dynamically realigning the stack, use the frame pointer for
463 // parameters, and the stack/base pointer for locals.
464 if (RegInfo->needsStackRealignment(MF)) {
465 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
467 FrameReg = RegInfo->getFrameRegister(MF);
469 } else if (MFI->hasVarSizedObjects()) {
470 assert(RegInfo->hasBasePointer(MF) &&
471 "VLAs and dynamic stack alignment, but missing base pointer!");
472 FrameReg = RegInfo->getBaseRegister();
477 // If there is a frame pointer, use it when we can.
478 if (hasFP(MF) && AFI->hasStackFrame()) {
479 // Use frame pointer to reference fixed objects. Use it for locals if
480 // there are VLAs (and thus the SP isn't reliable as a base).
481 if (isFixed || (MFI->hasVarSizedObjects() &&
482 !RegInfo->hasBasePointer(MF))) {
483 FrameReg = RegInfo->getFrameRegister(MF);
485 } else if (MFI->hasVarSizedObjects()) {
486 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
487 // Try to use the frame pointer if we can, else use the base pointer
488 // since it's available. This is handy for the emergency spill slot, in
490 if (AFI->isThumb2Function()) {
491 if (FPOffset >= -255 && FPOffset < 0) {
492 FrameReg = RegInfo->getFrameRegister(MF);
496 FrameReg = RegInfo->getBaseRegister();
497 } else if (AFI->isThumb2Function()) {
498 // In Thumb2 mode, the negative offset is very limited. Try to avoid
499 // out of range references.
500 if (FPOffset >= -255 && FPOffset < 0) {
501 FrameReg = RegInfo->getFrameRegister(MF);
504 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
505 // Otherwise, use SP or FP, whichever is closer to the stack slot.
506 FrameReg = RegInfo->getFrameRegister(MF);
510 // Use the base pointer if we have one.
511 if (RegInfo->hasBasePointer(MF))
512 FrameReg = RegInfo->getBaseRegister();
516 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
519 return getFrameIndexReference(MF, FI, FrameReg);
522 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
523 MachineBasicBlock::iterator MI,
524 const std::vector<CalleeSavedInfo> &CSI,
525 unsigned StmOpc, unsigned StrOpc,
527 bool(*Func)(unsigned, bool)) const {
528 MachineFunction &MF = *MBB.getParent();
529 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
532 if (MI != MBB.end()) DL = MI->getDebugLoc();
534 SmallVector<std::pair<unsigned,bool>, 4> Regs;
535 unsigned i = CSI.size();
537 unsigned LastReg = 0;
538 for (; i != 0; --i) {
539 unsigned Reg = CSI[i-1].getReg();
540 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
542 // Add the callee-saved register as live-in unless it's LR and
543 // @llvm.returnaddress is called. If LR is returned for
544 // @llvm.returnaddress then it's already added to the function and
545 // entry block live-in sets.
547 if (Reg == ARM::LR) {
548 if (MF.getFrameInfo()->isReturnAddressTaken() &&
549 MF.getRegInfo().isLiveIn(Reg))
556 // If NoGap is true, push consecutive registers and then leave the rest
557 // for other instructions. e.g.
558 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
559 if (NoGap && LastReg && LastReg != Reg-1)
562 Regs.push_back(std::make_pair(Reg, isKill));
567 if (Regs.size() > 1 || StrOpc== 0) {
568 MachineInstrBuilder MIB =
569 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
571 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
572 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
573 } else if (Regs.size() == 1) {
574 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
576 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
578 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
579 // that refactoring is complete (eventually).
580 if (StrOpc == ARM::STR_PRE) {
582 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::sub, 4, ARM_AM::no_shift));
591 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
592 MachineBasicBlock::iterator MI,
593 const std::vector<CalleeSavedInfo> &CSI,
594 unsigned LdmOpc, unsigned LdrOpc,
595 bool isVarArg, bool NoGap,
596 bool(*Func)(unsigned, bool)) const {
597 MachineFunction &MF = *MBB.getParent();
598 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
599 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
600 DebugLoc DL = MI->getDebugLoc();
601 unsigned RetOpcode = MI->getOpcode();
602 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
603 RetOpcode == ARM::TCRETURNdiND ||
604 RetOpcode == ARM::TCRETURNri ||
605 RetOpcode == ARM::TCRETURNriND);
607 SmallVector<unsigned, 4> Regs;
608 unsigned i = CSI.size();
610 unsigned LastReg = 0;
611 bool DeleteRet = false;
612 for (; i != 0; --i) {
613 unsigned Reg = CSI[i-1].getReg();
614 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
616 if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
618 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
619 // Fold the return instruction into the LDM.
623 // If NoGap is true, pop consecutive registers and then leave the rest
624 // for other instructions. e.g.
625 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
626 if (NoGap && LastReg && LastReg != Reg-1)
635 if (Regs.size() > 1 || LdrOpc == 0) {
636 MachineInstrBuilder MIB =
637 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
639 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
640 MIB.addReg(Regs[i], getDefRegState(true));
642 MI->eraseFromParent();
644 } else if (Regs.size() == 1) {
645 // If we adjusted the reg to PC from LR above, switch it back here. We
646 // only do that for LDM.
647 if (Regs[0] == ARM::PC)
649 MachineInstrBuilder MIB =
650 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
651 .addReg(ARM::SP, RegState::Define)
653 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
654 // that refactoring is complete (eventually).
655 if (LdrOpc == ARM::LDR_POST) {
657 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
666 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
667 MachineBasicBlock::iterator MI,
668 const std::vector<CalleeSavedInfo> &CSI,
669 const TargetRegisterInfo *TRI) const {
673 MachineFunction &MF = *MBB.getParent();
674 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
676 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
677 unsigned PushOneOpc = AFI->isThumbFunction() ? ARM::t2STR_PRE : ARM::STR_PRE;
678 unsigned FltOpc = ARM::VSTMDDB_UPD;
679 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register);
680 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register);
681 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register);
686 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
687 MachineBasicBlock::iterator MI,
688 const std::vector<CalleeSavedInfo> &CSI,
689 const TargetRegisterInfo *TRI) const {
693 MachineFunction &MF = *MBB.getParent();
694 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
695 bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
697 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
698 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST;
699 unsigned FltOpc = ARM::VLDMDIA_UPD;
700 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register);
701 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
702 &isARMArea2Register);
703 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
704 &isARMArea1Register);
709 // FIXME: Make generic?
710 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
711 const ARMBaseInstrInfo &TII) {
713 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
715 const MachineBasicBlock &MBB = *MBBI;
716 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
718 FnSize += TII.GetInstSizeInBytes(I);
723 /// estimateStackSize - Estimate and return the size of the frame.
724 /// FIXME: Make generic?
725 static unsigned estimateStackSize(MachineFunction &MF) {
726 const MachineFrameInfo *FFI = MF.getFrameInfo();
728 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
729 int FixedOff = -FFI->getObjectOffset(i);
730 if (FixedOff > Offset) Offset = FixedOff;
732 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
733 if (FFI->isDeadObjectIndex(i))
735 Offset += FFI->getObjectSize(i);
736 unsigned Align = FFI->getObjectAlignment(i);
737 // Adjust to alignment boundary
738 Offset = (Offset+Align-1)/Align*Align;
740 return (unsigned)Offset;
743 /// estimateRSStackSizeLimit - Look at each instruction that references stack
744 /// frames and return the stack size limit beyond which some of these
745 /// instructions will require a scratch register during their expansion later.
746 // FIXME: Move to TII?
747 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
748 const TargetFrameLowering *TFI) {
749 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
750 unsigned Limit = (1 << 12) - 1;
751 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
752 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
754 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
755 if (!I->getOperand(i).isFI()) continue;
757 // When using ADDri to get the address of a stack object, 255 is the
758 // largest offset guaranteed to fit in the immediate offset.
759 if (I->getOpcode() == ARM::ADDri) {
760 Limit = std::min(Limit, (1U << 8) - 1);
764 // Otherwise check the addressing mode.
765 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
766 case ARMII::AddrMode3:
767 case ARMII::AddrModeT2_i8:
768 Limit = std::min(Limit, (1U << 8) - 1);
770 case ARMII::AddrMode5:
771 case ARMII::AddrModeT2_i8s4:
772 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
774 case ARMII::AddrModeT2_i12:
775 // i12 supports only positive offset so these will be converted to
776 // i8 opcodes. See llvm::rewriteT2FrameIndex.
777 if (TFI->hasFP(MF) && AFI->hasStackFrame())
778 Limit = std::min(Limit, (1U << 8) - 1);
780 case ARMII::AddrMode4:
781 case ARMII::AddrMode6:
782 // Addressing modes 4 & 6 (load/store) instructions can't encode an
783 // immediate offset for stack references.
788 break; // At most one FI per instruction
797 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
798 RegScavenger *RS) const {
799 // This tells PEI to spill the FP as if it is any other callee-save register
800 // to take advantage the eliminateFrameIndex machinery. This also ensures it
801 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
802 // to combine multiple loads / stores.
803 bool CanEliminateFrame = true;
804 bool CS1Spilled = false;
805 bool LRSpilled = false;
806 unsigned NumGPRSpills = 0;
807 SmallVector<unsigned, 4> UnspilledCS1GPRs;
808 SmallVector<unsigned, 4> UnspilledCS2GPRs;
809 const ARMBaseRegisterInfo *RegInfo =
810 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
811 const ARMBaseInstrInfo &TII =
812 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
813 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
814 MachineFrameInfo *MFI = MF.getFrameInfo();
815 unsigned FramePtr = RegInfo->getFrameRegister(MF);
817 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
818 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
819 // since it's not always possible to restore sp from fp in a single
821 // FIXME: It will be better just to find spare register here.
822 if (AFI->isThumb2Function() &&
823 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
824 MF.getRegInfo().setPhysRegUsed(ARM::R4);
826 if (AFI->isThumb1OnlyFunction()) {
827 // Spill LR if Thumb1 function uses variable length argument lists.
828 if (AFI->getVarArgsRegSaveSize() > 0)
829 MF.getRegInfo().setPhysRegUsed(ARM::LR);
831 // Spill R4 if Thumb1 epilogue has to restore SP from FP since
832 // FIXME: It will be better just to find spare register here.
833 if (MFI->hasVarSizedObjects())
834 MF.getRegInfo().setPhysRegUsed(ARM::R4);
837 // Spill the BasePtr if it's used.
838 if (RegInfo->hasBasePointer(MF))
839 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
841 // Don't spill FP if the frame can be eliminated. This is determined
842 // by scanning the callee-save registers to see if any is used.
843 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
844 for (unsigned i = 0; CSRegs[i]; ++i) {
845 unsigned Reg = CSRegs[i];
846 bool Spilled = false;
847 if (MF.getRegInfo().isPhysRegUsed(Reg)) {
849 CanEliminateFrame = false;
851 // Check alias registers too.
852 for (const unsigned *Aliases =
853 RegInfo->getAliasSet(Reg); *Aliases; ++Aliases) {
854 if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
856 CanEliminateFrame = false;
861 if (!ARM::GPRRegisterClass->contains(Reg))
867 if (!STI.isTargetDarwin()) {
874 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
879 case ARM::R4: case ARM::R5:
880 case ARM::R6: case ARM::R7:
887 if (!STI.isTargetDarwin()) {
888 UnspilledCS1GPRs.push_back(Reg);
893 case ARM::R4: case ARM::R5:
894 case ARM::R6: case ARM::R7:
896 UnspilledCS1GPRs.push_back(Reg);
899 UnspilledCS2GPRs.push_back(Reg);
905 bool ForceLRSpill = false;
906 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
907 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
908 // Force LR to be spilled if the Thumb function size is > 2048. This enables
909 // use of BL to implement far jump. If it turns out that it's not needed
910 // then the branch fix up path will undo it.
911 if (FnSize >= (1 << 11)) {
912 CanEliminateFrame = false;
917 // If any of the stack slot references may be out of range of an immediate
918 // offset, make sure a register (or a spill slot) is available for the
919 // register scavenger. Note that if we're indexing off the frame pointer, the
920 // effective stack size is 4 bytes larger since the FP points to the stack
921 // slot of the previous FP. Also, if we have variable sized objects in the
922 // function, stack slot references will often be negative, and some of
923 // our instructions are positive-offset only, so conservatively consider
924 // that case to want a spill slot (or register) as well. Similarly, if
925 // the function adjusts the stack pointer during execution and the
926 // adjustments aren't already part of our stack size estimate, our offset
927 // calculations may be off, so be conservative.
928 // FIXME: We could add logic to be more precise about negative offsets
929 // and which instructions will need a scratch register for them. Is it
930 // worth the effort and added fragility?
933 (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
934 estimateRSStackSizeLimit(MF, this)))
935 || MFI->hasVarSizedObjects()
936 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
938 bool ExtraCSSpill = false;
939 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
940 AFI->setHasStackFrame(true);
942 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
943 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
944 if (!LRSpilled && CS1Spilled) {
945 MF.getRegInfo().setPhysRegUsed(ARM::LR);
947 UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
948 UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
949 ForceLRSpill = false;
954 MF.getRegInfo().setPhysRegUsed(FramePtr);
958 // If stack and double are 8-byte aligned and we are spilling an odd number
959 // of GPRs, spill one extra callee save GPR so we won't have to pad between
960 // the integer and double callee save areas.
961 unsigned TargetAlign = getStackAlignment();
962 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
963 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
964 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
965 unsigned Reg = UnspilledCS1GPRs[i];
966 // Don't spill high register if the function is thumb1
967 if (!AFI->isThumb1OnlyFunction() ||
968 isARMLowRegister(Reg) || Reg == ARM::LR) {
969 MF.getRegInfo().setPhysRegUsed(Reg);
970 if (!RegInfo->isReservedReg(MF, Reg))
975 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
976 unsigned Reg = UnspilledCS2GPRs.front();
977 MF.getRegInfo().setPhysRegUsed(Reg);
978 if (!RegInfo->isReservedReg(MF, Reg))
983 // Estimate if we might need to scavenge a register at some point in order
984 // to materialize a stack offset. If so, either spill one additional
985 // callee-saved register or reserve a special spill slot to facilitate
986 // register scavenging. Thumb1 needs a spill slot for stack pointer
987 // adjustments also, even when the frame itself is small.
988 if (BigStack && !ExtraCSSpill) {
989 // If any non-reserved CS register isn't spilled, just spill one or two
990 // extra. That should take care of it!
991 unsigned NumExtras = TargetAlign / 4;
992 SmallVector<unsigned, 2> Extras;
993 while (NumExtras && !UnspilledCS1GPRs.empty()) {
994 unsigned Reg = UnspilledCS1GPRs.back();
995 UnspilledCS1GPRs.pop_back();
996 if (!RegInfo->isReservedReg(MF, Reg) &&
997 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
999 Extras.push_back(Reg);
1003 // For non-Thumb1 functions, also check for hi-reg CS registers
1004 if (!AFI->isThumb1OnlyFunction()) {
1005 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1006 unsigned Reg = UnspilledCS2GPRs.back();
1007 UnspilledCS2GPRs.pop_back();
1008 if (!RegInfo->isReservedReg(MF, Reg)) {
1009 Extras.push_back(Reg);
1014 if (Extras.size() && NumExtras == 0) {
1015 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1016 MF.getRegInfo().setPhysRegUsed(Extras[i]);
1018 } else if (!AFI->isThumb1OnlyFunction()) {
1019 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1020 // closest to SP or frame pointer.
1021 const TargetRegisterClass *RC = ARM::GPRRegisterClass;
1022 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1030 MF.getRegInfo().setPhysRegUsed(ARM::LR);
1031 AFI->setLRIsSpilledForFarJump(true);