1dff0c46cSDimitry Andric //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
22754fe60SDimitry Andric //
32754fe60SDimitry Andric //                     The LLVM Compiler Infrastructure
42754fe60SDimitry Andric //
52754fe60SDimitry Andric // This file is distributed under the University of Illinois Open Source
62754fe60SDimitry Andric // License. See LICENSE.TXT for details.
72754fe60SDimitry Andric //
82754fe60SDimitry Andric //===----------------------------------------------------------------------===//
92754fe60SDimitry Andric //
102754fe60SDimitry Andric // This file contains the ARM implementation of TargetFrameLowering class.
112754fe60SDimitry Andric //
122754fe60SDimitry Andric //===----------------------------------------------------------------------===//
132754fe60SDimitry Andric 
142754fe60SDimitry Andric #include "ARMFrameLowering.h"
152754fe60SDimitry Andric #include "ARMBaseInstrInfo.h"
162754fe60SDimitry Andric #include "ARMBaseRegisterInfo.h"
172754fe60SDimitry Andric #include "ARMMachineFunctionInfo.h"
186122f3e6SDimitry Andric #include "MCTargetDesc/ARMAddressingModes.h"
19dff0c46cSDimitry Andric #include "llvm/Function.h"
202754fe60SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
212754fe60SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
222754fe60SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
232754fe60SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
242754fe60SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h"
252754fe60SDimitry Andric #include "llvm/Target/TargetOptions.h"
26dff0c46cSDimitry Andric #include "llvm/Support/CommandLine.h"
272754fe60SDimitry Andric 
282754fe60SDimitry Andric using namespace llvm;
292754fe60SDimitry Andric 
30dff0c46cSDimitry Andric static cl::opt<bool>
31dff0c46cSDimitry Andric SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
32dff0c46cSDimitry Andric                      cl::desc("Align ARM NEON spills in prolog and epilog"));
33dff0c46cSDimitry Andric 
34dff0c46cSDimitry Andric static MachineBasicBlock::iterator
35dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
36dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs);
37dff0c46cSDimitry Andric 
382754fe60SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame
392754fe60SDimitry Andric /// pointer register.  This is true if the function has variable sized allocas
402754fe60SDimitry Andric /// or if frame pointer elimination is disabled.
412754fe60SDimitry Andric bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
422754fe60SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
432754fe60SDimitry Andric 
44dff0c46cSDimitry Andric   // iOS requires FP not to be clobbered for backtracing purpose.
45dff0c46cSDimitry Andric   if (STI.isTargetIOS())
462754fe60SDimitry Andric     return true;
472754fe60SDimitry Andric 
482754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
492754fe60SDimitry Andric   // Always eliminate non-leaf frame pointers.
50dff0c46cSDimitry Andric   return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
51dff0c46cSDimitry Andric            MFI->hasCalls()) ||
522754fe60SDimitry Andric           RegInfo->needsStackRealignment(MF) ||
532754fe60SDimitry Andric           MFI->hasVarSizedObjects() ||
542754fe60SDimitry Andric           MFI->isFrameAddressTaken());
552754fe60SDimitry Andric }
562754fe60SDimitry Andric 
572754fe60SDimitry Andric /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
582754fe60SDimitry Andric /// not required, we reserve argument space for call sites in the function
592754fe60SDimitry Andric /// immediately on entry to the current function.  This eliminates the need for
602754fe60SDimitry Andric /// add/sub sp brackets around call sites.  Returns true if the call frame is
612754fe60SDimitry Andric /// included as part of the stack frame.
622754fe60SDimitry Andric bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
632754fe60SDimitry Andric   const MachineFrameInfo *FFI = MF.getFrameInfo();
642754fe60SDimitry Andric   unsigned CFSize = FFI->getMaxCallFrameSize();
652754fe60SDimitry Andric   // It's not always a good idea to include the call frame as part of the
662754fe60SDimitry Andric   // stack frame. ARM (especially Thumb) has small immediate offset to
672754fe60SDimitry Andric   // address the stack frame. So a large call frame can cause poor codegen
682754fe60SDimitry Andric   // and may even makes it impossible to scavenge a register.
692754fe60SDimitry Andric   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
702754fe60SDimitry Andric     return false;
712754fe60SDimitry Andric 
722754fe60SDimitry Andric   return !MF.getFrameInfo()->hasVarSizedObjects();
732754fe60SDimitry Andric }
742754fe60SDimitry Andric 
752754fe60SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
762754fe60SDimitry Andric /// call frame pseudos can be simplified.  Unlike most targets, having a FP
772754fe60SDimitry Andric /// is not sufficient here since we still may reference some objects via SP
782754fe60SDimitry Andric /// even when FP is available in Thumb2 mode.
792754fe60SDimitry Andric bool
802754fe60SDimitry Andric ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
812754fe60SDimitry Andric   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
822754fe60SDimitry Andric }
832754fe60SDimitry Andric 
84dff0c46cSDimitry Andric static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
852754fe60SDimitry Andric   for (unsigned i = 0; CSRegs[i]; ++i)
862754fe60SDimitry Andric     if (Reg == CSRegs[i])
872754fe60SDimitry Andric       return true;
882754fe60SDimitry Andric   return false;
892754fe60SDimitry Andric }
902754fe60SDimitry Andric 
912754fe60SDimitry Andric static bool isCSRestore(MachineInstr *MI,
922754fe60SDimitry Andric                         const ARMBaseInstrInfo &TII,
93dff0c46cSDimitry Andric                         const uint16_t *CSRegs) {
942754fe60SDimitry Andric   // Integer spill area is handled with "pop".
952754fe60SDimitry Andric   if (MI->getOpcode() == ARM::LDMIA_RET ||
962754fe60SDimitry Andric       MI->getOpcode() == ARM::t2LDMIA_RET ||
972754fe60SDimitry Andric       MI->getOpcode() == ARM::LDMIA_UPD ||
982754fe60SDimitry Andric       MI->getOpcode() == ARM::t2LDMIA_UPD ||
992754fe60SDimitry Andric       MI->getOpcode() == ARM::VLDMDIA_UPD) {
1002754fe60SDimitry Andric     // The first two operands are predicates. The last two are
1012754fe60SDimitry Andric     // imp-def and imp-use of SP. Check everything in between.
1022754fe60SDimitry Andric     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
1032754fe60SDimitry Andric       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
1042754fe60SDimitry Andric         return false;
1052754fe60SDimitry Andric     return true;
1062754fe60SDimitry Andric   }
1076122f3e6SDimitry Andric   if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
1086122f3e6SDimitry Andric        MI->getOpcode() == ARM::LDR_POST_REG ||
1092754fe60SDimitry Andric        MI->getOpcode() == ARM::t2LDR_POST) &&
1102754fe60SDimitry Andric       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
1112754fe60SDimitry Andric       MI->getOperand(1).getReg() == ARM::SP)
1122754fe60SDimitry Andric     return true;
1132754fe60SDimitry Andric 
1142754fe60SDimitry Andric   return false;
1152754fe60SDimitry Andric }
1162754fe60SDimitry Andric 
1172754fe60SDimitry Andric static void
1182754fe60SDimitry Andric emitSPUpdate(bool isARM,
1192754fe60SDimitry Andric              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
1202754fe60SDimitry Andric              DebugLoc dl, const ARMBaseInstrInfo &TII,
1213b0f4066SDimitry Andric              int NumBytes, unsigned MIFlags = MachineInstr::NoFlags) {
1222754fe60SDimitry Andric   if (isARM)
1232754fe60SDimitry Andric     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1243b0f4066SDimitry Andric                             ARMCC::AL, 0, TII, MIFlags);
1252754fe60SDimitry Andric   else
1262754fe60SDimitry Andric     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1273b0f4066SDimitry Andric                            ARMCC::AL, 0, TII, MIFlags);
1282754fe60SDimitry Andric }
1292754fe60SDimitry Andric 
1302754fe60SDimitry Andric void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
1312754fe60SDimitry Andric   MachineBasicBlock &MBB = MF.front();
1322754fe60SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
1332754fe60SDimitry Andric   MachineFrameInfo  *MFI = MF.getFrameInfo();
1342754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1352754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
1362754fe60SDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1372754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
1382754fe60SDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1392754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
1402754fe60SDimitry Andric          "This emitPrologue does not support Thumb1!");
1412754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
1422754fe60SDimitry Andric   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1432754fe60SDimitry Andric   unsigned NumBytes = MFI->getStackSize();
1442754fe60SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1452754fe60SDimitry Andric   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1462754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1472754fe60SDimitry Andric 
1482754fe60SDimitry Andric   // Determine the sizes of each callee-save spill areas and record which frame
1492754fe60SDimitry Andric   // belongs to which callee-save spill areas.
1502754fe60SDimitry Andric   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1512754fe60SDimitry Andric   int FramePtrSpillFI = 0;
152dff0c46cSDimitry Andric   int D8SpillFI = 0;
153f8254f43SDimitry Andric 
1542754fe60SDimitry Andric   // Allocate the vararg register save area. This is not counted in NumBytes.
1552754fe60SDimitry Andric   if (VARegSaveSize)
1563b0f4066SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize,
1573b0f4066SDimitry Andric                  MachineInstr::FrameSetup);
1582754fe60SDimitry Andric 
1592754fe60SDimitry Andric   if (!AFI->hasStackFrame()) {
1602754fe60SDimitry Andric     if (NumBytes != 0)
1613b0f4066SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
1623b0f4066SDimitry Andric                    MachineInstr::FrameSetup);
1632754fe60SDimitry Andric     return;
1642754fe60SDimitry Andric   }
1652754fe60SDimitry Andric 
1662754fe60SDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1672754fe60SDimitry Andric     unsigned Reg = CSI[i].getReg();
1682754fe60SDimitry Andric     int FI = CSI[i].getFrameIdx();
1692754fe60SDimitry Andric     switch (Reg) {
1702754fe60SDimitry Andric     case ARM::R4:
1712754fe60SDimitry Andric     case ARM::R5:
1722754fe60SDimitry Andric     case ARM::R6:
1732754fe60SDimitry Andric     case ARM::R7:
1742754fe60SDimitry Andric     case ARM::LR:
1752754fe60SDimitry Andric       if (Reg == FramePtr)
1762754fe60SDimitry Andric         FramePtrSpillFI = FI;
1772754fe60SDimitry Andric       AFI->addGPRCalleeSavedArea1Frame(FI);
1782754fe60SDimitry Andric       GPRCS1Size += 4;
1792754fe60SDimitry Andric       break;
1802754fe60SDimitry Andric     case ARM::R8:
1812754fe60SDimitry Andric     case ARM::R9:
1822754fe60SDimitry Andric     case ARM::R10:
1832754fe60SDimitry Andric     case ARM::R11:
1842754fe60SDimitry Andric       if (Reg == FramePtr)
1852754fe60SDimitry Andric         FramePtrSpillFI = FI;
186dff0c46cSDimitry Andric       if (STI.isTargetIOS()) {
1872754fe60SDimitry Andric         AFI->addGPRCalleeSavedArea2Frame(FI);
1882754fe60SDimitry Andric         GPRCS2Size += 4;
1892754fe60SDimitry Andric       } else {
1902754fe60SDimitry Andric         AFI->addGPRCalleeSavedArea1Frame(FI);
1912754fe60SDimitry Andric         GPRCS1Size += 4;
1922754fe60SDimitry Andric       }
1932754fe60SDimitry Andric       break;
1942754fe60SDimitry Andric     default:
195dff0c46cSDimitry Andric       // This is a DPR. Exclude the aligned DPRCS2 spills.
196dff0c46cSDimitry Andric       if (Reg == ARM::D8)
197dff0c46cSDimitry Andric         D8SpillFI = FI;
198dff0c46cSDimitry Andric       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) {
1992754fe60SDimitry Andric         AFI->addDPRCalleeSavedAreaFrame(FI);
2002754fe60SDimitry Andric         DPRCSSize += 8;
2012754fe60SDimitry Andric       }
2022754fe60SDimitry Andric     }
203dff0c46cSDimitry Andric   }
2042754fe60SDimitry Andric 
2052754fe60SDimitry Andric   // Move past area 1.
2062754fe60SDimitry Andric   if (GPRCS1Size > 0) MBBI++;
2072754fe60SDimitry Andric 
2082754fe60SDimitry Andric   // Set FP to point to the stack slot that contains the previous FP.
209dff0c46cSDimitry Andric   // For iOS, FP is R7, which has now been stored in spill area 1.
210dff0c46cSDimitry Andric   // Otherwise, if this is not iOS, all the callee-saved registers go
2112754fe60SDimitry Andric   // into spill area 1, including the FP in R11.  In either case, it is
2122754fe60SDimitry Andric   // now safe to emit this assignment.
2132754fe60SDimitry Andric   bool HasFP = hasFP(MF);
2142754fe60SDimitry Andric   if (HasFP) {
2152754fe60SDimitry Andric     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
2162754fe60SDimitry Andric     MachineInstrBuilder MIB =
2172754fe60SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
2183b0f4066SDimitry Andric       .addFrameIndex(FramePtrSpillFI).addImm(0)
2193b0f4066SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
2202754fe60SDimitry Andric     AddDefaultCC(AddDefaultPred(MIB));
2212754fe60SDimitry Andric   }
2222754fe60SDimitry Andric 
2232754fe60SDimitry Andric   // Move past area 2.
2242754fe60SDimitry Andric   if (GPRCS2Size > 0) MBBI++;
2252754fe60SDimitry Andric 
2262754fe60SDimitry Andric   // Determine starting offsets of spill areas.
2272754fe60SDimitry Andric   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
2282754fe60SDimitry Andric   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
2292754fe60SDimitry Andric   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
2302754fe60SDimitry Andric   if (HasFP)
2312754fe60SDimitry Andric     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
2322754fe60SDimitry Andric                                 NumBytes);
2332754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
2342754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
2352754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
2362754fe60SDimitry Andric 
2372754fe60SDimitry Andric   // Move past area 3.
238dd6029ffSDimitry Andric   if (DPRCSSize > 0) {
239dd6029ffSDimitry Andric     MBBI++;
240dd6029ffSDimitry Andric     // Since vpush register list cannot have gaps, there may be multiple vpush
241dd6029ffSDimitry Andric     // instructions in the prologue.
242dd6029ffSDimitry Andric     while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
243dd6029ffSDimitry Andric       MBBI++;
244dd6029ffSDimitry Andric   }
2452754fe60SDimitry Andric 
246dff0c46cSDimitry Andric   // Move past the aligned DPRCS2 area.
247dff0c46cSDimitry Andric   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
248dff0c46cSDimitry Andric     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
249dff0c46cSDimitry Andric     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
250dff0c46cSDimitry Andric     // leaves the stack pointer pointing to the DPRCS2 area.
251dff0c46cSDimitry Andric     //
252dff0c46cSDimitry Andric     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
253dff0c46cSDimitry Andric     NumBytes += MFI->getObjectOffset(D8SpillFI);
254dff0c46cSDimitry Andric   } else
2552754fe60SDimitry Andric     NumBytes = DPRCSOffset;
256dff0c46cSDimitry Andric 
2572754fe60SDimitry Andric   if (NumBytes) {
2582754fe60SDimitry Andric     // Adjust SP after all the callee-save spills.
2593b0f4066SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
2603b0f4066SDimitry Andric                  MachineInstr::FrameSetup);
2612754fe60SDimitry Andric     if (HasFP && isARM)
2622754fe60SDimitry Andric       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
2632754fe60SDimitry Andric       // Note it's not safe to do this in Thumb2 mode because it would have
2642754fe60SDimitry Andric       // taken two instructions:
2652754fe60SDimitry Andric       // mov sp, r7
2662754fe60SDimitry Andric       // sub sp, #24
2672754fe60SDimitry Andric       // If an interrupt is taken between the two instructions, then sp is in
2682754fe60SDimitry Andric       // an inconsistent state (pointing to the middle of callee-saved area).
2692754fe60SDimitry Andric       // The interrupt handler can end up clobbering the registers.
2702754fe60SDimitry Andric       AFI->setShouldRestoreSPFromFP(true);
2712754fe60SDimitry Andric   }
2722754fe60SDimitry Andric 
2732754fe60SDimitry Andric   if (STI.isTargetELF() && hasFP(MF))
2742754fe60SDimitry Andric     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
2752754fe60SDimitry Andric                              AFI->getFramePtrSpillOffset());
2762754fe60SDimitry Andric 
2772754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
2782754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
2792754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
2802754fe60SDimitry Andric 
2812754fe60SDimitry Andric   // If we need dynamic stack realignment, do it here. Be paranoid and make
2822754fe60SDimitry Andric   // sure if we also have VLAs, we have a base pointer for frame access.
283dff0c46cSDimitry Andric   // If aligned NEON registers were spilled, the stack has already been
284dff0c46cSDimitry Andric   // realigned.
285dff0c46cSDimitry Andric   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
2862754fe60SDimitry Andric     unsigned MaxAlign = MFI->getMaxAlignment();
2872754fe60SDimitry Andric     assert (!AFI->isThumb1OnlyFunction());
2882754fe60SDimitry Andric     if (!AFI->isThumbFunction()) {
2892754fe60SDimitry Andric       // Emit bic sp, sp, MaxAlign
2902754fe60SDimitry Andric       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
2912754fe60SDimitry Andric                                           TII.get(ARM::BICri), ARM::SP)
2922754fe60SDimitry Andric                                   .addReg(ARM::SP, RegState::Kill)
2932754fe60SDimitry Andric                                   .addImm(MaxAlign-1)));
2942754fe60SDimitry Andric     } else {
2952754fe60SDimitry Andric       // We cannot use sp as source/dest register here, thus we're emitting the
2962754fe60SDimitry Andric       // following sequence:
2972754fe60SDimitry Andric       // mov r4, sp
2982754fe60SDimitry Andric       // bic r4, r4, MaxAlign
2992754fe60SDimitry Andric       // mov sp, r4
3002754fe60SDimitry Andric       // FIXME: It will be better just to find spare register here.
30117a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
30217a519f9SDimitry Andric         .addReg(ARM::SP, RegState::Kill));
3032754fe60SDimitry Andric       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
3042754fe60SDimitry Andric                                           TII.get(ARM::t2BICri), ARM::R4)
3052754fe60SDimitry Andric                                   .addReg(ARM::R4, RegState::Kill)
3062754fe60SDimitry Andric                                   .addImm(MaxAlign-1)));
30717a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
30817a519f9SDimitry Andric         .addReg(ARM::R4, RegState::Kill));
3092754fe60SDimitry Andric     }
3102754fe60SDimitry Andric 
3112754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
3122754fe60SDimitry Andric   }
3132754fe60SDimitry Andric 
3142754fe60SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
3152754fe60SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
3162754fe60SDimitry Andric   // will be allocated after this, so we can still use the base pointer
3172754fe60SDimitry Andric   // to reference locals.
3183b0f4066SDimitry Andric   // FIXME: Clarify FrameSetup flags here.
3192754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF)) {
3202754fe60SDimitry Andric     if (isARM)
3212754fe60SDimitry Andric       BuildMI(MBB, MBBI, dl,
3222754fe60SDimitry Andric               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
3232754fe60SDimitry Andric         .addReg(ARM::SP)
3242754fe60SDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
3252754fe60SDimitry Andric     else
32617a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
32717a519f9SDimitry Andric                              RegInfo->getBaseRegister())
32817a519f9SDimitry Andric         .addReg(ARM::SP));
3292754fe60SDimitry Andric   }
3302754fe60SDimitry Andric 
3312754fe60SDimitry Andric   // If the frame has variable sized objects then the epilogue must restore
3322754fe60SDimitry Andric   // the sp from fp. We can assume there's an FP here since hasFP already
3332754fe60SDimitry Andric   // checks for hasVarSizedObjects.
3342754fe60SDimitry Andric   if (MFI->hasVarSizedObjects())
3352754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
3362754fe60SDimitry Andric }
3372754fe60SDimitry Andric 
3382754fe60SDimitry Andric void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
3392754fe60SDimitry Andric                                     MachineBasicBlock &MBB) const {
3402754fe60SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
341dff0c46cSDimitry Andric   assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
3422754fe60SDimitry Andric   unsigned RetOpcode = MBBI->getOpcode();
3432754fe60SDimitry Andric   DebugLoc dl = MBBI->getDebugLoc();
3442754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
3452754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3462754fe60SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
3472754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
3482754fe60SDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
3492754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
3502754fe60SDimitry Andric          "This emitEpilogue does not support Thumb1!");
3512754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
3522754fe60SDimitry Andric 
3532754fe60SDimitry Andric   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
3542754fe60SDimitry Andric   int NumBytes = (int)MFI->getStackSize();
3552754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
3562754fe60SDimitry Andric 
3572754fe60SDimitry Andric   if (!AFI->hasStackFrame()) {
3582754fe60SDimitry Andric     if (NumBytes != 0)
3592754fe60SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
3602754fe60SDimitry Andric   } else {
3612754fe60SDimitry Andric     // Unwind MBBI to point to first LDR / VLDRD.
362dff0c46cSDimitry Andric     const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
3632754fe60SDimitry Andric     if (MBBI != MBB.begin()) {
3642754fe60SDimitry Andric       do
3652754fe60SDimitry Andric         --MBBI;
3662754fe60SDimitry Andric       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
3672754fe60SDimitry Andric       if (!isCSRestore(MBBI, TII, CSRegs))
3682754fe60SDimitry Andric         ++MBBI;
3692754fe60SDimitry Andric     }
3702754fe60SDimitry Andric 
3712754fe60SDimitry Andric     // Move SP to start of FP callee save spill area.
3722754fe60SDimitry Andric     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
3732754fe60SDimitry Andric                  AFI->getGPRCalleeSavedArea2Size() +
3742754fe60SDimitry Andric                  AFI->getDPRCalleeSavedAreaSize());
3752754fe60SDimitry Andric 
3762754fe60SDimitry Andric     // Reset SP based on frame pointer only if the stack frame extends beyond
3772754fe60SDimitry Andric     // frame pointer stack slot or target is ELF and the function has FP.
3782754fe60SDimitry Andric     if (AFI->shouldRestoreSPFromFP()) {
3792754fe60SDimitry Andric       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
3802754fe60SDimitry Andric       if (NumBytes) {
3812754fe60SDimitry Andric         if (isARM)
3822754fe60SDimitry Andric           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
3832754fe60SDimitry Andric                                   ARMCC::AL, 0, TII);
3842754fe60SDimitry Andric         else {
3852754fe60SDimitry Andric           // It's not possible to restore SP from FP in a single instruction.
386dff0c46cSDimitry Andric           // For iOS, this looks like:
3872754fe60SDimitry Andric           // mov sp, r7
3882754fe60SDimitry Andric           // sub sp, #24
3892754fe60SDimitry Andric           // This is bad, if an interrupt is taken after the mov, sp is in an
3902754fe60SDimitry Andric           // inconsistent state.
3912754fe60SDimitry Andric           // Use the first callee-saved register as a scratch register.
3922754fe60SDimitry Andric           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
3932754fe60SDimitry Andric                  "No scratch register to restore SP from FP!");
3942754fe60SDimitry Andric           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
3952754fe60SDimitry Andric                                  ARMCC::AL, 0, TII);
39617a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
39717a519f9SDimitry Andric                                  ARM::SP)
39817a519f9SDimitry Andric             .addReg(ARM::R4));
3992754fe60SDimitry Andric         }
4002754fe60SDimitry Andric       } else {
4012754fe60SDimitry Andric         // Thumb2 or ARM.
4022754fe60SDimitry Andric         if (isARM)
4032754fe60SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
4042754fe60SDimitry Andric             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
4052754fe60SDimitry Andric         else
40617a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
40717a519f9SDimitry Andric                                  ARM::SP)
40817a519f9SDimitry Andric             .addReg(FramePtr));
4092754fe60SDimitry Andric       }
4102754fe60SDimitry Andric     } else if (NumBytes)
4112754fe60SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
4122754fe60SDimitry Andric 
4132754fe60SDimitry Andric     // Increment past our save areas.
414dd6029ffSDimitry Andric     if (AFI->getDPRCalleeSavedAreaSize()) {
415dd6029ffSDimitry Andric       MBBI++;
416dd6029ffSDimitry Andric       // Since vpop register list cannot have gaps, there may be multiple vpop
417dd6029ffSDimitry Andric       // instructions in the epilogue.
418dd6029ffSDimitry Andric       while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
419dd6029ffSDimitry Andric         MBBI++;
420dd6029ffSDimitry Andric     }
4212754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
4222754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
4232754fe60SDimitry Andric   }
4242754fe60SDimitry Andric 
425dff0c46cSDimitry Andric   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
4262754fe60SDimitry Andric     // Tail call return: adjust the stack pointer and jump to callee.
4272754fe60SDimitry Andric     MBBI = MBB.getLastNonDebugInstr();
4282754fe60SDimitry Andric     MachineOperand &JumpTarget = MBBI->getOperand(0);
4292754fe60SDimitry Andric 
4302754fe60SDimitry Andric     // Jump to label or value in register.
431dff0c46cSDimitry Andric     if (RetOpcode == ARM::TCRETURNdi) {
432dff0c46cSDimitry Andric       unsigned TCOpcode = STI.isThumb() ?
433dff0c46cSDimitry Andric                (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
434dff0c46cSDimitry Andric                ARM::TAILJMPd;
4352754fe60SDimitry Andric       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
4362754fe60SDimitry Andric       if (JumpTarget.isGlobal())
4372754fe60SDimitry Andric         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
4382754fe60SDimitry Andric                              JumpTarget.getTargetFlags());
4392754fe60SDimitry Andric       else {
4402754fe60SDimitry Andric         assert(JumpTarget.isSymbol());
4412754fe60SDimitry Andric         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
4422754fe60SDimitry Andric                               JumpTarget.getTargetFlags());
4432754fe60SDimitry Andric       }
4446122f3e6SDimitry Andric 
4456122f3e6SDimitry Andric       // Add the default predicate in Thumb mode.
4466122f3e6SDimitry Andric       if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
4472754fe60SDimitry Andric     } else if (RetOpcode == ARM::TCRETURNri) {
4483b0f4066SDimitry Andric       BuildMI(MBB, MBBI, dl,
4493b0f4066SDimitry Andric               TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
4502754fe60SDimitry Andric         addReg(JumpTarget.getReg(), RegState::Kill);
4512754fe60SDimitry Andric     }
4522754fe60SDimitry Andric 
4532754fe60SDimitry Andric     MachineInstr *NewMI = prior(MBBI);
4542754fe60SDimitry Andric     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
4552754fe60SDimitry Andric       NewMI->addOperand(MBBI->getOperand(i));
4562754fe60SDimitry Andric 
4572754fe60SDimitry Andric     // Delete the pseudo instruction TCRETURN.
4582754fe60SDimitry Andric     MBB.erase(MBBI);
45917a519f9SDimitry Andric     MBBI = NewMI;
4602754fe60SDimitry Andric   }
4612754fe60SDimitry Andric 
4622754fe60SDimitry Andric   if (VARegSaveSize)
4632754fe60SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
4642754fe60SDimitry Andric }
4652754fe60SDimitry Andric 
4662754fe60SDimitry Andric /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
4672754fe60SDimitry Andric /// debug info.  It's the same as what we use for resolving the code-gen
4682754fe60SDimitry Andric /// references for now.  FIXME: This can go wrong when references are
4692754fe60SDimitry Andric /// SP-relative and simple call frames aren't used.
4702754fe60SDimitry Andric int
4712754fe60SDimitry Andric ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
4722754fe60SDimitry Andric                                          unsigned &FrameReg) const {
4732754fe60SDimitry Andric   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
4742754fe60SDimitry Andric }
4752754fe60SDimitry Andric 
4762754fe60SDimitry Andric int
4772754fe60SDimitry Andric ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
4783b0f4066SDimitry Andric                                              int FI, unsigned &FrameReg,
4792754fe60SDimitry Andric                                              int SPAdj) const {
4802754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
4812754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
4822754fe60SDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
4832754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4842754fe60SDimitry Andric   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
4852754fe60SDimitry Andric   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
4862754fe60SDimitry Andric   bool isFixed = MFI->isFixedObjectIndex(FI);
4872754fe60SDimitry Andric 
4882754fe60SDimitry Andric   FrameReg = ARM::SP;
4892754fe60SDimitry Andric   Offset += SPAdj;
4902754fe60SDimitry Andric   if (AFI->isGPRCalleeSavedArea1Frame(FI))
4912754fe60SDimitry Andric     return Offset - AFI->getGPRCalleeSavedArea1Offset();
4922754fe60SDimitry Andric   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
4932754fe60SDimitry Andric     return Offset - AFI->getGPRCalleeSavedArea2Offset();
4942754fe60SDimitry Andric   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
4952754fe60SDimitry Andric     return Offset - AFI->getDPRCalleeSavedAreaOffset();
4962754fe60SDimitry Andric 
497dff0c46cSDimitry Andric   // SP can move around if there are allocas.  We may also lose track of SP
498dff0c46cSDimitry Andric   // when emergency spilling inside a non-reserved call frame setup.
499dff0c46cSDimitry Andric   bool hasMovingSP = !hasReservedCallFrame(MF);
500dff0c46cSDimitry Andric 
5012754fe60SDimitry Andric   // When dynamically realigning the stack, use the frame pointer for
5022754fe60SDimitry Andric   // parameters, and the stack/base pointer for locals.
5032754fe60SDimitry Andric   if (RegInfo->needsStackRealignment(MF)) {
5042754fe60SDimitry Andric     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
5052754fe60SDimitry Andric     if (isFixed) {
5062754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
5072754fe60SDimitry Andric       Offset = FPOffset;
508dff0c46cSDimitry Andric     } else if (hasMovingSP) {
5092754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) &&
5102754fe60SDimitry Andric              "VLAs and dynamic stack alignment, but missing base pointer!");
5112754fe60SDimitry Andric       FrameReg = RegInfo->getBaseRegister();
5122754fe60SDimitry Andric     }
5132754fe60SDimitry Andric     return Offset;
5142754fe60SDimitry Andric   }
5152754fe60SDimitry Andric 
5162754fe60SDimitry Andric   // If there is a frame pointer, use it when we can.
5172754fe60SDimitry Andric   if (hasFP(MF) && AFI->hasStackFrame()) {
5182754fe60SDimitry Andric     // Use frame pointer to reference fixed objects. Use it for locals if
5192754fe60SDimitry Andric     // there are VLAs (and thus the SP isn't reliable as a base).
520dff0c46cSDimitry Andric     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
5212754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
5222754fe60SDimitry Andric       return FPOffset;
523dff0c46cSDimitry Andric     } else if (hasMovingSP) {
5242754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
5253b0f4066SDimitry Andric       if (AFI->isThumb2Function()) {
5262754fe60SDimitry Andric         // Try to use the frame pointer if we can, else use the base pointer
5272754fe60SDimitry Andric         // since it's available. This is handy for the emergency spill slot, in
5282754fe60SDimitry Andric         // particular.
5292754fe60SDimitry Andric         if (FPOffset >= -255 && FPOffset < 0) {
5302754fe60SDimitry Andric           FrameReg = RegInfo->getFrameRegister(MF);
5312754fe60SDimitry Andric           return FPOffset;
5322754fe60SDimitry Andric         }
5333b0f4066SDimitry Andric       }
5342754fe60SDimitry Andric     } else if (AFI->isThumb2Function()) {
5353b0f4066SDimitry Andric       // Use  add <rd>, sp, #<imm8>
5363b0f4066SDimitry Andric       //      ldr <rd>, [sp, #<imm8>]
5373b0f4066SDimitry Andric       // if at all possible to save space.
5383b0f4066SDimitry Andric       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
5393b0f4066SDimitry Andric         return Offset;
5402754fe60SDimitry Andric       // In Thumb2 mode, the negative offset is very limited. Try to avoid
5413b0f4066SDimitry Andric       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
5422754fe60SDimitry Andric       if (FPOffset >= -255 && FPOffset < 0) {
5432754fe60SDimitry Andric         FrameReg = RegInfo->getFrameRegister(MF);
5442754fe60SDimitry Andric         return FPOffset;
5452754fe60SDimitry Andric       }
5462754fe60SDimitry Andric     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
5472754fe60SDimitry Andric       // Otherwise, use SP or FP, whichever is closer to the stack slot.
5482754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
5492754fe60SDimitry Andric       return FPOffset;
5502754fe60SDimitry Andric     }
5512754fe60SDimitry Andric   }
5522754fe60SDimitry Andric   // Use the base pointer if we have one.
5532754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
5542754fe60SDimitry Andric     FrameReg = RegInfo->getBaseRegister();
5552754fe60SDimitry Andric   return Offset;
5562754fe60SDimitry Andric }
5572754fe60SDimitry Andric 
5582754fe60SDimitry Andric int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
5592754fe60SDimitry Andric                                           int FI) const {
5602754fe60SDimitry Andric   unsigned FrameReg;
5612754fe60SDimitry Andric   return getFrameIndexReference(MF, FI, FrameReg);
5622754fe60SDimitry Andric }
5632754fe60SDimitry Andric 
5642754fe60SDimitry Andric void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
5652754fe60SDimitry Andric                                     MachineBasicBlock::iterator MI,
5662754fe60SDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
5672754fe60SDimitry Andric                                     unsigned StmOpc, unsigned StrOpc,
5682754fe60SDimitry Andric                                     bool NoGap,
5693b0f4066SDimitry Andric                                     bool(*Func)(unsigned, bool),
570dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
5713b0f4066SDimitry Andric                                     unsigned MIFlags) const {
5722754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
5732754fe60SDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
5742754fe60SDimitry Andric 
5752754fe60SDimitry Andric   DebugLoc DL;
5762754fe60SDimitry Andric   if (MI != MBB.end()) DL = MI->getDebugLoc();
5772754fe60SDimitry Andric 
5782754fe60SDimitry Andric   SmallVector<std::pair<unsigned,bool>, 4> Regs;
5792754fe60SDimitry Andric   unsigned i = CSI.size();
5802754fe60SDimitry Andric   while (i != 0) {
5812754fe60SDimitry Andric     unsigned LastReg = 0;
5822754fe60SDimitry Andric     for (; i != 0; --i) {
5832754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
584dff0c46cSDimitry Andric       if (!(Func)(Reg, STI.isTargetIOS())) continue;
585dff0c46cSDimitry Andric 
586dff0c46cSDimitry Andric       // D-registers in the aligned area DPRCS2 are NOT spilled here.
587dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
588dff0c46cSDimitry Andric         continue;
5892754fe60SDimitry Andric 
5902754fe60SDimitry Andric       // Add the callee-saved register as live-in unless it's LR and
5912754fe60SDimitry Andric       // @llvm.returnaddress is called. If LR is returned for
5922754fe60SDimitry Andric       // @llvm.returnaddress then it's already added to the function and
5932754fe60SDimitry Andric       // entry block live-in sets.
5942754fe60SDimitry Andric       bool isKill = true;
5952754fe60SDimitry Andric       if (Reg == ARM::LR) {
5962754fe60SDimitry Andric         if (MF.getFrameInfo()->isReturnAddressTaken() &&
5972754fe60SDimitry Andric             MF.getRegInfo().isLiveIn(Reg))
5982754fe60SDimitry Andric           isKill = false;
5992754fe60SDimitry Andric       }
6002754fe60SDimitry Andric 
6012754fe60SDimitry Andric       if (isKill)
6022754fe60SDimitry Andric         MBB.addLiveIn(Reg);
6032754fe60SDimitry Andric 
6042754fe60SDimitry Andric       // If NoGap is true, push consecutive registers and then leave the rest
6052754fe60SDimitry Andric       // for other instructions. e.g.
6062754fe60SDimitry Andric       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
6072754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
6082754fe60SDimitry Andric         break;
6092754fe60SDimitry Andric       LastReg = Reg;
6102754fe60SDimitry Andric       Regs.push_back(std::make_pair(Reg, isKill));
6112754fe60SDimitry Andric     }
6122754fe60SDimitry Andric 
6132754fe60SDimitry Andric     if (Regs.empty())
6142754fe60SDimitry Andric       continue;
6152754fe60SDimitry Andric     if (Regs.size() > 1 || StrOpc== 0) {
6162754fe60SDimitry Andric       MachineInstrBuilder MIB =
6172754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
6183b0f4066SDimitry Andric                        .addReg(ARM::SP).setMIFlags(MIFlags));
6192754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
6202754fe60SDimitry Andric         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
6212754fe60SDimitry Andric     } else if (Regs.size() == 1) {
6222754fe60SDimitry Andric       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
6232754fe60SDimitry Andric                                         ARM::SP)
6242754fe60SDimitry Andric         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
6256122f3e6SDimitry Andric         .addReg(ARM::SP).setMIFlags(MIFlags)
6266122f3e6SDimitry Andric         .addImm(-4);
6272754fe60SDimitry Andric       AddDefaultPred(MIB);
6282754fe60SDimitry Andric     }
6292754fe60SDimitry Andric     Regs.clear();
6302754fe60SDimitry Andric   }
6312754fe60SDimitry Andric }
6322754fe60SDimitry Andric 
6332754fe60SDimitry Andric void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
6342754fe60SDimitry Andric                                    MachineBasicBlock::iterator MI,
6352754fe60SDimitry Andric                                    const std::vector<CalleeSavedInfo> &CSI,
6362754fe60SDimitry Andric                                    unsigned LdmOpc, unsigned LdrOpc,
6372754fe60SDimitry Andric                                    bool isVarArg, bool NoGap,
638dff0c46cSDimitry Andric                                    bool(*Func)(unsigned, bool),
639dff0c46cSDimitry Andric                                    unsigned NumAlignedDPRCS2Regs) const {
6402754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
6412754fe60SDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
6422754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
6432754fe60SDimitry Andric   DebugLoc DL = MI->getDebugLoc();
6442754fe60SDimitry Andric   unsigned RetOpcode = MI->getOpcode();
6452754fe60SDimitry Andric   bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
646dff0c46cSDimitry Andric                      RetOpcode == ARM::TCRETURNri);
6472754fe60SDimitry Andric 
6482754fe60SDimitry Andric   SmallVector<unsigned, 4> Regs;
6492754fe60SDimitry Andric   unsigned i = CSI.size();
6502754fe60SDimitry Andric   while (i != 0) {
6512754fe60SDimitry Andric     unsigned LastReg = 0;
6522754fe60SDimitry Andric     bool DeleteRet = false;
6532754fe60SDimitry Andric     for (; i != 0; --i) {
6542754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
655dff0c46cSDimitry Andric       if (!(Func)(Reg, STI.isTargetIOS())) continue;
656dff0c46cSDimitry Andric 
657dff0c46cSDimitry Andric       // The aligned reloads from area DPRCS2 are not inserted here.
658dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
659dff0c46cSDimitry Andric         continue;
6602754fe60SDimitry Andric 
6612754fe60SDimitry Andric       if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
6622754fe60SDimitry Andric         Reg = ARM::PC;
6632754fe60SDimitry Andric         LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
6642754fe60SDimitry Andric         // Fold the return instruction into the LDM.
6652754fe60SDimitry Andric         DeleteRet = true;
6662754fe60SDimitry Andric       }
6672754fe60SDimitry Andric 
6682754fe60SDimitry Andric       // If NoGap is true, pop consecutive registers and then leave the rest
6692754fe60SDimitry Andric       // for other instructions. e.g.
6702754fe60SDimitry Andric       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
6712754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
6722754fe60SDimitry Andric         break;
6732754fe60SDimitry Andric 
6742754fe60SDimitry Andric       LastReg = Reg;
6752754fe60SDimitry Andric       Regs.push_back(Reg);
6762754fe60SDimitry Andric     }
6772754fe60SDimitry Andric 
6782754fe60SDimitry Andric     if (Regs.empty())
6792754fe60SDimitry Andric       continue;
6802754fe60SDimitry Andric     if (Regs.size() > 1 || LdrOpc == 0) {
6812754fe60SDimitry Andric       MachineInstrBuilder MIB =
6822754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
6832754fe60SDimitry Andric                        .addReg(ARM::SP));
6842754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
6852754fe60SDimitry Andric         MIB.addReg(Regs[i], getDefRegState(true));
6866122f3e6SDimitry Andric       if (DeleteRet) {
6876122f3e6SDimitry Andric         MIB->copyImplicitOps(&*MI);
6882754fe60SDimitry Andric         MI->eraseFromParent();
6896122f3e6SDimitry Andric       }
6902754fe60SDimitry Andric       MI = MIB;
6912754fe60SDimitry Andric     } else if (Regs.size() == 1) {
6922754fe60SDimitry Andric       // If we adjusted the reg to PC from LR above, switch it back here. We
6932754fe60SDimitry Andric       // only do that for LDM.
6942754fe60SDimitry Andric       if (Regs[0] == ARM::PC)
6952754fe60SDimitry Andric         Regs[0] = ARM::LR;
6962754fe60SDimitry Andric       MachineInstrBuilder MIB =
6972754fe60SDimitry Andric         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
6982754fe60SDimitry Andric           .addReg(ARM::SP, RegState::Define)
6992754fe60SDimitry Andric           .addReg(ARM::SP);
7002754fe60SDimitry Andric       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
7012754fe60SDimitry Andric       // that refactoring is complete (eventually).
7026122f3e6SDimitry Andric       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
7032754fe60SDimitry Andric         MIB.addReg(0);
7042754fe60SDimitry Andric         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
7052754fe60SDimitry Andric       } else
7062754fe60SDimitry Andric         MIB.addImm(4);
7072754fe60SDimitry Andric       AddDefaultPred(MIB);
7082754fe60SDimitry Andric     }
7092754fe60SDimitry Andric     Regs.clear();
7102754fe60SDimitry Andric   }
7112754fe60SDimitry Andric }
7122754fe60SDimitry Andric 
713dff0c46cSDimitry Andric /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
714dff0c46cSDimitry Andric /// starting from d8.  Also insert stack realignment code and leave the stack
715dff0c46cSDimitry Andric /// pointer pointing to the d8 spill slot.
716dff0c46cSDimitry Andric static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
717dff0c46cSDimitry Andric                                     MachineBasicBlock::iterator MI,
718dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
719dff0c46cSDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
720dff0c46cSDimitry Andric                                     const TargetRegisterInfo *TRI) {
721dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
722dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
723dff0c46cSDimitry Andric   DebugLoc DL = MI->getDebugLoc();
724dff0c46cSDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
725dff0c46cSDimitry Andric   MachineFrameInfo &MFI = *MF.getFrameInfo();
726dff0c46cSDimitry Andric 
727dff0c46cSDimitry Andric   // Mark the D-register spill slots as properly aligned.  Since MFI computes
728dff0c46cSDimitry Andric   // stack slot layout backwards, this can actually mean that the d-reg stack
729dff0c46cSDimitry Andric   // slot offsets can be wrong. The offset for d8 will always be correct.
730dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
731dff0c46cSDimitry Andric     unsigned DNum = CSI[i].getReg() - ARM::D8;
732dff0c46cSDimitry Andric     if (DNum >= 8)
733dff0c46cSDimitry Andric       continue;
734dff0c46cSDimitry Andric     int FI = CSI[i].getFrameIdx();
735dff0c46cSDimitry Andric     // The even-numbered registers will be 16-byte aligned, the odd-numbered
736dff0c46cSDimitry Andric     // registers will be 8-byte aligned.
737dff0c46cSDimitry Andric     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
738dff0c46cSDimitry Andric 
739dff0c46cSDimitry Andric     // The stack slot for D8 needs to be maximally aligned because this is
740dff0c46cSDimitry Andric     // actually the point where we align the stack pointer.  MachineFrameInfo
741dff0c46cSDimitry Andric     // computes all offsets relative to the incoming stack pointer which is a
742dff0c46cSDimitry Andric     // bit weird when realigning the stack.  Any extra padding for this
743dff0c46cSDimitry Andric     // over-alignment is not realized because the code inserted below adjusts
744dff0c46cSDimitry Andric     // the stack pointer by numregs * 8 before aligning the stack pointer.
745dff0c46cSDimitry Andric     if (DNum == 0)
746dff0c46cSDimitry Andric       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
747dff0c46cSDimitry Andric   }
748dff0c46cSDimitry Andric 
749dff0c46cSDimitry Andric   // Move the stack pointer to the d8 spill slot, and align it at the same
750dff0c46cSDimitry Andric   // time. Leave the stack slot address in the scratch register r4.
751dff0c46cSDimitry Andric   //
752dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
753dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
754dff0c46cSDimitry Andric   //   mov sp, r4
755dff0c46cSDimitry Andric   //
756dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
757dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
758dff0c46cSDimitry Andric   AFI->setShouldRestoreSPFromFP(true);
759dff0c46cSDimitry Andric 
760dff0c46cSDimitry Andric   // sub r4, sp, #numregs * 8
761dff0c46cSDimitry Andric   // The immediate is <= 64, so it doesn't need any special encoding.
762dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
763dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
764dff0c46cSDimitry Andric                               .addReg(ARM::SP)
765dff0c46cSDimitry Andric                               .addImm(8 * NumAlignedDPRCS2Regs)));
766dff0c46cSDimitry Andric 
767dff0c46cSDimitry Andric   // bic r4, r4, #align-1
768dff0c46cSDimitry Andric   Opc = isThumb ? ARM::t2BICri : ARM::BICri;
769dff0c46cSDimitry Andric   unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
770dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
771dff0c46cSDimitry Andric                               .addReg(ARM::R4, RegState::Kill)
772dff0c46cSDimitry Andric                               .addImm(MaxAlign - 1)));
773dff0c46cSDimitry Andric 
774dff0c46cSDimitry Andric   // mov sp, r4
775dff0c46cSDimitry Andric   // The stack pointer must be adjusted before spilling anything, otherwise
776dff0c46cSDimitry Andric   // the stack slots could be clobbered by an interrupt handler.
777dff0c46cSDimitry Andric   // Leave r4 live, it is used below.
778dff0c46cSDimitry Andric   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
779dff0c46cSDimitry Andric   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
780dff0c46cSDimitry Andric                             .addReg(ARM::R4);
781dff0c46cSDimitry Andric   MIB = AddDefaultPred(MIB);
782dff0c46cSDimitry Andric   if (!isThumb)
783dff0c46cSDimitry Andric     AddDefaultCC(MIB);
784dff0c46cSDimitry Andric 
785dff0c46cSDimitry Andric   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
786dff0c46cSDimitry Andric   // r4 holds the stack slot address.
787dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
788dff0c46cSDimitry Andric 
789dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
790dff0c46cSDimitry Andric   // The writeback is only needed when emitting two vst1.64 instructions.
791dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
792dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
793dff0c46cSDimitry Andric                                                ARM::QQPRRegisterClass);
794dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
795dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
796dff0c46cSDimitry Andric                            ARM::R4)
797dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
798dff0c46cSDimitry Andric                    .addReg(NextReg)
799dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
800dff0c46cSDimitry Andric     NextReg += 4;
801dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
802dff0c46cSDimitry Andric   }
803dff0c46cSDimitry Andric 
804dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
805dff0c46cSDimitry Andric   // register to be spilled.
806dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
807dff0c46cSDimitry Andric 
808dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
809dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
810dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
811dff0c46cSDimitry Andric                                                ARM::QQPRRegisterClass);
812dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
813dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
814dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(NextReg)
815dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
816dff0c46cSDimitry Andric     NextReg += 4;
817dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
818dff0c46cSDimitry Andric   }
819dff0c46cSDimitry Andric 
820dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 2 d-regs.
821dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
822dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
823dff0c46cSDimitry Andric                                                ARM::QPRRegisterClass);
824dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
825dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
826dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(SupReg));
827dff0c46cSDimitry Andric     NextReg += 2;
828dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
829dff0c46cSDimitry Andric   }
830dff0c46cSDimitry Andric 
831dff0c46cSDimitry Andric   // Finally, use a vanilla vstr.64 for the odd last register.
832dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs) {
833dff0c46cSDimitry Andric     MBB.addLiveIn(NextReg);
834dff0c46cSDimitry Andric     // vstr.64 uses addrmode5 which has an offset scale of 4.
835dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
836dff0c46cSDimitry Andric                    .addReg(NextReg)
837dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
838dff0c46cSDimitry Andric   }
839dff0c46cSDimitry Andric 
840dff0c46cSDimitry Andric   // The last spill instruction inserted should kill the scratch register r4.
841dff0c46cSDimitry Andric   llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
842dff0c46cSDimitry Andric }
843dff0c46cSDimitry Andric 
844dff0c46cSDimitry Andric /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
845dff0c46cSDimitry Andric /// iterator to the following instruction.
846dff0c46cSDimitry Andric static MachineBasicBlock::iterator
847dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
848dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs) {
849dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
850dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
851dff0c46cSDimitry Andric   //   mov sp, r4
852dff0c46cSDimitry Andric   ++MI; ++MI; ++MI;
853dff0c46cSDimitry Andric   assert(MI->mayStore() && "Expecting spill instruction");
854dff0c46cSDimitry Andric 
855dff0c46cSDimitry Andric   // These switches all fall through.
856dff0c46cSDimitry Andric   switch(NumAlignedDPRCS2Regs) {
857dff0c46cSDimitry Andric   case 7:
858dff0c46cSDimitry Andric     ++MI;
859dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
860dff0c46cSDimitry Andric   default:
861dff0c46cSDimitry Andric     ++MI;
862dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
863dff0c46cSDimitry Andric   case 1:
864dff0c46cSDimitry Andric   case 2:
865dff0c46cSDimitry Andric   case 4:
866dff0c46cSDimitry Andric     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
867dff0c46cSDimitry Andric     ++MI;
868dff0c46cSDimitry Andric   }
869dff0c46cSDimitry Andric   return MI;
870dff0c46cSDimitry Andric }
871dff0c46cSDimitry Andric 
872dff0c46cSDimitry Andric /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
873dff0c46cSDimitry Andric /// starting from d8.  These instructions are assumed to execute while the
874dff0c46cSDimitry Andric /// stack is still aligned, unlike the code inserted by emitPopInst.
875dff0c46cSDimitry Andric static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
876dff0c46cSDimitry Andric                                       MachineBasicBlock::iterator MI,
877dff0c46cSDimitry Andric                                       unsigned NumAlignedDPRCS2Regs,
878dff0c46cSDimitry Andric                                       const std::vector<CalleeSavedInfo> &CSI,
879dff0c46cSDimitry Andric                                       const TargetRegisterInfo *TRI) {
880dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
881dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
882dff0c46cSDimitry Andric   DebugLoc DL = MI->getDebugLoc();
883dff0c46cSDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
884dff0c46cSDimitry Andric 
885dff0c46cSDimitry Andric   // Find the frame index assigned to d8.
886dff0c46cSDimitry Andric   int D8SpillFI = 0;
887dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
888dff0c46cSDimitry Andric     if (CSI[i].getReg() == ARM::D8) {
889dff0c46cSDimitry Andric       D8SpillFI = CSI[i].getFrameIdx();
890dff0c46cSDimitry Andric       break;
891dff0c46cSDimitry Andric     }
892dff0c46cSDimitry Andric 
893dff0c46cSDimitry Andric   // Materialize the address of the d8 spill slot into the scratch register r4.
894dff0c46cSDimitry Andric   // This can be fairly complicated if the stack frame is large, so just use
895dff0c46cSDimitry Andric   // the normal frame index elimination mechanism to do it.  This code runs as
896dff0c46cSDimitry Andric   // the initial part of the epilog where the stack and base pointers haven't
897dff0c46cSDimitry Andric   // been changed yet.
898dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
899dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
900dff0c46cSDimitry Andric 
901dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
902dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
903dff0c46cSDimitry Andric                               .addFrameIndex(D8SpillFI).addImm(0)));
904dff0c46cSDimitry Andric 
905dff0c46cSDimitry Andric   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
906dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
907dff0c46cSDimitry Andric 
908dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
909dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
910dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
911dff0c46cSDimitry Andric                                                ARM::QQPRRegisterClass);
912dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
913dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Define)
914dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
915dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
916dff0c46cSDimitry Andric     NextReg += 4;
917dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
918dff0c46cSDimitry Andric   }
919dff0c46cSDimitry Andric 
920dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
921dff0c46cSDimitry Andric   // register to be spilled.
922dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
923dff0c46cSDimitry Andric 
924dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
925dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
926dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
927dff0c46cSDimitry Andric                                                ARM::QQPRRegisterClass);
928dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
929dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16)
930dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
931dff0c46cSDimitry Andric     NextReg += 4;
932dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
933dff0c46cSDimitry Andric   }
934dff0c46cSDimitry Andric 
935dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 2 d-regs.
936dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
937dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
938dff0c46cSDimitry Andric                                                ARM::QPRRegisterClass);
939dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
940dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16));
941dff0c46cSDimitry Andric     NextReg += 2;
942dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
943dff0c46cSDimitry Andric   }
944dff0c46cSDimitry Andric 
945dff0c46cSDimitry Andric   // Finally, use a vanilla vldr.64 for the remaining odd register.
946dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
947dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
948dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
949dff0c46cSDimitry Andric 
950dff0c46cSDimitry Andric   // Last store kills r4.
951dff0c46cSDimitry Andric   llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
952dff0c46cSDimitry Andric }
953dff0c46cSDimitry Andric 
9542754fe60SDimitry Andric bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
9552754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
9562754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
9572754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
9582754fe60SDimitry Andric   if (CSI.empty())
9592754fe60SDimitry Andric     return false;
9602754fe60SDimitry Andric 
9612754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
9622754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
9632754fe60SDimitry Andric 
9642754fe60SDimitry Andric   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
9656122f3e6SDimitry Andric   unsigned PushOneOpc = AFI->isThumbFunction() ?
9666122f3e6SDimitry Andric     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
9672754fe60SDimitry Andric   unsigned FltOpc = ARM::VSTMDDB_UPD;
968dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
969dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
9703b0f4066SDimitry Andric                MachineInstr::FrameSetup);
971dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
9723b0f4066SDimitry Andric                MachineInstr::FrameSetup);
9733b0f4066SDimitry Andric   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
974dff0c46cSDimitry Andric                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
975dff0c46cSDimitry Andric 
976dff0c46cSDimitry Andric   // The code above does not insert spill code for the aligned DPRCS2 registers.
977dff0c46cSDimitry Andric   // The stack realignment code will be inserted between the push instructions
978dff0c46cSDimitry Andric   // and these spills.
979dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
980dff0c46cSDimitry Andric     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
9812754fe60SDimitry Andric 
9822754fe60SDimitry Andric   return true;
9832754fe60SDimitry Andric }
9842754fe60SDimitry Andric 
9852754fe60SDimitry Andric bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
9862754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
9872754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
9882754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
9892754fe60SDimitry Andric   if (CSI.empty())
9902754fe60SDimitry Andric     return false;
9912754fe60SDimitry Andric 
9922754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
9932754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
9942754fe60SDimitry Andric   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
995dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
996dff0c46cSDimitry Andric 
997dff0c46cSDimitry Andric   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
998dff0c46cSDimitry Andric   // registers. Do that here instead.
999dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1000dff0c46cSDimitry Andric     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
10012754fe60SDimitry Andric 
10022754fe60SDimitry Andric   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
10036122f3e6SDimitry Andric   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
10042754fe60SDimitry Andric   unsigned FltOpc = ARM::VLDMDIA_UPD;
1005dff0c46cSDimitry Andric   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1006dff0c46cSDimitry Andric               NumAlignedDPRCS2Regs);
10072754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1008dff0c46cSDimitry Andric               &isARMArea2Register, 0);
10092754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1010dff0c46cSDimitry Andric               &isARMArea1Register, 0);
10112754fe60SDimitry Andric 
10122754fe60SDimitry Andric   return true;
10132754fe60SDimitry Andric }
10142754fe60SDimitry Andric 
10152754fe60SDimitry Andric // FIXME: Make generic?
10162754fe60SDimitry Andric static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
10172754fe60SDimitry Andric                                        const ARMBaseInstrInfo &TII) {
10182754fe60SDimitry Andric   unsigned FnSize = 0;
10192754fe60SDimitry Andric   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
10202754fe60SDimitry Andric        MBBI != E; ++MBBI) {
10212754fe60SDimitry Andric     const MachineBasicBlock &MBB = *MBBI;
10222754fe60SDimitry Andric     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
10232754fe60SDimitry Andric          I != E; ++I)
10242754fe60SDimitry Andric       FnSize += TII.GetInstSizeInBytes(I);
10252754fe60SDimitry Andric   }
10262754fe60SDimitry Andric   return FnSize;
10272754fe60SDimitry Andric }
10282754fe60SDimitry Andric 
10292754fe60SDimitry Andric /// estimateStackSize - Estimate and return the size of the frame.
10302754fe60SDimitry Andric /// FIXME: Make generic?
10312754fe60SDimitry Andric static unsigned estimateStackSize(MachineFunction &MF) {
103217a519f9SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
103317a519f9SDimitry Andric   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
103417a519f9SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
103517a519f9SDimitry Andric   unsigned MaxAlign = MFI->getMaxAlignment();
10362754fe60SDimitry Andric   int Offset = 0;
103717a519f9SDimitry Andric 
103817a519f9SDimitry Andric   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
103917a519f9SDimitry Andric   // It really should be refactored to share code. Until then, changes
104017a519f9SDimitry Andric   // should keep in mind that there's tight coupling between the two.
104117a519f9SDimitry Andric 
104217a519f9SDimitry Andric   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
104317a519f9SDimitry Andric     int FixedOff = -MFI->getObjectOffset(i);
10442754fe60SDimitry Andric     if (FixedOff > Offset) Offset = FixedOff;
10452754fe60SDimitry Andric   }
104617a519f9SDimitry Andric   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
104717a519f9SDimitry Andric     if (MFI->isDeadObjectIndex(i))
10482754fe60SDimitry Andric       continue;
104917a519f9SDimitry Andric     Offset += MFI->getObjectSize(i);
105017a519f9SDimitry Andric     unsigned Align = MFI->getObjectAlignment(i);
10512754fe60SDimitry Andric     // Adjust to alignment boundary
10522754fe60SDimitry Andric     Offset = (Offset+Align-1)/Align*Align;
105317a519f9SDimitry Andric 
105417a519f9SDimitry Andric     MaxAlign = std::max(Align, MaxAlign);
10552754fe60SDimitry Andric   }
105617a519f9SDimitry Andric 
105717a519f9SDimitry Andric   if (MFI->adjustsStack() && TFI->hasReservedCallFrame(MF))
105817a519f9SDimitry Andric     Offset += MFI->getMaxCallFrameSize();
105917a519f9SDimitry Andric 
106017a519f9SDimitry Andric   // Round up the size to a multiple of the alignment.  If the function has
106117a519f9SDimitry Andric   // any calls or alloca's, align to the target's StackAlignment value to
106217a519f9SDimitry Andric   // ensure that the callee's frame or the alloca data is suitably aligned;
106317a519f9SDimitry Andric   // otherwise, for leaf functions, align to the TransientStackAlignment
106417a519f9SDimitry Andric   // value.
106517a519f9SDimitry Andric   unsigned StackAlign;
106617a519f9SDimitry Andric   if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
106717a519f9SDimitry Andric       (RegInfo->needsStackRealignment(MF) && MFI->getObjectIndexEnd() != 0))
106817a519f9SDimitry Andric     StackAlign = TFI->getStackAlignment();
106917a519f9SDimitry Andric   else
107017a519f9SDimitry Andric     StackAlign = TFI->getTransientStackAlignment();
107117a519f9SDimitry Andric 
107217a519f9SDimitry Andric   // If the frame pointer is eliminated, all frame offsets will be relative to
107317a519f9SDimitry Andric   // SP not FP. Align to MaxAlign so this works.
107417a519f9SDimitry Andric   StackAlign = std::max(StackAlign, MaxAlign);
107517a519f9SDimitry Andric   unsigned AlignMask = StackAlign - 1;
107617a519f9SDimitry Andric   Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
107717a519f9SDimitry Andric 
10782754fe60SDimitry Andric   return (unsigned)Offset;
10792754fe60SDimitry Andric }
10802754fe60SDimitry Andric 
10812754fe60SDimitry Andric /// estimateRSStackSizeLimit - Look at each instruction that references stack
10822754fe60SDimitry Andric /// frames and return the stack size limit beyond which some of these
10832754fe60SDimitry Andric /// instructions will require a scratch register during their expansion later.
10842754fe60SDimitry Andric // FIXME: Move to TII?
10852754fe60SDimitry Andric static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
10862754fe60SDimitry Andric                                          const TargetFrameLowering *TFI) {
10872754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
10882754fe60SDimitry Andric   unsigned Limit = (1 << 12) - 1;
10892754fe60SDimitry Andric   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
10902754fe60SDimitry Andric     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
10912754fe60SDimitry Andric          I != E; ++I) {
10922754fe60SDimitry Andric       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
10932754fe60SDimitry Andric         if (!I->getOperand(i).isFI()) continue;
10942754fe60SDimitry Andric 
10952754fe60SDimitry Andric         // When using ADDri to get the address of a stack object, 255 is the
10962754fe60SDimitry Andric         // largest offset guaranteed to fit in the immediate offset.
10972754fe60SDimitry Andric         if (I->getOpcode() == ARM::ADDri) {
10982754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
10992754fe60SDimitry Andric           break;
11002754fe60SDimitry Andric         }
11012754fe60SDimitry Andric 
11022754fe60SDimitry Andric         // Otherwise check the addressing mode.
11032754fe60SDimitry Andric         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
11042754fe60SDimitry Andric         case ARMII::AddrMode3:
11052754fe60SDimitry Andric         case ARMII::AddrModeT2_i8:
11062754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
11072754fe60SDimitry Andric           break;
11082754fe60SDimitry Andric         case ARMII::AddrMode5:
11092754fe60SDimitry Andric         case ARMII::AddrModeT2_i8s4:
11102754fe60SDimitry Andric           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
11112754fe60SDimitry Andric           break;
11122754fe60SDimitry Andric         case ARMII::AddrModeT2_i12:
11132754fe60SDimitry Andric           // i12 supports only positive offset so these will be converted to
11142754fe60SDimitry Andric           // i8 opcodes. See llvm::rewriteT2FrameIndex.
11152754fe60SDimitry Andric           if (TFI->hasFP(MF) && AFI->hasStackFrame())
11162754fe60SDimitry Andric             Limit = std::min(Limit, (1U << 8) - 1);
11172754fe60SDimitry Andric           break;
11182754fe60SDimitry Andric         case ARMII::AddrMode4:
11192754fe60SDimitry Andric         case ARMII::AddrMode6:
11202754fe60SDimitry Andric           // Addressing modes 4 & 6 (load/store) instructions can't encode an
11212754fe60SDimitry Andric           // immediate offset for stack references.
11222754fe60SDimitry Andric           return 0;
11232754fe60SDimitry Andric         default:
11242754fe60SDimitry Andric           break;
11252754fe60SDimitry Andric         }
11262754fe60SDimitry Andric         break; // At most one FI per instruction
11272754fe60SDimitry Andric       }
11282754fe60SDimitry Andric     }
11292754fe60SDimitry Andric   }
11302754fe60SDimitry Andric 
11312754fe60SDimitry Andric   return Limit;
11322754fe60SDimitry Andric }
11332754fe60SDimitry Andric 
1134dff0c46cSDimitry Andric // In functions that realign the stack, it can be an advantage to spill the
1135dff0c46cSDimitry Andric // callee-saved vector registers after realigning the stack. The vst1 and vld1
1136dff0c46cSDimitry Andric // instructions take alignment hints that can improve performance.
1137dff0c46cSDimitry Andric //
1138dff0c46cSDimitry Andric static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1139dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1140dff0c46cSDimitry Andric   if (!SpillAlignedNEONRegs)
1141dff0c46cSDimitry Andric     return;
1142dff0c46cSDimitry Andric 
1143dff0c46cSDimitry Andric   // Naked functions don't spill callee-saved registers.
1144dff0c46cSDimitry Andric   if (MF.getFunction()->hasFnAttr(Attribute::Naked))
1145dff0c46cSDimitry Andric     return;
1146dff0c46cSDimitry Andric 
1147dff0c46cSDimitry Andric   // We are planning to use NEON instructions vst1 / vld1.
1148dff0c46cSDimitry Andric   if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1149dff0c46cSDimitry Andric     return;
1150dff0c46cSDimitry Andric 
1151dff0c46cSDimitry Andric   // Don't bother if the default stack alignment is sufficiently high.
1152dff0c46cSDimitry Andric   if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1153dff0c46cSDimitry Andric     return;
1154dff0c46cSDimitry Andric 
1155dff0c46cSDimitry Andric   // Aligned spills require stack realignment.
1156dff0c46cSDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
1157dff0c46cSDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1158dff0c46cSDimitry Andric   if (!RegInfo->canRealignStack(MF))
1159dff0c46cSDimitry Andric     return;
1160dff0c46cSDimitry Andric 
1161dff0c46cSDimitry Andric   // We always spill contiguous d-registers starting from d8. Count how many
1162dff0c46cSDimitry Andric   // needs spilling.  The register allocator will almost always use the
1163dff0c46cSDimitry Andric   // callee-saved registers in order, but it can happen that there are holes in
1164dff0c46cSDimitry Andric   // the range.  Registers above the hole will be spilled to the standard DPRCS
1165dff0c46cSDimitry Andric   // area.
1166dff0c46cSDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
1167dff0c46cSDimitry Andric   unsigned NumSpills = 0;
1168dff0c46cSDimitry Andric   for (; NumSpills < 8; ++NumSpills)
1169dff0c46cSDimitry Andric     if (!MRI.isPhysRegOrOverlapUsed(ARM::D8 + NumSpills))
1170dff0c46cSDimitry Andric       break;
1171dff0c46cSDimitry Andric 
1172dff0c46cSDimitry Andric   // Don't do this for just one d-register. It's not worth it.
1173dff0c46cSDimitry Andric   if (NumSpills < 2)
1174dff0c46cSDimitry Andric     return;
1175dff0c46cSDimitry Andric 
1176dff0c46cSDimitry Andric   // Spill the first NumSpills D-registers after realigning the stack.
1177dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1178dff0c46cSDimitry Andric 
1179dff0c46cSDimitry Andric   // A scratch register is required for the vst1 / vld1 instructions.
1180dff0c46cSDimitry Andric   MF.getRegInfo().setPhysRegUsed(ARM::R4);
1181dff0c46cSDimitry Andric }
1182dff0c46cSDimitry Andric 
11832754fe60SDimitry Andric void
11842754fe60SDimitry Andric ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
11852754fe60SDimitry Andric                                                        RegScavenger *RS) const {
11862754fe60SDimitry Andric   // This tells PEI to spill the FP as if it is any other callee-save register
11872754fe60SDimitry Andric   // to take advantage the eliminateFrameIndex machinery. This also ensures it
11882754fe60SDimitry Andric   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
11892754fe60SDimitry Andric   // to combine multiple loads / stores.
11902754fe60SDimitry Andric   bool CanEliminateFrame = true;
11912754fe60SDimitry Andric   bool CS1Spilled = false;
11922754fe60SDimitry Andric   bool LRSpilled = false;
11932754fe60SDimitry Andric   unsigned NumGPRSpills = 0;
11942754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS1GPRs;
11952754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS2GPRs;
11962754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
11972754fe60SDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
11982754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
11992754fe60SDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
12002754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
12012754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
12022754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
12032754fe60SDimitry Andric 
12042754fe60SDimitry Andric   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
12052754fe60SDimitry Andric   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
12062754fe60SDimitry Andric   // since it's not always possible to restore sp from fp in a single
12072754fe60SDimitry Andric   // instruction.
12082754fe60SDimitry Andric   // FIXME: It will be better just to find spare register here.
12092754fe60SDimitry Andric   if (AFI->isThumb2Function() &&
12102754fe60SDimitry Andric       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
12112754fe60SDimitry Andric     MF.getRegInfo().setPhysRegUsed(ARM::R4);
12122754fe60SDimitry Andric 
12132754fe60SDimitry Andric   if (AFI->isThumb1OnlyFunction()) {
12142754fe60SDimitry Andric     // Spill LR if Thumb1 function uses variable length argument lists.
12152754fe60SDimitry Andric     if (AFI->getVarArgsRegSaveSize() > 0)
12162754fe60SDimitry Andric       MF.getRegInfo().setPhysRegUsed(ARM::LR);
12172754fe60SDimitry Andric 
121817a519f9SDimitry Andric     // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
121917a519f9SDimitry Andric     // for sure what the stack size will be, but for this, an estimate is good
122017a519f9SDimitry Andric     // enough. If there anything changes it, it'll be a spill, which implies
122117a519f9SDimitry Andric     // we've used all the registers and so R4 is already used, so not marking
122217a519f9SDimitry Andric     // it here will be OK.
12232754fe60SDimitry Andric     // FIXME: It will be better just to find spare register here.
122417a519f9SDimitry Andric     unsigned StackSize = estimateStackSize(MF);
122517a519f9SDimitry Andric     if (MFI->hasVarSizedObjects() || StackSize > 508)
12262754fe60SDimitry Andric       MF.getRegInfo().setPhysRegUsed(ARM::R4);
12272754fe60SDimitry Andric   }
12282754fe60SDimitry Andric 
1229dff0c46cSDimitry Andric   // See if we can spill vector registers to aligned stack.
1230dff0c46cSDimitry Andric   checkNumAlignedDPRCS2Regs(MF);
1231dff0c46cSDimitry Andric 
12322754fe60SDimitry Andric   // Spill the BasePtr if it's used.
12332754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
12342754fe60SDimitry Andric     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
12352754fe60SDimitry Andric 
12362754fe60SDimitry Andric   // Don't spill FP if the frame can be eliminated. This is determined
12372754fe60SDimitry Andric   // by scanning the callee-save registers to see if any is used.
1238dff0c46cSDimitry Andric   const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
12392754fe60SDimitry Andric   for (unsigned i = 0; CSRegs[i]; ++i) {
12402754fe60SDimitry Andric     unsigned Reg = CSRegs[i];
12412754fe60SDimitry Andric     bool Spilled = false;
1242dff0c46cSDimitry Andric     if (MF.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
12432754fe60SDimitry Andric       Spilled = true;
12442754fe60SDimitry Andric       CanEliminateFrame = false;
12452754fe60SDimitry Andric     }
12462754fe60SDimitry Andric 
12472754fe60SDimitry Andric     if (!ARM::GPRRegisterClass->contains(Reg))
12482754fe60SDimitry Andric       continue;
12492754fe60SDimitry Andric 
12502754fe60SDimitry Andric     if (Spilled) {
12512754fe60SDimitry Andric       NumGPRSpills++;
12522754fe60SDimitry Andric 
1253dff0c46cSDimitry Andric       if (!STI.isTargetIOS()) {
12542754fe60SDimitry Andric         if (Reg == ARM::LR)
12552754fe60SDimitry Andric           LRSpilled = true;
12562754fe60SDimitry Andric         CS1Spilled = true;
12572754fe60SDimitry Andric         continue;
12582754fe60SDimitry Andric       }
12592754fe60SDimitry Andric 
12602754fe60SDimitry Andric       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
12612754fe60SDimitry Andric       switch (Reg) {
12622754fe60SDimitry Andric       case ARM::LR:
12632754fe60SDimitry Andric         LRSpilled = true;
12642754fe60SDimitry Andric         // Fallthrough
12652754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
12662754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
12672754fe60SDimitry Andric         CS1Spilled = true;
12682754fe60SDimitry Andric         break;
12692754fe60SDimitry Andric       default:
12702754fe60SDimitry Andric         break;
12712754fe60SDimitry Andric       }
12722754fe60SDimitry Andric     } else {
1273dff0c46cSDimitry Andric       if (!STI.isTargetIOS()) {
12742754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
12752754fe60SDimitry Andric         continue;
12762754fe60SDimitry Andric       }
12772754fe60SDimitry Andric 
12782754fe60SDimitry Andric       switch (Reg) {
12792754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
12802754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
12812754fe60SDimitry Andric       case ARM::LR:
12822754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
12832754fe60SDimitry Andric         break;
12842754fe60SDimitry Andric       default:
12852754fe60SDimitry Andric         UnspilledCS2GPRs.push_back(Reg);
12862754fe60SDimitry Andric         break;
12872754fe60SDimitry Andric       }
12882754fe60SDimitry Andric     }
12892754fe60SDimitry Andric   }
12902754fe60SDimitry Andric 
12912754fe60SDimitry Andric   bool ForceLRSpill = false;
12922754fe60SDimitry Andric   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
12932754fe60SDimitry Andric     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
12942754fe60SDimitry Andric     // Force LR to be spilled if the Thumb function size is > 2048. This enables
12952754fe60SDimitry Andric     // use of BL to implement far jump. If it turns out that it's not needed
12962754fe60SDimitry Andric     // then the branch fix up path will undo it.
12972754fe60SDimitry Andric     if (FnSize >= (1 << 11)) {
12982754fe60SDimitry Andric       CanEliminateFrame = false;
12992754fe60SDimitry Andric       ForceLRSpill = true;
13002754fe60SDimitry Andric     }
13012754fe60SDimitry Andric   }
13022754fe60SDimitry Andric 
13032754fe60SDimitry Andric   // If any of the stack slot references may be out of range of an immediate
13042754fe60SDimitry Andric   // offset, make sure a register (or a spill slot) is available for the
13052754fe60SDimitry Andric   // register scavenger. Note that if we're indexing off the frame pointer, the
13062754fe60SDimitry Andric   // effective stack size is 4 bytes larger since the FP points to the stack
13072754fe60SDimitry Andric   // slot of the previous FP. Also, if we have variable sized objects in the
13082754fe60SDimitry Andric   // function, stack slot references will often be negative, and some of
13092754fe60SDimitry Andric   // our instructions are positive-offset only, so conservatively consider
13102754fe60SDimitry Andric   // that case to want a spill slot (or register) as well. Similarly, if
13112754fe60SDimitry Andric   // the function adjusts the stack pointer during execution and the
13122754fe60SDimitry Andric   // adjustments aren't already part of our stack size estimate, our offset
13132754fe60SDimitry Andric   // calculations may be off, so be conservative.
13142754fe60SDimitry Andric   // FIXME: We could add logic to be more precise about negative offsets
13152754fe60SDimitry Andric   //        and which instructions will need a scratch register for them. Is it
13162754fe60SDimitry Andric   //        worth the effort and added fragility?
13172754fe60SDimitry Andric   bool BigStack =
13182754fe60SDimitry Andric     (RS &&
13192754fe60SDimitry Andric      (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
13202754fe60SDimitry Andric       estimateRSStackSizeLimit(MF, this)))
13212754fe60SDimitry Andric     || MFI->hasVarSizedObjects()
13222754fe60SDimitry Andric     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
13232754fe60SDimitry Andric 
13242754fe60SDimitry Andric   bool ExtraCSSpill = false;
13252754fe60SDimitry Andric   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
13262754fe60SDimitry Andric     AFI->setHasStackFrame(true);
13272754fe60SDimitry Andric 
13282754fe60SDimitry Andric     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
13292754fe60SDimitry Andric     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
13302754fe60SDimitry Andric     if (!LRSpilled && CS1Spilled) {
13312754fe60SDimitry Andric       MF.getRegInfo().setPhysRegUsed(ARM::LR);
13322754fe60SDimitry Andric       NumGPRSpills++;
13332754fe60SDimitry Andric       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
13342754fe60SDimitry Andric                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
13352754fe60SDimitry Andric       ForceLRSpill = false;
13362754fe60SDimitry Andric       ExtraCSSpill = true;
13372754fe60SDimitry Andric     }
13382754fe60SDimitry Andric 
13392754fe60SDimitry Andric     if (hasFP(MF)) {
13402754fe60SDimitry Andric       MF.getRegInfo().setPhysRegUsed(FramePtr);
13412754fe60SDimitry Andric       NumGPRSpills++;
13422754fe60SDimitry Andric     }
13432754fe60SDimitry Andric 
13442754fe60SDimitry Andric     // If stack and double are 8-byte aligned and we are spilling an odd number
13452754fe60SDimitry Andric     // of GPRs, spill one extra callee save GPR so we won't have to pad between
13462754fe60SDimitry Andric     // the integer and double callee save areas.
13472754fe60SDimitry Andric     unsigned TargetAlign = getStackAlignment();
13482754fe60SDimitry Andric     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
13492754fe60SDimitry Andric       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
13502754fe60SDimitry Andric         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
13512754fe60SDimitry Andric           unsigned Reg = UnspilledCS1GPRs[i];
13522754fe60SDimitry Andric           // Don't spill high register if the function is thumb1
13532754fe60SDimitry Andric           if (!AFI->isThumb1OnlyFunction() ||
13542754fe60SDimitry Andric               isARMLowRegister(Reg) || Reg == ARM::LR) {
13552754fe60SDimitry Andric             MF.getRegInfo().setPhysRegUsed(Reg);
13562754fe60SDimitry Andric             if (!RegInfo->isReservedReg(MF, Reg))
13572754fe60SDimitry Andric               ExtraCSSpill = true;
13582754fe60SDimitry Andric             break;
13592754fe60SDimitry Andric           }
13602754fe60SDimitry Andric         }
13612754fe60SDimitry Andric       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
13622754fe60SDimitry Andric         unsigned Reg = UnspilledCS2GPRs.front();
13632754fe60SDimitry Andric         MF.getRegInfo().setPhysRegUsed(Reg);
13642754fe60SDimitry Andric         if (!RegInfo->isReservedReg(MF, Reg))
13652754fe60SDimitry Andric           ExtraCSSpill = true;
13662754fe60SDimitry Andric       }
13672754fe60SDimitry Andric     }
13682754fe60SDimitry Andric 
13692754fe60SDimitry Andric     // Estimate if we might need to scavenge a register at some point in order
13702754fe60SDimitry Andric     // to materialize a stack offset. If so, either spill one additional
13712754fe60SDimitry Andric     // callee-saved register or reserve a special spill slot to facilitate
13722754fe60SDimitry Andric     // register scavenging. Thumb1 needs a spill slot for stack pointer
13732754fe60SDimitry Andric     // adjustments also, even when the frame itself is small.
13742754fe60SDimitry Andric     if (BigStack && !ExtraCSSpill) {
13752754fe60SDimitry Andric       // If any non-reserved CS register isn't spilled, just spill one or two
13762754fe60SDimitry Andric       // extra. That should take care of it!
13772754fe60SDimitry Andric       unsigned NumExtras = TargetAlign / 4;
13782754fe60SDimitry Andric       SmallVector<unsigned, 2> Extras;
13792754fe60SDimitry Andric       while (NumExtras && !UnspilledCS1GPRs.empty()) {
13802754fe60SDimitry Andric         unsigned Reg = UnspilledCS1GPRs.back();
13812754fe60SDimitry Andric         UnspilledCS1GPRs.pop_back();
13822754fe60SDimitry Andric         if (!RegInfo->isReservedReg(MF, Reg) &&
13832754fe60SDimitry Andric             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
13842754fe60SDimitry Andric              Reg == ARM::LR)) {
13852754fe60SDimitry Andric           Extras.push_back(Reg);
13862754fe60SDimitry Andric           NumExtras--;
13872754fe60SDimitry Andric         }
13882754fe60SDimitry Andric       }
13892754fe60SDimitry Andric       // For non-Thumb1 functions, also check for hi-reg CS registers
13902754fe60SDimitry Andric       if (!AFI->isThumb1OnlyFunction()) {
13912754fe60SDimitry Andric         while (NumExtras && !UnspilledCS2GPRs.empty()) {
13922754fe60SDimitry Andric           unsigned Reg = UnspilledCS2GPRs.back();
13932754fe60SDimitry Andric           UnspilledCS2GPRs.pop_back();
13942754fe60SDimitry Andric           if (!RegInfo->isReservedReg(MF, Reg)) {
13952754fe60SDimitry Andric             Extras.push_back(Reg);
13962754fe60SDimitry Andric             NumExtras--;
13972754fe60SDimitry Andric           }
13982754fe60SDimitry Andric         }
13992754fe60SDimitry Andric       }
14002754fe60SDimitry Andric       if (Extras.size() && NumExtras == 0) {
14012754fe60SDimitry Andric         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
14022754fe60SDimitry Andric           MF.getRegInfo().setPhysRegUsed(Extras[i]);
14032754fe60SDimitry Andric         }
14042754fe60SDimitry Andric       } else if (!AFI->isThumb1OnlyFunction()) {
14052754fe60SDimitry Andric         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
14062754fe60SDimitry Andric         // closest to SP or frame pointer.
14072754fe60SDimitry Andric         const TargetRegisterClass *RC = ARM::GPRRegisterClass;
14082754fe60SDimitry Andric         RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
14092754fe60SDimitry Andric                                                            RC->getAlignment(),
14102754fe60SDimitry Andric                                                            false));
14112754fe60SDimitry Andric       }
14122754fe60SDimitry Andric     }
14132754fe60SDimitry Andric   }
14142754fe60SDimitry Andric 
14152754fe60SDimitry Andric   if (ForceLRSpill) {
14162754fe60SDimitry Andric     MF.getRegInfo().setPhysRegUsed(ARM::LR);
14172754fe60SDimitry Andric     AFI->setLRIsSpilledForFarJump(true);
14182754fe60SDimitry Andric   }
14192754fe60SDimitry Andric }
1420