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/Function.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Support/CommandLine.h"
31 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
32 cl::desc("Align ARM NEON spills in prolog and epilog"));
34 static MachineBasicBlock::iterator
35 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
36 unsigned NumAlignedDPRCS2Regs);
38 /// hasFP - Return true if the specified function should have a dedicated frame
39 /// pointer register. This is true if the function has variable sized allocas
40 /// or if frame pointer elimination is disabled.
41 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
42 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
44 // iOS requires FP not to be clobbered for backtracing purpose.
45 if (STI.isTargetIOS())
48 const MachineFrameInfo *MFI = MF.getFrameInfo();
49 // Always eliminate non-leaf frame pointers.
50 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
52 RegInfo->needsStackRealignment(MF) ||
53 MFI->hasVarSizedObjects() ||
54 MFI->isFrameAddressTaken());
57 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
58 /// not required, we reserve argument space for call sites in the function
59 /// immediately on entry to the current function. This eliminates the need for
60 /// add/sub sp brackets around call sites. Returns true if the call frame is
61 /// included as part of the stack frame.
62 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
63 const MachineFrameInfo *FFI = MF.getFrameInfo();
64 unsigned CFSize = FFI->getMaxCallFrameSize();
65 // It's not always a good idea to include the call frame as part of the
66 // stack frame. ARM (especially Thumb) has small immediate offset to
67 // address the stack frame. So a large call frame can cause poor codegen
68 // and may even makes it impossible to scavenge a register.
69 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
72 return !MF.getFrameInfo()->hasVarSizedObjects();
75 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
76 /// call frame pseudos can be simplified. Unlike most targets, having a FP
77 /// is not sufficient here since we still may reference some objects via SP
78 /// even when FP is available in Thumb2 mode.
80 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
81 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
84 static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
85 for (unsigned i = 0; CSRegs[i]; ++i)
91 static bool isCSRestore(MachineInstr *MI,
92 const ARMBaseInstrInfo &TII,
93 const uint16_t *CSRegs) {
94 // Integer spill area is handled with "pop".
95 if (MI->getOpcode() == ARM::LDMIA_RET ||
96 MI->getOpcode() == ARM::t2LDMIA_RET ||
97 MI->getOpcode() == ARM::LDMIA_UPD ||
98 MI->getOpcode() == ARM::t2LDMIA_UPD ||
99 MI->getOpcode() == ARM::VLDMDIA_UPD) {
100 // The first two operands are predicates. The last two are
101 // imp-def and imp-use of SP. Check everything in between.
102 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
103 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
107 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
108 MI->getOpcode() == ARM::LDR_POST_REG ||
109 MI->getOpcode() == ARM::t2LDR_POST) &&
110 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
111 MI->getOperand(1).getReg() == ARM::SP)
118 emitSPUpdate(bool isARM,
119 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
120 DebugLoc dl, const ARMBaseInstrInfo &TII,
121 int NumBytes, unsigned MIFlags = MachineInstr::NoFlags) {
123 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
124 ARMCC::AL, 0, TII, MIFlags);
126 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
127 ARMCC::AL, 0, TII, MIFlags);
130 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
131 MachineBasicBlock &MBB = MF.front();
132 MachineBasicBlock::iterator MBBI = MBB.begin();
133 MachineFrameInfo *MFI = MF.getFrameInfo();
134 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
135 const ARMBaseRegisterInfo *RegInfo =
136 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
137 const ARMBaseInstrInfo &TII =
138 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
139 assert(!AFI->isThumb1OnlyFunction() &&
140 "This emitPrologue does not support Thumb1!");
141 bool isARM = !AFI->isThumbFunction();
142 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
143 unsigned NumBytes = MFI->getStackSize();
144 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
145 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
146 unsigned FramePtr = RegInfo->getFrameRegister(MF);
148 // Determine the sizes of each callee-save spill areas and record which frame
149 // belongs to which callee-save spill areas.
150 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
151 int FramePtrSpillFI = 0;
154 // Allocate the vararg register save area. This is not counted in NumBytes.
156 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize,
157 MachineInstr::FrameSetup);
159 if (!AFI->hasStackFrame()) {
161 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
162 MachineInstr::FrameSetup);
166 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
167 unsigned Reg = CSI[i].getReg();
168 int FI = CSI[i].getFrameIdx();
176 FramePtrSpillFI = FI;
177 AFI->addGPRCalleeSavedArea1Frame(FI);
185 FramePtrSpillFI = FI;
186 if (STI.isTargetIOS()) {
187 AFI->addGPRCalleeSavedArea2Frame(FI);
190 AFI->addGPRCalleeSavedArea1Frame(FI);
195 // This is a DPR. Exclude the aligned DPRCS2 spills.
198 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) {
199 AFI->addDPRCalleeSavedAreaFrame(FI);
206 if (GPRCS1Size > 0) MBBI++;
208 // Set FP to point to the stack slot that contains the previous FP.
209 // For iOS, FP is R7, which has now been stored in spill area 1.
210 // Otherwise, if this is not iOS, all the callee-saved registers go
211 // into spill area 1, including the FP in R11. In either case, it is
212 // now safe to emit this assignment.
213 bool HasFP = hasFP(MF);
215 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
216 MachineInstrBuilder MIB =
217 BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
218 .addFrameIndex(FramePtrSpillFI).addImm(0)
219 .setMIFlag(MachineInstr::FrameSetup);
220 AddDefaultCC(AddDefaultPred(MIB));
224 if (GPRCS2Size > 0) MBBI++;
226 // Determine starting offsets of spill areas.
227 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
228 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
229 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
231 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
233 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
234 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
235 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
240 // Since vpush register list cannot have gaps, there may be multiple vpush
241 // instructions in the prologue.
242 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
246 // Move past the aligned DPRCS2 area.
247 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
248 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
249 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
250 // leaves the stack pointer pointing to the DPRCS2 area.
252 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
253 NumBytes += MFI->getObjectOffset(D8SpillFI);
255 NumBytes = DPRCSOffset;
258 // Adjust SP after all the callee-save spills.
259 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
260 MachineInstr::FrameSetup);
262 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
263 // Note it's not safe to do this in Thumb2 mode because it would have
264 // taken two instructions:
267 // If an interrupt is taken between the two instructions, then sp is in
268 // an inconsistent state (pointing to the middle of callee-saved area).
269 // The interrupt handler can end up clobbering the registers.
270 AFI->setShouldRestoreSPFromFP(true);
273 if (STI.isTargetELF() && hasFP(MF))
274 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
275 AFI->getFramePtrSpillOffset());
277 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
278 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
279 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
281 // If we need dynamic stack realignment, do it here. Be paranoid and make
282 // sure if we also have VLAs, we have a base pointer for frame access.
283 // If aligned NEON registers were spilled, the stack has already been
285 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
286 unsigned MaxAlign = MFI->getMaxAlignment();
287 assert (!AFI->isThumb1OnlyFunction());
288 if (!AFI->isThumbFunction()) {
289 // Emit bic sp, sp, MaxAlign
290 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
291 TII.get(ARM::BICri), ARM::SP)
292 .addReg(ARM::SP, RegState::Kill)
293 .addImm(MaxAlign-1)));
295 // We cannot use sp as source/dest register here, thus we're emitting the
296 // following sequence:
298 // bic r4, r4, MaxAlign
300 // FIXME: It will be better just to find spare register here.
301 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
302 .addReg(ARM::SP, RegState::Kill));
303 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
304 TII.get(ARM::t2BICri), ARM::R4)
305 .addReg(ARM::R4, RegState::Kill)
306 .addImm(MaxAlign-1)));
307 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
308 .addReg(ARM::R4, RegState::Kill));
311 AFI->setShouldRestoreSPFromFP(true);
314 // If we need a base pointer, set it up here. It's whatever the value
315 // of the stack pointer is at this point. Any variable size objects
316 // will be allocated after this, so we can still use the base pointer
317 // to reference locals.
318 // FIXME: Clarify FrameSetup flags here.
319 if (RegInfo->hasBasePointer(MF)) {
321 BuildMI(MBB, MBBI, dl,
322 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
324 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
326 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
327 RegInfo->getBaseRegister())
331 // If the frame has variable sized objects then the epilogue must restore
332 // the sp from fp. We can assume there's an FP here since hasFP already
333 // checks for hasVarSizedObjects.
334 if (MFI->hasVarSizedObjects())
335 AFI->setShouldRestoreSPFromFP(true);
338 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
339 MachineBasicBlock &MBB) const {
340 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
341 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
342 unsigned RetOpcode = MBBI->getOpcode();
343 DebugLoc dl = MBBI->getDebugLoc();
344 MachineFrameInfo *MFI = MF.getFrameInfo();
345 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
346 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
347 const ARMBaseInstrInfo &TII =
348 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
349 assert(!AFI->isThumb1OnlyFunction() &&
350 "This emitEpilogue does not support Thumb1!");
351 bool isARM = !AFI->isThumbFunction();
353 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
354 int NumBytes = (int)MFI->getStackSize();
355 unsigned FramePtr = RegInfo->getFrameRegister(MF);
357 if (!AFI->hasStackFrame()) {
359 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
361 // Unwind MBBI to point to first LDR / VLDRD.
362 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
363 if (MBBI != MBB.begin()) {
366 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
367 if (!isCSRestore(MBBI, TII, CSRegs))
371 // Move SP to start of FP callee save spill area.
372 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
373 AFI->getGPRCalleeSavedArea2Size() +
374 AFI->getDPRCalleeSavedAreaSize());
376 // Reset SP based on frame pointer only if the stack frame extends beyond
377 // frame pointer stack slot or target is ELF and the function has FP.
378 if (AFI->shouldRestoreSPFromFP()) {
379 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
382 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
385 // It's not possible to restore SP from FP in a single instruction.
386 // For iOS, this looks like:
389 // This is bad, if an interrupt is taken after the mov, sp is in an
390 // inconsistent state.
391 // Use the first callee-saved register as a scratch register.
392 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
393 "No scratch register to restore SP from FP!");
394 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
396 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
403 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
404 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
406 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
411 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
413 // Increment past our save areas.
414 if (AFI->getDPRCalleeSavedAreaSize()) {
416 // Since vpop register list cannot have gaps, there may be multiple vpop
417 // instructions in the epilogue.
418 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
421 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
422 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
425 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
426 RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
427 // Tail call return: adjust the stack pointer and jump to callee.
428 MBBI = MBB.getLastNonDebugInstr();
429 MachineOperand &JumpTarget = MBBI->getOperand(0);
431 // Jump to label or value in register.
432 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND) {
433 unsigned TCOpcode = (RetOpcode == ARM::TCRETURNdi)
434 ? (STI.isThumb() ? ARM::tTAILJMPd : ARM::TAILJMPd)
435 : (STI.isThumb() ? ARM::tTAILJMPdND : ARM::TAILJMPdND);
436 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
437 if (JumpTarget.isGlobal())
438 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
439 JumpTarget.getTargetFlags());
441 assert(JumpTarget.isSymbol());
442 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
443 JumpTarget.getTargetFlags());
446 // Add the default predicate in Thumb mode.
447 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
448 } else if (RetOpcode == ARM::TCRETURNri) {
449 BuildMI(MBB, MBBI, dl,
450 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
451 addReg(JumpTarget.getReg(), RegState::Kill);
452 } else if (RetOpcode == ARM::TCRETURNriND) {
453 BuildMI(MBB, MBBI, dl,
454 TII.get(STI.isThumb() ? ARM::tTAILJMPrND : ARM::TAILJMPrND)).
455 addReg(JumpTarget.getReg(), RegState::Kill);
458 MachineInstr *NewMI = prior(MBBI);
459 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
460 NewMI->addOperand(MBBI->getOperand(i));
462 // Delete the pseudo instruction TCRETURN.
468 emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
471 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
472 /// debug info. It's the same as what we use for resolving the code-gen
473 /// references for now. FIXME: This can go wrong when references are
474 /// SP-relative and simple call frames aren't used.
476 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
477 unsigned &FrameReg) const {
478 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
482 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
483 int FI, unsigned &FrameReg,
485 const MachineFrameInfo *MFI = MF.getFrameInfo();
486 const ARMBaseRegisterInfo *RegInfo =
487 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
488 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
489 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
490 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
491 bool isFixed = MFI->isFixedObjectIndex(FI);
495 if (AFI->isGPRCalleeSavedArea1Frame(FI))
496 return Offset - AFI->getGPRCalleeSavedArea1Offset();
497 else if (AFI->isGPRCalleeSavedArea2Frame(FI))
498 return Offset - AFI->getGPRCalleeSavedArea2Offset();
499 else if (AFI->isDPRCalleeSavedAreaFrame(FI))
500 return Offset - AFI->getDPRCalleeSavedAreaOffset();
502 // SP can move around if there are allocas. We may also lose track of SP
503 // when emergency spilling inside a non-reserved call frame setup.
504 bool hasMovingSP = MFI->hasVarSizedObjects() || !hasReservedCallFrame(MF);
506 // When dynamically realigning the stack, use the frame pointer for
507 // parameters, and the stack/base pointer for locals.
508 if (RegInfo->needsStackRealignment(MF)) {
509 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
511 FrameReg = RegInfo->getFrameRegister(MF);
513 } else if (hasMovingSP) {
514 assert(RegInfo->hasBasePointer(MF) &&
515 "VLAs and dynamic stack alignment, but missing base pointer!");
516 FrameReg = RegInfo->getBaseRegister();
521 // If there is a frame pointer, use it when we can.
522 if (hasFP(MF) && AFI->hasStackFrame()) {
523 // Use frame pointer to reference fixed objects. Use it for locals if
524 // there are VLAs (and thus the SP isn't reliable as a base).
525 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
526 FrameReg = RegInfo->getFrameRegister(MF);
528 } else if (hasMovingSP) {
529 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
530 if (AFI->isThumb2Function()) {
531 // Try to use the frame pointer if we can, else use the base pointer
532 // since it's available. This is handy for the emergency spill slot, in
534 if (FPOffset >= -255 && FPOffset < 0) {
535 FrameReg = RegInfo->getFrameRegister(MF);
539 } else if (AFI->isThumb2Function()) {
540 // Use add <rd>, sp, #<imm8>
541 // ldr <rd>, [sp, #<imm8>]
542 // if at all possible to save space.
543 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
545 // In Thumb2 mode, the negative offset is very limited. Try to avoid
546 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
547 if (FPOffset >= -255 && FPOffset < 0) {
548 FrameReg = RegInfo->getFrameRegister(MF);
551 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
552 // Otherwise, use SP or FP, whichever is closer to the stack slot.
553 FrameReg = RegInfo->getFrameRegister(MF);
557 // Use the base pointer if we have one.
558 if (RegInfo->hasBasePointer(MF))
559 FrameReg = RegInfo->getBaseRegister();
563 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
566 return getFrameIndexReference(MF, FI, FrameReg);
569 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
570 MachineBasicBlock::iterator MI,
571 const std::vector<CalleeSavedInfo> &CSI,
572 unsigned StmOpc, unsigned StrOpc,
574 bool(*Func)(unsigned, bool),
575 unsigned NumAlignedDPRCS2Regs,
576 unsigned MIFlags) const {
577 MachineFunction &MF = *MBB.getParent();
578 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
581 if (MI != MBB.end()) DL = MI->getDebugLoc();
583 SmallVector<std::pair<unsigned,bool>, 4> Regs;
584 unsigned i = CSI.size();
586 unsigned LastReg = 0;
587 for (; i != 0; --i) {
588 unsigned Reg = CSI[i-1].getReg();
589 if (!(Func)(Reg, STI.isTargetIOS())) continue;
591 // D-registers in the aligned area DPRCS2 are NOT spilled here.
592 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
595 // Add the callee-saved register as live-in unless it's LR and
596 // @llvm.returnaddress is called. If LR is returned for
597 // @llvm.returnaddress then it's already added to the function and
598 // entry block live-in sets.
600 if (Reg == ARM::LR) {
601 if (MF.getFrameInfo()->isReturnAddressTaken() &&
602 MF.getRegInfo().isLiveIn(Reg))
609 // If NoGap is true, push consecutive registers and then leave the rest
610 // for other instructions. e.g.
611 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
612 if (NoGap && LastReg && LastReg != Reg-1)
615 Regs.push_back(std::make_pair(Reg, isKill));
620 if (Regs.size() > 1 || StrOpc== 0) {
621 MachineInstrBuilder MIB =
622 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
623 .addReg(ARM::SP).setMIFlags(MIFlags));
624 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
625 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
626 } else if (Regs.size() == 1) {
627 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
629 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
630 .addReg(ARM::SP).setMIFlags(MIFlags)
638 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
639 MachineBasicBlock::iterator MI,
640 const std::vector<CalleeSavedInfo> &CSI,
641 unsigned LdmOpc, unsigned LdrOpc,
642 bool isVarArg, bool NoGap,
643 bool(*Func)(unsigned, bool),
644 unsigned NumAlignedDPRCS2Regs) const {
645 MachineFunction &MF = *MBB.getParent();
646 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
647 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
648 DebugLoc DL = MI->getDebugLoc();
649 unsigned RetOpcode = MI->getOpcode();
650 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
651 RetOpcode == ARM::TCRETURNdiND ||
652 RetOpcode == ARM::TCRETURNri ||
653 RetOpcode == ARM::TCRETURNriND);
655 SmallVector<unsigned, 4> Regs;
656 unsigned i = CSI.size();
658 unsigned LastReg = 0;
659 bool DeleteRet = false;
660 for (; i != 0; --i) {
661 unsigned Reg = CSI[i-1].getReg();
662 if (!(Func)(Reg, STI.isTargetIOS())) continue;
664 // The aligned reloads from area DPRCS2 are not inserted here.
665 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
668 if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
670 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
671 // Fold the return instruction into the LDM.
675 // If NoGap is true, pop consecutive registers and then leave the rest
676 // for other instructions. e.g.
677 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
678 if (NoGap && LastReg && LastReg != Reg-1)
687 if (Regs.size() > 1 || LdrOpc == 0) {
688 MachineInstrBuilder MIB =
689 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
691 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
692 MIB.addReg(Regs[i], getDefRegState(true));
694 MIB->copyImplicitOps(&*MI);
695 MI->eraseFromParent();
698 } else if (Regs.size() == 1) {
699 // If we adjusted the reg to PC from LR above, switch it back here. We
700 // only do that for LDM.
701 if (Regs[0] == ARM::PC)
703 MachineInstrBuilder MIB =
704 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
705 .addReg(ARM::SP, RegState::Define)
707 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
708 // that refactoring is complete (eventually).
709 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
711 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
720 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
721 /// starting from d8. Also insert stack realignment code and leave the stack
722 /// pointer pointing to the d8 spill slot.
723 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
724 MachineBasicBlock::iterator MI,
725 unsigned NumAlignedDPRCS2Regs,
726 const std::vector<CalleeSavedInfo> &CSI,
727 const TargetRegisterInfo *TRI) {
728 MachineFunction &MF = *MBB.getParent();
729 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
730 DebugLoc DL = MI->getDebugLoc();
731 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
732 MachineFrameInfo &MFI = *MF.getFrameInfo();
734 // Mark the D-register spill slots as properly aligned. Since MFI computes
735 // stack slot layout backwards, this can actually mean that the d-reg stack
736 // slot offsets can be wrong. The offset for d8 will always be correct.
737 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
738 unsigned DNum = CSI[i].getReg() - ARM::D8;
741 int FI = CSI[i].getFrameIdx();
742 // The even-numbered registers will be 16-byte aligned, the odd-numbered
743 // registers will be 8-byte aligned.
744 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
746 // The stack slot for D8 needs to be maximally aligned because this is
747 // actually the point where we align the stack pointer. MachineFrameInfo
748 // computes all offsets relative to the incoming stack pointer which is a
749 // bit weird when realigning the stack. Any extra padding for this
750 // over-alignment is not realized because the code inserted below adjusts
751 // the stack pointer by numregs * 8 before aligning the stack pointer.
753 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
756 // Move the stack pointer to the d8 spill slot, and align it at the same
757 // time. Leave the stack slot address in the scratch register r4.
759 // sub r4, sp, #numregs * 8
760 // bic r4, r4, #align - 1
763 bool isThumb = AFI->isThumbFunction();
764 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
765 AFI->setShouldRestoreSPFromFP(true);
767 // sub r4, sp, #numregs * 8
768 // The immediate is <= 64, so it doesn't need any special encoding.
769 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
770 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
772 .addImm(8 * NumAlignedDPRCS2Regs)));
774 // bic r4, r4, #align-1
775 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
776 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
777 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
778 .addReg(ARM::R4, RegState::Kill)
779 .addImm(MaxAlign - 1)));
782 // The stack pointer must be adjusted before spilling anything, otherwise
783 // the stack slots could be clobbered by an interrupt handler.
784 // Leave r4 live, it is used below.
785 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
786 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
788 MIB = AddDefaultPred(MIB);
792 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
793 // r4 holds the stack slot address.
794 unsigned NextReg = ARM::D8;
796 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
797 // The writeback is only needed when emitting two vst1.64 instructions.
798 if (NumAlignedDPRCS2Regs >= 6) {
799 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
800 ARM::QQPRRegisterClass);
801 MBB.addLiveIn(SupReg);
802 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
804 .addReg(ARM::R4, RegState::Kill).addImm(16)
806 .addReg(SupReg, RegState::ImplicitKill));
808 NumAlignedDPRCS2Regs -= 4;
811 // We won't modify r4 beyond this point. It currently points to the next
812 // register to be spilled.
813 unsigned R4BaseReg = NextReg;
815 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
816 if (NumAlignedDPRCS2Regs >= 4) {
817 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
818 ARM::QQPRRegisterClass);
819 MBB.addLiveIn(SupReg);
820 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
821 .addReg(ARM::R4).addImm(16).addReg(NextReg)
822 .addReg(SupReg, RegState::ImplicitKill));
824 NumAlignedDPRCS2Regs -= 4;
827 // 16-byte aligned vst1.64 with 2 d-regs.
828 if (NumAlignedDPRCS2Regs >= 2) {
829 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
830 ARM::QPRRegisterClass);
831 MBB.addLiveIn(SupReg);
832 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
833 .addReg(ARM::R4).addImm(16).addReg(NextReg)
834 .addReg(SupReg, RegState::ImplicitKill));
836 NumAlignedDPRCS2Regs -= 2;
839 // Finally, use a vanilla vstr.64 for the odd last register.
840 if (NumAlignedDPRCS2Regs) {
841 MBB.addLiveIn(NextReg);
842 // vstr.64 uses addrmode5 which has an offset scale of 4.
843 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
845 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
848 // The last spill instruction inserted should kill the scratch register r4.
849 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
852 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
853 /// iterator to the following instruction.
854 static MachineBasicBlock::iterator
855 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
856 unsigned NumAlignedDPRCS2Regs) {
857 // sub r4, sp, #numregs * 8
858 // bic r4, r4, #align - 1
861 assert(MI->mayStore() && "Expecting spill instruction");
863 // These switches all fall through.
864 switch(NumAlignedDPRCS2Regs) {
867 assert(MI->mayStore() && "Expecting spill instruction");
870 assert(MI->mayStore() && "Expecting spill instruction");
874 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
880 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
881 /// starting from d8. These instructions are assumed to execute while the
882 /// stack is still aligned, unlike the code inserted by emitPopInst.
883 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
884 MachineBasicBlock::iterator MI,
885 unsigned NumAlignedDPRCS2Regs,
886 const std::vector<CalleeSavedInfo> &CSI,
887 const TargetRegisterInfo *TRI) {
888 MachineFunction &MF = *MBB.getParent();
889 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
890 DebugLoc DL = MI->getDebugLoc();
891 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
893 // Find the frame index assigned to d8.
895 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
896 if (CSI[i].getReg() == ARM::D8) {
897 D8SpillFI = CSI[i].getFrameIdx();
901 // Materialize the address of the d8 spill slot into the scratch register r4.
902 // This can be fairly complicated if the stack frame is large, so just use
903 // the normal frame index elimination mechanism to do it. This code runs as
904 // the initial part of the epilog where the stack and base pointers haven't
906 bool isThumb = AFI->isThumbFunction();
907 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
909 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
910 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
911 .addFrameIndex(D8SpillFI).addImm(0)));
913 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
914 unsigned NextReg = ARM::D8;
916 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
917 if (NumAlignedDPRCS2Regs >= 6) {
918 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
919 ARM::QQPRRegisterClass);
920 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
921 .addReg(ARM::R4, RegState::Define)
922 .addReg(ARM::R4, RegState::Kill).addImm(16)
923 .addReg(SupReg, RegState::ImplicitDefine));
925 NumAlignedDPRCS2Regs -= 4;
928 // We won't modify r4 beyond this point. It currently points to the next
929 // register to be spilled.
930 unsigned R4BaseReg = NextReg;
932 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
933 if (NumAlignedDPRCS2Regs >= 4) {
934 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
935 ARM::QQPRRegisterClass);
936 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
937 .addReg(ARM::R4).addImm(16)
938 .addReg(SupReg, RegState::ImplicitDefine));
940 NumAlignedDPRCS2Regs -= 4;
943 // 16-byte aligned vld1.64 with 2 d-regs.
944 if (NumAlignedDPRCS2Regs >= 2) {
945 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
946 ARM::QPRRegisterClass);
947 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), NextReg)
948 .addReg(ARM::R4).addImm(16)
949 .addReg(SupReg, RegState::ImplicitDefine));
951 NumAlignedDPRCS2Regs -= 2;
954 // Finally, use a vanilla vldr.64 for the remaining odd register.
955 if (NumAlignedDPRCS2Regs)
956 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
957 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
959 // Last store kills r4.
960 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
963 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
964 MachineBasicBlock::iterator MI,
965 const std::vector<CalleeSavedInfo> &CSI,
966 const TargetRegisterInfo *TRI) const {
970 MachineFunction &MF = *MBB.getParent();
971 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
973 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
974 unsigned PushOneOpc = AFI->isThumbFunction() ?
975 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
976 unsigned FltOpc = ARM::VSTMDDB_UPD;
977 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
978 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
979 MachineInstr::FrameSetup);
980 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
981 MachineInstr::FrameSetup);
982 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
983 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
985 // The code above does not insert spill code for the aligned DPRCS2 registers.
986 // The stack realignment code will be inserted between the push instructions
988 if (NumAlignedDPRCS2Regs)
989 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
994 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
995 MachineBasicBlock::iterator MI,
996 const std::vector<CalleeSavedInfo> &CSI,
997 const TargetRegisterInfo *TRI) const {
1001 MachineFunction &MF = *MBB.getParent();
1002 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1003 bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
1004 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1006 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1007 // registers. Do that here instead.
1008 if (NumAlignedDPRCS2Regs)
1009 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1011 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1012 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1013 unsigned FltOpc = ARM::VLDMDIA_UPD;
1014 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1015 NumAlignedDPRCS2Regs);
1016 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1017 &isARMArea2Register, 0);
1018 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1019 &isARMArea1Register, 0);
1024 // FIXME: Make generic?
1025 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1026 const ARMBaseInstrInfo &TII) {
1027 unsigned FnSize = 0;
1028 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
1029 MBBI != E; ++MBBI) {
1030 const MachineBasicBlock &MBB = *MBBI;
1031 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
1033 FnSize += TII.GetInstSizeInBytes(I);
1038 /// estimateStackSize - Estimate and return the size of the frame.
1039 /// FIXME: Make generic?
1040 static unsigned estimateStackSize(MachineFunction &MF) {
1041 const MachineFrameInfo *MFI = MF.getFrameInfo();
1042 const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
1043 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
1044 unsigned MaxAlign = MFI->getMaxAlignment();
1047 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
1048 // It really should be refactored to share code. Until then, changes
1049 // should keep in mind that there's tight coupling between the two.
1051 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
1052 int FixedOff = -MFI->getObjectOffset(i);
1053 if (FixedOff > Offset) Offset = FixedOff;
1055 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1056 if (MFI->isDeadObjectIndex(i))
1058 Offset += MFI->getObjectSize(i);
1059 unsigned Align = MFI->getObjectAlignment(i);
1060 // Adjust to alignment boundary
1061 Offset = (Offset+Align-1)/Align*Align;
1063 MaxAlign = std::max(Align, MaxAlign);
1066 if (MFI->adjustsStack() && TFI->hasReservedCallFrame(MF))
1067 Offset += MFI->getMaxCallFrameSize();
1069 // Round up the size to a multiple of the alignment. If the function has
1070 // any calls or alloca's, align to the target's StackAlignment value to
1071 // ensure that the callee's frame or the alloca data is suitably aligned;
1072 // otherwise, for leaf functions, align to the TransientStackAlignment
1074 unsigned StackAlign;
1075 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
1076 (RegInfo->needsStackRealignment(MF) && MFI->getObjectIndexEnd() != 0))
1077 StackAlign = TFI->getStackAlignment();
1079 StackAlign = TFI->getTransientStackAlignment();
1081 // If the frame pointer is eliminated, all frame offsets will be relative to
1082 // SP not FP. Align to MaxAlign so this works.
1083 StackAlign = std::max(StackAlign, MaxAlign);
1084 unsigned AlignMask = StackAlign - 1;
1085 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
1087 return (unsigned)Offset;
1090 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1091 /// frames and return the stack size limit beyond which some of these
1092 /// instructions will require a scratch register during their expansion later.
1093 // FIXME: Move to TII?
1094 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1095 const TargetFrameLowering *TFI) {
1096 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1097 unsigned Limit = (1 << 12) - 1;
1098 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
1099 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1101 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1102 if (!I->getOperand(i).isFI()) continue;
1104 // When using ADDri to get the address of a stack object, 255 is the
1105 // largest offset guaranteed to fit in the immediate offset.
1106 if (I->getOpcode() == ARM::ADDri) {
1107 Limit = std::min(Limit, (1U << 8) - 1);
1111 // Otherwise check the addressing mode.
1112 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
1113 case ARMII::AddrMode3:
1114 case ARMII::AddrModeT2_i8:
1115 Limit = std::min(Limit, (1U << 8) - 1);
1117 case ARMII::AddrMode5:
1118 case ARMII::AddrModeT2_i8s4:
1119 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1121 case ARMII::AddrModeT2_i12:
1122 // i12 supports only positive offset so these will be converted to
1123 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1124 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1125 Limit = std::min(Limit, (1U << 8) - 1);
1127 case ARMII::AddrMode4:
1128 case ARMII::AddrMode6:
1129 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1130 // immediate offset for stack references.
1135 break; // At most one FI per instruction
1143 // In functions that realign the stack, it can be an advantage to spill the
1144 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1145 // instructions take alignment hints that can improve performance.
1147 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1148 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1149 if (!SpillAlignedNEONRegs)
1152 // Naked functions don't spill callee-saved registers.
1153 if (MF.getFunction()->hasFnAttr(Attribute::Naked))
1156 // We are planning to use NEON instructions vst1 / vld1.
1157 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1160 // Don't bother if the default stack alignment is sufficiently high.
1161 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1164 // Aligned spills require stack realignment.
1165 const ARMBaseRegisterInfo *RegInfo =
1166 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1167 if (!RegInfo->canRealignStack(MF))
1170 // We always spill contiguous d-registers starting from d8. Count how many
1171 // needs spilling. The register allocator will almost always use the
1172 // callee-saved registers in order, but it can happen that there are holes in
1173 // the range. Registers above the hole will be spilled to the standard DPRCS
1175 MachineRegisterInfo &MRI = MF.getRegInfo();
1176 unsigned NumSpills = 0;
1177 for (; NumSpills < 8; ++NumSpills)
1178 if (!MRI.isPhysRegOrOverlapUsed(ARM::D8 + NumSpills))
1181 // Don't do this for just one d-register. It's not worth it.
1185 // Spill the first NumSpills D-registers after realigning the stack.
1186 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1188 // A scratch register is required for the vst1 / vld1 instructions.
1189 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1193 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1194 RegScavenger *RS) const {
1195 // This tells PEI to spill the FP as if it is any other callee-save register
1196 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1197 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1198 // to combine multiple loads / stores.
1199 bool CanEliminateFrame = true;
1200 bool CS1Spilled = false;
1201 bool LRSpilled = false;
1202 unsigned NumGPRSpills = 0;
1203 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1204 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1205 const ARMBaseRegisterInfo *RegInfo =
1206 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1207 const ARMBaseInstrInfo &TII =
1208 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1209 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1210 MachineFrameInfo *MFI = MF.getFrameInfo();
1211 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1213 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1214 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1215 // since it's not always possible to restore sp from fp in a single
1217 // FIXME: It will be better just to find spare register here.
1218 if (AFI->isThumb2Function() &&
1219 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1220 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1222 if (AFI->isThumb1OnlyFunction()) {
1223 // Spill LR if Thumb1 function uses variable length argument lists.
1224 if (AFI->getVarArgsRegSaveSize() > 0)
1225 MF.getRegInfo().setPhysRegUsed(ARM::LR);
1227 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1228 // for sure what the stack size will be, but for this, an estimate is good
1229 // enough. If there anything changes it, it'll be a spill, which implies
1230 // we've used all the registers and so R4 is already used, so not marking
1231 // it here will be OK.
1232 // FIXME: It will be better just to find spare register here.
1233 unsigned StackSize = estimateStackSize(MF);
1234 if (MFI->hasVarSizedObjects() || StackSize > 508)
1235 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1238 // See if we can spill vector registers to aligned stack.
1239 checkNumAlignedDPRCS2Regs(MF);
1241 // Spill the BasePtr if it's used.
1242 if (RegInfo->hasBasePointer(MF))
1243 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1245 // Don't spill FP if the frame can be eliminated. This is determined
1246 // by scanning the callee-save registers to see if any is used.
1247 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
1248 for (unsigned i = 0; CSRegs[i]; ++i) {
1249 unsigned Reg = CSRegs[i];
1250 bool Spilled = false;
1251 if (MF.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
1253 CanEliminateFrame = false;
1256 if (!ARM::GPRRegisterClass->contains(Reg))
1262 if (!STI.isTargetIOS()) {
1269 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1274 case ARM::R4: case ARM::R5:
1275 case ARM::R6: case ARM::R7:
1282 if (!STI.isTargetIOS()) {
1283 UnspilledCS1GPRs.push_back(Reg);
1288 case ARM::R4: case ARM::R5:
1289 case ARM::R6: case ARM::R7:
1291 UnspilledCS1GPRs.push_back(Reg);
1294 UnspilledCS2GPRs.push_back(Reg);
1300 bool ForceLRSpill = false;
1301 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1302 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1303 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1304 // use of BL to implement far jump. If it turns out that it's not needed
1305 // then the branch fix up path will undo it.
1306 if (FnSize >= (1 << 11)) {
1307 CanEliminateFrame = false;
1308 ForceLRSpill = true;
1312 // If any of the stack slot references may be out of range of an immediate
1313 // offset, make sure a register (or a spill slot) is available for the
1314 // register scavenger. Note that if we're indexing off the frame pointer, the
1315 // effective stack size is 4 bytes larger since the FP points to the stack
1316 // slot of the previous FP. Also, if we have variable sized objects in the
1317 // function, stack slot references will often be negative, and some of
1318 // our instructions are positive-offset only, so conservatively consider
1319 // that case to want a spill slot (or register) as well. Similarly, if
1320 // the function adjusts the stack pointer during execution and the
1321 // adjustments aren't already part of our stack size estimate, our offset
1322 // calculations may be off, so be conservative.
1323 // FIXME: We could add logic to be more precise about negative offsets
1324 // and which instructions will need a scratch register for them. Is it
1325 // worth the effort and added fragility?
1328 (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1329 estimateRSStackSizeLimit(MF, this)))
1330 || MFI->hasVarSizedObjects()
1331 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1333 bool ExtraCSSpill = false;
1334 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1335 AFI->setHasStackFrame(true);
1337 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1338 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1339 if (!LRSpilled && CS1Spilled) {
1340 MF.getRegInfo().setPhysRegUsed(ARM::LR);
1342 UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
1343 UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1344 ForceLRSpill = false;
1345 ExtraCSSpill = true;
1349 MF.getRegInfo().setPhysRegUsed(FramePtr);
1353 // If stack and double are 8-byte aligned and we are spilling an odd number
1354 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1355 // the integer and double callee save areas.
1356 unsigned TargetAlign = getStackAlignment();
1357 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1358 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1359 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1360 unsigned Reg = UnspilledCS1GPRs[i];
1361 // Don't spill high register if the function is thumb1
1362 if (!AFI->isThumb1OnlyFunction() ||
1363 isARMLowRegister(Reg) || Reg == ARM::LR) {
1364 MF.getRegInfo().setPhysRegUsed(Reg);
1365 if (!RegInfo->isReservedReg(MF, Reg))
1366 ExtraCSSpill = true;
1370 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1371 unsigned Reg = UnspilledCS2GPRs.front();
1372 MF.getRegInfo().setPhysRegUsed(Reg);
1373 if (!RegInfo->isReservedReg(MF, Reg))
1374 ExtraCSSpill = true;
1378 // Estimate if we might need to scavenge a register at some point in order
1379 // to materialize a stack offset. If so, either spill one additional
1380 // callee-saved register or reserve a special spill slot to facilitate
1381 // register scavenging. Thumb1 needs a spill slot for stack pointer
1382 // adjustments also, even when the frame itself is small.
1383 if (BigStack && !ExtraCSSpill) {
1384 // If any non-reserved CS register isn't spilled, just spill one or two
1385 // extra. That should take care of it!
1386 unsigned NumExtras = TargetAlign / 4;
1387 SmallVector<unsigned, 2> Extras;
1388 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1389 unsigned Reg = UnspilledCS1GPRs.back();
1390 UnspilledCS1GPRs.pop_back();
1391 if (!RegInfo->isReservedReg(MF, Reg) &&
1392 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1394 Extras.push_back(Reg);
1398 // For non-Thumb1 functions, also check for hi-reg CS registers
1399 if (!AFI->isThumb1OnlyFunction()) {
1400 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1401 unsigned Reg = UnspilledCS2GPRs.back();
1402 UnspilledCS2GPRs.pop_back();
1403 if (!RegInfo->isReservedReg(MF, Reg)) {
1404 Extras.push_back(Reg);
1409 if (Extras.size() && NumExtras == 0) {
1410 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1411 MF.getRegInfo().setPhysRegUsed(Extras[i]);
1413 } else if (!AFI->isThumb1OnlyFunction()) {
1414 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1415 // closest to SP or frame pointer.
1416 const TargetRegisterClass *RC = ARM::GPRRegisterClass;
1417 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1425 MF.getRegInfo().setPhysRegUsed(ARM::LR);
1426 AFI->setLRIsSpilledForFarJump(true);