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 "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/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_IMM ||
97 MI->getOpcode() == ARM::LDR_POST_REG ||
98 MI->getOpcode() == ARM::t2LDR_POST) &&
99 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
100 MI->getOperand(1).getReg() == ARM::SP)
107 emitSPUpdate(bool isARM,
108 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
109 DebugLoc dl, const ARMBaseInstrInfo &TII,
110 int NumBytes, unsigned MIFlags = MachineInstr::NoFlags) {
112 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
113 ARMCC::AL, 0, TII, MIFlags);
115 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
116 ARMCC::AL, 0, TII, MIFlags);
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,
145 MachineInstr::FrameSetup);
147 if (!AFI->hasStackFrame()) {
149 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
150 MachineInstr::FrameSetup);
154 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
155 unsigned Reg = CSI[i].getReg();
156 int FI = CSI[i].getFrameIdx();
164 FramePtrSpillFI = FI;
165 AFI->addGPRCalleeSavedArea1Frame(FI);
173 FramePtrSpillFI = FI;
174 if (STI.isTargetDarwin()) {
175 AFI->addGPRCalleeSavedArea2Frame(FI);
178 AFI->addGPRCalleeSavedArea1Frame(FI);
183 AFI->addDPRCalleeSavedAreaFrame(FI);
189 if (GPRCS1Size > 0) MBBI++;
191 // Set FP to point to the stack slot that contains the previous FP.
192 // For Darwin, FP is R7, which has now been stored in spill area 1.
193 // Otherwise, if this is not Darwin, all the callee-saved registers go
194 // into spill area 1, including the FP in R11. In either case, it is
195 // now safe to emit this assignment.
196 bool HasFP = hasFP(MF);
198 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
199 MachineInstrBuilder MIB =
200 BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
201 .addFrameIndex(FramePtrSpillFI).addImm(0)
202 .setMIFlag(MachineInstr::FrameSetup);
203 AddDefaultCC(AddDefaultPred(MIB));
207 if (GPRCS2Size > 0) MBBI++;
209 // Determine starting offsets of spill areas.
210 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
211 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
212 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
214 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
216 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
217 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
218 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
223 // Since vpush register list cannot have gaps, there may be multiple vpush
224 // instructions in the prologue.
225 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
229 NumBytes = DPRCSOffset;
231 // Adjust SP after all the callee-save spills.
232 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
233 MachineInstr::FrameSetup);
235 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
236 // Note it's not safe to do this in Thumb2 mode because it would have
237 // taken two instructions:
240 // If an interrupt is taken between the two instructions, then sp is in
241 // an inconsistent state (pointing to the middle of callee-saved area).
242 // The interrupt handler can end up clobbering the registers.
243 AFI->setShouldRestoreSPFromFP(true);
246 if (STI.isTargetELF() && hasFP(MF))
247 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
248 AFI->getFramePtrSpillOffset());
250 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
251 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
252 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
254 // If we need dynamic stack realignment, do it here. Be paranoid and make
255 // sure if we also have VLAs, we have a base pointer for frame access.
256 if (RegInfo->needsStackRealignment(MF)) {
257 unsigned MaxAlign = MFI->getMaxAlignment();
258 assert (!AFI->isThumb1OnlyFunction());
259 if (!AFI->isThumbFunction()) {
260 // Emit bic sp, sp, MaxAlign
261 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
262 TII.get(ARM::BICri), ARM::SP)
263 .addReg(ARM::SP, RegState::Kill)
264 .addImm(MaxAlign-1)));
266 // We cannot use sp as source/dest register here, thus we're emitting the
267 // following sequence:
269 // bic r4, r4, MaxAlign
271 // FIXME: It will be better just to find spare register here.
272 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
273 .addReg(ARM::SP, RegState::Kill));
274 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
275 TII.get(ARM::t2BICri), ARM::R4)
276 .addReg(ARM::R4, RegState::Kill)
277 .addImm(MaxAlign-1)));
278 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
279 .addReg(ARM::R4, RegState::Kill));
282 AFI->setShouldRestoreSPFromFP(true);
285 // If we need a base pointer, set it up here. It's whatever the value
286 // of the stack pointer is at this point. Any variable size objects
287 // will be allocated after this, so we can still use the base pointer
288 // to reference locals.
289 // FIXME: Clarify FrameSetup flags here.
290 if (RegInfo->hasBasePointer(MF)) {
292 BuildMI(MBB, MBBI, dl,
293 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
295 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
297 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
298 RegInfo->getBaseRegister())
302 // If the frame has variable sized objects then the epilogue must restore
303 // the sp from fp. We can assume there's an FP here since hasFP already
304 // checks for hasVarSizedObjects.
305 if (MFI->hasVarSizedObjects())
306 AFI->setShouldRestoreSPFromFP(true);
309 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
310 MachineBasicBlock &MBB) const {
311 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
312 assert(MBBI->getDesc().isReturn() &&
313 "Can only insert epilog into returning blocks");
314 unsigned RetOpcode = MBBI->getOpcode();
315 DebugLoc dl = MBBI->getDebugLoc();
316 MachineFrameInfo *MFI = MF.getFrameInfo();
317 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
318 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
319 const ARMBaseInstrInfo &TII =
320 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
321 assert(!AFI->isThumb1OnlyFunction() &&
322 "This emitEpilogue does not support Thumb1!");
323 bool isARM = !AFI->isThumbFunction();
325 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
326 int NumBytes = (int)MFI->getStackSize();
327 unsigned FramePtr = RegInfo->getFrameRegister(MF);
329 if (!AFI->hasStackFrame()) {
331 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
333 // Unwind MBBI to point to first LDR / VLDRD.
334 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
335 if (MBBI != MBB.begin()) {
338 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
339 if (!isCSRestore(MBBI, TII, CSRegs))
343 // Move SP to start of FP callee save spill area.
344 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
345 AFI->getGPRCalleeSavedArea2Size() +
346 AFI->getDPRCalleeSavedAreaSize());
348 // Reset SP based on frame pointer only if the stack frame extends beyond
349 // frame pointer stack slot or target is ELF and the function has FP.
350 if (AFI->shouldRestoreSPFromFP()) {
351 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
354 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
357 // It's not possible to restore SP from FP in a single instruction.
358 // For Darwin, this looks like:
361 // This is bad, if an interrupt is taken after the mov, sp is in an
362 // inconsistent state.
363 // Use the first callee-saved register as a scratch register.
364 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
365 "No scratch register to restore SP from FP!");
366 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
368 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
375 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
376 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
378 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
383 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
385 // Increment past our save areas.
386 if (AFI->getDPRCalleeSavedAreaSize()) {
388 // Since vpop register list cannot have gaps, there may be multiple vpop
389 // instructions in the epilogue.
390 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
393 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
394 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
397 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
398 RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
399 // Tail call return: adjust the stack pointer and jump to callee.
400 MBBI = MBB.getLastNonDebugInstr();
401 MachineOperand &JumpTarget = MBBI->getOperand(0);
403 // Jump to label or value in register.
404 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND) {
405 unsigned TCOpcode = (RetOpcode == ARM::TCRETURNdi)
406 ? (STI.isThumb() ? ARM::tTAILJMPd : ARM::TAILJMPd)
407 : (STI.isThumb() ? ARM::tTAILJMPdND : ARM::TAILJMPdND);
408 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
409 if (JumpTarget.isGlobal())
410 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
411 JumpTarget.getTargetFlags());
413 assert(JumpTarget.isSymbol());
414 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
415 JumpTarget.getTargetFlags());
417 } else if (RetOpcode == ARM::TCRETURNri) {
418 BuildMI(MBB, MBBI, dl,
419 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
420 addReg(JumpTarget.getReg(), RegState::Kill);
421 } else if (RetOpcode == ARM::TCRETURNriND) {
422 BuildMI(MBB, MBBI, dl,
423 TII.get(STI.isThumb() ? ARM::tTAILJMPrND : ARM::TAILJMPrND)).
424 addReg(JumpTarget.getReg(), RegState::Kill);
427 MachineInstr *NewMI = prior(MBBI);
428 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
429 NewMI->addOperand(MBBI->getOperand(i));
431 // Delete the pseudo instruction TCRETURN.
437 emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
440 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
441 /// debug info. It's the same as what we use for resolving the code-gen
442 /// references for now. FIXME: This can go wrong when references are
443 /// SP-relative and simple call frames aren't used.
445 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
446 unsigned &FrameReg) const {
447 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
451 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
452 int FI, unsigned &FrameReg,
454 const MachineFrameInfo *MFI = MF.getFrameInfo();
455 const ARMBaseRegisterInfo *RegInfo =
456 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
457 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
458 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
459 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
460 bool isFixed = MFI->isFixedObjectIndex(FI);
464 if (AFI->isGPRCalleeSavedArea1Frame(FI))
465 return Offset - AFI->getGPRCalleeSavedArea1Offset();
466 else if (AFI->isGPRCalleeSavedArea2Frame(FI))
467 return Offset - AFI->getGPRCalleeSavedArea2Offset();
468 else if (AFI->isDPRCalleeSavedAreaFrame(FI))
469 return Offset - AFI->getDPRCalleeSavedAreaOffset();
471 // When dynamically realigning the stack, use the frame pointer for
472 // parameters, and the stack/base pointer for locals.
473 if (RegInfo->needsStackRealignment(MF)) {
474 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
476 FrameReg = RegInfo->getFrameRegister(MF);
478 } else if (MFI->hasVarSizedObjects()) {
479 assert(RegInfo->hasBasePointer(MF) &&
480 "VLAs and dynamic stack alignment, but missing base pointer!");
481 FrameReg = RegInfo->getBaseRegister();
486 // If there is a frame pointer, use it when we can.
487 if (hasFP(MF) && AFI->hasStackFrame()) {
488 // Use frame pointer to reference fixed objects. Use it for locals if
489 // there are VLAs (and thus the SP isn't reliable as a base).
490 if (isFixed || (MFI->hasVarSizedObjects() &&
491 !RegInfo->hasBasePointer(MF))) {
492 FrameReg = RegInfo->getFrameRegister(MF);
494 } else if (MFI->hasVarSizedObjects()) {
495 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
496 if (AFI->isThumb2Function()) {
497 // Try to use the frame pointer if we can, else use the base pointer
498 // since it's available. This is handy for the emergency spill slot, in
500 if (FPOffset >= -255 && FPOffset < 0) {
501 FrameReg = RegInfo->getFrameRegister(MF);
505 } else if (AFI->isThumb2Function()) {
506 // Use add <rd>, sp, #<imm8>
507 // ldr <rd>, [sp, #<imm8>]
508 // if at all possible to save space.
509 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
511 // In Thumb2 mode, the negative offset is very limited. Try to avoid
512 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
513 if (FPOffset >= -255 && FPOffset < 0) {
514 FrameReg = RegInfo->getFrameRegister(MF);
517 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
518 // Otherwise, use SP or FP, whichever is closer to the stack slot.
519 FrameReg = RegInfo->getFrameRegister(MF);
523 // Use the base pointer if we have one.
524 if (RegInfo->hasBasePointer(MF))
525 FrameReg = RegInfo->getBaseRegister();
529 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
532 return getFrameIndexReference(MF, FI, FrameReg);
535 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
536 MachineBasicBlock::iterator MI,
537 const std::vector<CalleeSavedInfo> &CSI,
538 unsigned StmOpc, unsigned StrOpc,
540 bool(*Func)(unsigned, bool),
541 unsigned MIFlags) const {
542 MachineFunction &MF = *MBB.getParent();
543 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
546 if (MI != MBB.end()) DL = MI->getDebugLoc();
548 SmallVector<std::pair<unsigned,bool>, 4> Regs;
549 unsigned i = CSI.size();
551 unsigned LastReg = 0;
552 for (; i != 0; --i) {
553 unsigned Reg = CSI[i-1].getReg();
554 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
556 // Add the callee-saved register as live-in unless it's LR and
557 // @llvm.returnaddress is called. If LR is returned for
558 // @llvm.returnaddress then it's already added to the function and
559 // entry block live-in sets.
561 if (Reg == ARM::LR) {
562 if (MF.getFrameInfo()->isReturnAddressTaken() &&
563 MF.getRegInfo().isLiveIn(Reg))
570 // If NoGap is true, push consecutive registers and then leave the rest
571 // for other instructions. e.g.
572 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
573 if (NoGap && LastReg && LastReg != Reg-1)
576 Regs.push_back(std::make_pair(Reg, isKill));
581 if (Regs.size() > 1 || StrOpc== 0) {
582 MachineInstrBuilder MIB =
583 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
584 .addReg(ARM::SP).setMIFlags(MIFlags));
585 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
586 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
587 } else if (Regs.size() == 1) {
588 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
590 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
591 .addReg(ARM::SP).setMIFlags(MIFlags)
599 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
600 MachineBasicBlock::iterator MI,
601 const std::vector<CalleeSavedInfo> &CSI,
602 unsigned LdmOpc, unsigned LdrOpc,
603 bool isVarArg, bool NoGap,
604 bool(*Func)(unsigned, bool)) const {
605 MachineFunction &MF = *MBB.getParent();
606 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
607 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
608 DebugLoc DL = MI->getDebugLoc();
609 unsigned RetOpcode = MI->getOpcode();
610 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
611 RetOpcode == ARM::TCRETURNdiND ||
612 RetOpcode == ARM::TCRETURNri ||
613 RetOpcode == ARM::TCRETURNriND);
615 SmallVector<unsigned, 4> Regs;
616 unsigned i = CSI.size();
618 unsigned LastReg = 0;
619 bool DeleteRet = false;
620 for (; i != 0; --i) {
621 unsigned Reg = CSI[i-1].getReg();
622 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
624 if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
626 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
627 // Fold the return instruction into the LDM.
631 // If NoGap is true, pop consecutive registers and then leave the rest
632 // for other instructions. e.g.
633 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
634 if (NoGap && LastReg && LastReg != Reg-1)
643 if (Regs.size() > 1 || LdrOpc == 0) {
644 MachineInstrBuilder MIB =
645 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
647 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
648 MIB.addReg(Regs[i], getDefRegState(true));
650 MIB->copyImplicitOps(&*MI);
651 MI->eraseFromParent();
654 } else if (Regs.size() == 1) {
655 // If we adjusted the reg to PC from LR above, switch it back here. We
656 // only do that for LDM.
657 if (Regs[0] == ARM::PC)
659 MachineInstrBuilder MIB =
660 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
661 .addReg(ARM::SP, RegState::Define)
663 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
664 // that refactoring is complete (eventually).
665 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
667 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
676 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
677 MachineBasicBlock::iterator MI,
678 const std::vector<CalleeSavedInfo> &CSI,
679 const TargetRegisterInfo *TRI) const {
683 MachineFunction &MF = *MBB.getParent();
684 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
686 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
687 unsigned PushOneOpc = AFI->isThumbFunction() ?
688 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
689 unsigned FltOpc = ARM::VSTMDDB_UPD;
690 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register,
691 MachineInstr::FrameSetup);
692 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register,
693 MachineInstr::FrameSetup);
694 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
695 MachineInstr::FrameSetup);
700 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
701 MachineBasicBlock::iterator MI,
702 const std::vector<CalleeSavedInfo> &CSI,
703 const TargetRegisterInfo *TRI) const {
707 MachineFunction &MF = *MBB.getParent();
708 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
709 bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
711 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
712 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
713 unsigned FltOpc = ARM::VLDMDIA_UPD;
714 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register);
715 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
716 &isARMArea2Register);
717 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
718 &isARMArea1Register);
723 // FIXME: Make generic?
724 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
725 const ARMBaseInstrInfo &TII) {
727 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
729 const MachineBasicBlock &MBB = *MBBI;
730 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
732 FnSize += TII.GetInstSizeInBytes(I);
737 /// estimateStackSize - Estimate and return the size of the frame.
738 /// FIXME: Make generic?
739 static unsigned estimateStackSize(MachineFunction &MF) {
740 const MachineFrameInfo *MFI = MF.getFrameInfo();
741 const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
742 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
743 unsigned MaxAlign = MFI->getMaxAlignment();
746 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
747 // It really should be refactored to share code. Until then, changes
748 // should keep in mind that there's tight coupling between the two.
750 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
751 int FixedOff = -MFI->getObjectOffset(i);
752 if (FixedOff > Offset) Offset = FixedOff;
754 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
755 if (MFI->isDeadObjectIndex(i))
757 Offset += MFI->getObjectSize(i);
758 unsigned Align = MFI->getObjectAlignment(i);
759 // Adjust to alignment boundary
760 Offset = (Offset+Align-1)/Align*Align;
762 MaxAlign = std::max(Align, MaxAlign);
765 if (MFI->adjustsStack() && TFI->hasReservedCallFrame(MF))
766 Offset += MFI->getMaxCallFrameSize();
768 // Round up the size to a multiple of the alignment. If the function has
769 // any calls or alloca's, align to the target's StackAlignment value to
770 // ensure that the callee's frame or the alloca data is suitably aligned;
771 // otherwise, for leaf functions, align to the TransientStackAlignment
774 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
775 (RegInfo->needsStackRealignment(MF) && MFI->getObjectIndexEnd() != 0))
776 StackAlign = TFI->getStackAlignment();
778 StackAlign = TFI->getTransientStackAlignment();
780 // If the frame pointer is eliminated, all frame offsets will be relative to
781 // SP not FP. Align to MaxAlign so this works.
782 StackAlign = std::max(StackAlign, MaxAlign);
783 unsigned AlignMask = StackAlign - 1;
784 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
786 return (unsigned)Offset;
789 /// estimateRSStackSizeLimit - Look at each instruction that references stack
790 /// frames and return the stack size limit beyond which some of these
791 /// instructions will require a scratch register during their expansion later.
792 // FIXME: Move to TII?
793 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
794 const TargetFrameLowering *TFI) {
795 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
796 unsigned Limit = (1 << 12) - 1;
797 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
798 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
800 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
801 if (!I->getOperand(i).isFI()) continue;
803 // When using ADDri to get the address of a stack object, 255 is the
804 // largest offset guaranteed to fit in the immediate offset.
805 if (I->getOpcode() == ARM::ADDri) {
806 Limit = std::min(Limit, (1U << 8) - 1);
810 // Otherwise check the addressing mode.
811 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
812 case ARMII::AddrMode3:
813 case ARMII::AddrModeT2_i8:
814 Limit = std::min(Limit, (1U << 8) - 1);
816 case ARMII::AddrMode5:
817 case ARMII::AddrModeT2_i8s4:
818 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
820 case ARMII::AddrModeT2_i12:
821 // i12 supports only positive offset so these will be converted to
822 // i8 opcodes. See llvm::rewriteT2FrameIndex.
823 if (TFI->hasFP(MF) && AFI->hasStackFrame())
824 Limit = std::min(Limit, (1U << 8) - 1);
826 case ARMII::AddrMode4:
827 case ARMII::AddrMode6:
828 // Addressing modes 4 & 6 (load/store) instructions can't encode an
829 // immediate offset for stack references.
834 break; // At most one FI per instruction
843 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
844 RegScavenger *RS) const {
845 // This tells PEI to spill the FP as if it is any other callee-save register
846 // to take advantage the eliminateFrameIndex machinery. This also ensures it
847 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
848 // to combine multiple loads / stores.
849 bool CanEliminateFrame = true;
850 bool CS1Spilled = false;
851 bool LRSpilled = false;
852 unsigned NumGPRSpills = 0;
853 SmallVector<unsigned, 4> UnspilledCS1GPRs;
854 SmallVector<unsigned, 4> UnspilledCS2GPRs;
855 const ARMBaseRegisterInfo *RegInfo =
856 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
857 const ARMBaseInstrInfo &TII =
858 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
859 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
860 MachineFrameInfo *MFI = MF.getFrameInfo();
861 unsigned FramePtr = RegInfo->getFrameRegister(MF);
863 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
864 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
865 // since it's not always possible to restore sp from fp in a single
867 // FIXME: It will be better just to find spare register here.
868 if (AFI->isThumb2Function() &&
869 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
870 MF.getRegInfo().setPhysRegUsed(ARM::R4);
872 if (AFI->isThumb1OnlyFunction()) {
873 // Spill LR if Thumb1 function uses variable length argument lists.
874 if (AFI->getVarArgsRegSaveSize() > 0)
875 MF.getRegInfo().setPhysRegUsed(ARM::LR);
877 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
878 // for sure what the stack size will be, but for this, an estimate is good
879 // enough. If there anything changes it, it'll be a spill, which implies
880 // we've used all the registers and so R4 is already used, so not marking
881 // it here will be OK.
882 // FIXME: It will be better just to find spare register here.
883 unsigned StackSize = estimateStackSize(MF);
884 if (MFI->hasVarSizedObjects() || StackSize > 508)
885 MF.getRegInfo().setPhysRegUsed(ARM::R4);
888 // Spill the BasePtr if it's used.
889 if (RegInfo->hasBasePointer(MF))
890 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
892 // Don't spill FP if the frame can be eliminated. This is determined
893 // by scanning the callee-save registers to see if any is used.
894 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
895 for (unsigned i = 0; CSRegs[i]; ++i) {
896 unsigned Reg = CSRegs[i];
897 bool Spilled = false;
898 if (MF.getRegInfo().isPhysRegUsed(Reg)) {
900 CanEliminateFrame = false;
902 // Check alias registers too.
903 for (const unsigned *Aliases =
904 RegInfo->getAliasSet(Reg); *Aliases; ++Aliases) {
905 if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
907 CanEliminateFrame = false;
912 if (!ARM::GPRRegisterClass->contains(Reg))
918 if (!STI.isTargetDarwin()) {
925 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
930 case ARM::R4: case ARM::R5:
931 case ARM::R6: case ARM::R7:
938 if (!STI.isTargetDarwin()) {
939 UnspilledCS1GPRs.push_back(Reg);
944 case ARM::R4: case ARM::R5:
945 case ARM::R6: case ARM::R7:
947 UnspilledCS1GPRs.push_back(Reg);
950 UnspilledCS2GPRs.push_back(Reg);
956 bool ForceLRSpill = false;
957 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
958 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
959 // Force LR to be spilled if the Thumb function size is > 2048. This enables
960 // use of BL to implement far jump. If it turns out that it's not needed
961 // then the branch fix up path will undo it.
962 if (FnSize >= (1 << 11)) {
963 CanEliminateFrame = false;
968 // If any of the stack slot references may be out of range of an immediate
969 // offset, make sure a register (or a spill slot) is available for the
970 // register scavenger. Note that if we're indexing off the frame pointer, the
971 // effective stack size is 4 bytes larger since the FP points to the stack
972 // slot of the previous FP. Also, if we have variable sized objects in the
973 // function, stack slot references will often be negative, and some of
974 // our instructions are positive-offset only, so conservatively consider
975 // that case to want a spill slot (or register) as well. Similarly, if
976 // the function adjusts the stack pointer during execution and the
977 // adjustments aren't already part of our stack size estimate, our offset
978 // calculations may be off, so be conservative.
979 // FIXME: We could add logic to be more precise about negative offsets
980 // and which instructions will need a scratch register for them. Is it
981 // worth the effort and added fragility?
984 (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
985 estimateRSStackSizeLimit(MF, this)))
986 || MFI->hasVarSizedObjects()
987 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
989 bool ExtraCSSpill = false;
990 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
991 AFI->setHasStackFrame(true);
993 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
994 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
995 if (!LRSpilled && CS1Spilled) {
996 MF.getRegInfo().setPhysRegUsed(ARM::LR);
998 UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
999 UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1000 ForceLRSpill = false;
1001 ExtraCSSpill = true;
1005 MF.getRegInfo().setPhysRegUsed(FramePtr);
1009 // If stack and double are 8-byte aligned and we are spilling an odd number
1010 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1011 // the integer and double callee save areas.
1012 unsigned TargetAlign = getStackAlignment();
1013 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1014 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1015 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1016 unsigned Reg = UnspilledCS1GPRs[i];
1017 // Don't spill high register if the function is thumb1
1018 if (!AFI->isThumb1OnlyFunction() ||
1019 isARMLowRegister(Reg) || Reg == ARM::LR) {
1020 MF.getRegInfo().setPhysRegUsed(Reg);
1021 if (!RegInfo->isReservedReg(MF, Reg))
1022 ExtraCSSpill = true;
1026 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1027 unsigned Reg = UnspilledCS2GPRs.front();
1028 MF.getRegInfo().setPhysRegUsed(Reg);
1029 if (!RegInfo->isReservedReg(MF, Reg))
1030 ExtraCSSpill = true;
1034 // Estimate if we might need to scavenge a register at some point in order
1035 // to materialize a stack offset. If so, either spill one additional
1036 // callee-saved register or reserve a special spill slot to facilitate
1037 // register scavenging. Thumb1 needs a spill slot for stack pointer
1038 // adjustments also, even when the frame itself is small.
1039 if (BigStack && !ExtraCSSpill) {
1040 // If any non-reserved CS register isn't spilled, just spill one or two
1041 // extra. That should take care of it!
1042 unsigned NumExtras = TargetAlign / 4;
1043 SmallVector<unsigned, 2> Extras;
1044 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1045 unsigned Reg = UnspilledCS1GPRs.back();
1046 UnspilledCS1GPRs.pop_back();
1047 if (!RegInfo->isReservedReg(MF, Reg) &&
1048 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1050 Extras.push_back(Reg);
1054 // For non-Thumb1 functions, also check for hi-reg CS registers
1055 if (!AFI->isThumb1OnlyFunction()) {
1056 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1057 unsigned Reg = UnspilledCS2GPRs.back();
1058 UnspilledCS2GPRs.pop_back();
1059 if (!RegInfo->isReservedReg(MF, Reg)) {
1060 Extras.push_back(Reg);
1065 if (Extras.size() && NumExtras == 0) {
1066 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1067 MF.getRegInfo().setPhysRegUsed(Extras[i]);
1069 } else if (!AFI->isThumb1OnlyFunction()) {
1070 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1071 // closest to SP or frame pointer.
1072 const TargetRegisterClass *RC = ARM::GPRRegisterClass;
1073 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1081 MF.getRegInfo().setPhysRegUsed(ARM::LR);
1082 AFI->setLRIsSpilledForFarJump(true);