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"
187ae0e2c9SDimitry Andric #include "llvm/CallingConv.h"
197ae0e2c9SDimitry Andric #include "llvm/Function.h"
206122f3e6SDimitry Andric #include "MCTargetDesc/ARMAddressingModes.h"
21dff0c46cSDimitry Andric #include "llvm/Function.h"
222754fe60SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
232754fe60SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
242754fe60SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
252754fe60SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
262754fe60SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h"
272754fe60SDimitry Andric #include "llvm/Target/TargetOptions.h"
28dff0c46cSDimitry Andric #include "llvm/Support/CommandLine.h"
292754fe60SDimitry Andric 
302754fe60SDimitry Andric using namespace llvm;
312754fe60SDimitry Andric 
32dff0c46cSDimitry Andric static cl::opt<bool>
33dff0c46cSDimitry Andric SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
34dff0c46cSDimitry Andric                      cl::desc("Align ARM NEON spills in prolog and epilog"));
35dff0c46cSDimitry Andric 
36dff0c46cSDimitry Andric static MachineBasicBlock::iterator
37dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
38dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs);
39dff0c46cSDimitry Andric 
402754fe60SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame
412754fe60SDimitry Andric /// pointer register.  This is true if the function has variable sized allocas
422754fe60SDimitry Andric /// or if frame pointer elimination is disabled.
432754fe60SDimitry Andric bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
442754fe60SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
452754fe60SDimitry Andric 
46dff0c46cSDimitry Andric   // iOS requires FP not to be clobbered for backtracing purpose.
47dff0c46cSDimitry Andric   if (STI.isTargetIOS())
482754fe60SDimitry Andric     return true;
492754fe60SDimitry Andric 
502754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
512754fe60SDimitry Andric   // Always eliminate non-leaf frame pointers.
52dff0c46cSDimitry Andric   return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
53dff0c46cSDimitry Andric            MFI->hasCalls()) ||
542754fe60SDimitry Andric           RegInfo->needsStackRealignment(MF) ||
552754fe60SDimitry Andric           MFI->hasVarSizedObjects() ||
562754fe60SDimitry Andric           MFI->isFrameAddressTaken());
572754fe60SDimitry Andric }
582754fe60SDimitry Andric 
592754fe60SDimitry Andric /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
602754fe60SDimitry Andric /// not required, we reserve argument space for call sites in the function
612754fe60SDimitry Andric /// immediately on entry to the current function.  This eliminates the need for
622754fe60SDimitry Andric /// add/sub sp brackets around call sites.  Returns true if the call frame is
632754fe60SDimitry Andric /// included as part of the stack frame.
642754fe60SDimitry Andric bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
652754fe60SDimitry Andric   const MachineFrameInfo *FFI = MF.getFrameInfo();
662754fe60SDimitry Andric   unsigned CFSize = FFI->getMaxCallFrameSize();
672754fe60SDimitry Andric   // It's not always a good idea to include the call frame as part of the
682754fe60SDimitry Andric   // stack frame. ARM (especially Thumb) has small immediate offset to
692754fe60SDimitry Andric   // address the stack frame. So a large call frame can cause poor codegen
702754fe60SDimitry Andric   // and may even makes it impossible to scavenge a register.
712754fe60SDimitry Andric   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
722754fe60SDimitry Andric     return false;
732754fe60SDimitry Andric 
742754fe60SDimitry Andric   return !MF.getFrameInfo()->hasVarSizedObjects();
752754fe60SDimitry Andric }
762754fe60SDimitry Andric 
772754fe60SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
782754fe60SDimitry Andric /// call frame pseudos can be simplified.  Unlike most targets, having a FP
792754fe60SDimitry Andric /// is not sufficient here since we still may reference some objects via SP
802754fe60SDimitry Andric /// even when FP is available in Thumb2 mode.
812754fe60SDimitry Andric bool
822754fe60SDimitry Andric ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
832754fe60SDimitry Andric   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
842754fe60SDimitry Andric }
852754fe60SDimitry Andric 
86dff0c46cSDimitry Andric static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
872754fe60SDimitry Andric   for (unsigned i = 0; CSRegs[i]; ++i)
882754fe60SDimitry Andric     if (Reg == CSRegs[i])
892754fe60SDimitry Andric       return true;
902754fe60SDimitry Andric   return false;
912754fe60SDimitry Andric }
922754fe60SDimitry Andric 
932754fe60SDimitry Andric static bool isCSRestore(MachineInstr *MI,
942754fe60SDimitry Andric                         const ARMBaseInstrInfo &TII,
95dff0c46cSDimitry Andric                         const uint16_t *CSRegs) {
962754fe60SDimitry Andric   // Integer spill area is handled with "pop".
972754fe60SDimitry Andric   if (MI->getOpcode() == ARM::LDMIA_RET ||
982754fe60SDimitry Andric       MI->getOpcode() == ARM::t2LDMIA_RET ||
992754fe60SDimitry Andric       MI->getOpcode() == ARM::LDMIA_UPD ||
1002754fe60SDimitry Andric       MI->getOpcode() == ARM::t2LDMIA_UPD ||
1012754fe60SDimitry Andric       MI->getOpcode() == ARM::VLDMDIA_UPD) {
1022754fe60SDimitry Andric     // The first two operands are predicates. The last two are
1032754fe60SDimitry Andric     // imp-def and imp-use of SP. Check everything in between.
1042754fe60SDimitry Andric     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
1052754fe60SDimitry Andric       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
1062754fe60SDimitry Andric         return false;
1072754fe60SDimitry Andric     return true;
1082754fe60SDimitry Andric   }
1096122f3e6SDimitry Andric   if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
1106122f3e6SDimitry Andric        MI->getOpcode() == ARM::LDR_POST_REG ||
1112754fe60SDimitry Andric        MI->getOpcode() == ARM::t2LDR_POST) &&
1122754fe60SDimitry Andric       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
1132754fe60SDimitry Andric       MI->getOperand(1).getReg() == ARM::SP)
1142754fe60SDimitry Andric     return true;
1152754fe60SDimitry Andric 
1162754fe60SDimitry Andric   return false;
1172754fe60SDimitry Andric }
1182754fe60SDimitry Andric 
1192754fe60SDimitry Andric static void
1202754fe60SDimitry Andric emitSPUpdate(bool isARM,
1212754fe60SDimitry Andric              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
1222754fe60SDimitry Andric              DebugLoc dl, const ARMBaseInstrInfo &TII,
1233b0f4066SDimitry Andric              int NumBytes, unsigned MIFlags = MachineInstr::NoFlags) {
1242754fe60SDimitry Andric   if (isARM)
1252754fe60SDimitry Andric     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1263b0f4066SDimitry Andric                             ARMCC::AL, 0, TII, MIFlags);
1272754fe60SDimitry Andric   else
1282754fe60SDimitry Andric     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1293b0f4066SDimitry Andric                            ARMCC::AL, 0, TII, MIFlags);
1302754fe60SDimitry Andric }
1312754fe60SDimitry Andric 
1322754fe60SDimitry Andric void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
1332754fe60SDimitry Andric   MachineBasicBlock &MBB = MF.front();
1342754fe60SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
1352754fe60SDimitry Andric   MachineFrameInfo  *MFI = MF.getFrameInfo();
1362754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1372754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
1382754fe60SDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1392754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
1402754fe60SDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1412754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
1422754fe60SDimitry Andric          "This emitPrologue does not support Thumb1!");
1432754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
1442754fe60SDimitry Andric   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1452754fe60SDimitry Andric   unsigned NumBytes = MFI->getStackSize();
1462754fe60SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1472754fe60SDimitry Andric   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1482754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1492754fe60SDimitry Andric 
1502754fe60SDimitry Andric   // Determine the sizes of each callee-save spill areas and record which frame
1512754fe60SDimitry Andric   // belongs to which callee-save spill areas.
1522754fe60SDimitry Andric   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1532754fe60SDimitry Andric   int FramePtrSpillFI = 0;
154dff0c46cSDimitry Andric   int D8SpillFI = 0;
155f8254f43SDimitry Andric 
1567ae0e2c9SDimitry Andric   // All calls are tail calls in GHC calling conv, and functions have no prologue/epilogue.
1577ae0e2c9SDimitry Andric   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
1587ae0e2c9SDimitry Andric     return;
1597ae0e2c9SDimitry Andric 
1602754fe60SDimitry Andric   // Allocate the vararg register save area. This is not counted in NumBytes.
1612754fe60SDimitry Andric   if (VARegSaveSize)
1623b0f4066SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize,
1633b0f4066SDimitry Andric                  MachineInstr::FrameSetup);
1642754fe60SDimitry Andric 
1652754fe60SDimitry Andric   if (!AFI->hasStackFrame()) {
1662754fe60SDimitry Andric     if (NumBytes != 0)
1673b0f4066SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
1683b0f4066SDimitry Andric                    MachineInstr::FrameSetup);
1692754fe60SDimitry Andric     return;
1702754fe60SDimitry Andric   }
1712754fe60SDimitry Andric 
1722754fe60SDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1732754fe60SDimitry Andric     unsigned Reg = CSI[i].getReg();
1742754fe60SDimitry Andric     int FI = CSI[i].getFrameIdx();
1752754fe60SDimitry Andric     switch (Reg) {
1762754fe60SDimitry Andric     case ARM::R4:
1772754fe60SDimitry Andric     case ARM::R5:
1782754fe60SDimitry Andric     case ARM::R6:
1792754fe60SDimitry Andric     case ARM::R7:
1802754fe60SDimitry Andric     case ARM::LR:
1812754fe60SDimitry Andric       if (Reg == FramePtr)
1822754fe60SDimitry Andric         FramePtrSpillFI = FI;
1832754fe60SDimitry Andric       AFI->addGPRCalleeSavedArea1Frame(FI);
1842754fe60SDimitry Andric       GPRCS1Size += 4;
1852754fe60SDimitry Andric       break;
1862754fe60SDimitry Andric     case ARM::R8:
1872754fe60SDimitry Andric     case ARM::R9:
1882754fe60SDimitry Andric     case ARM::R10:
1892754fe60SDimitry Andric     case ARM::R11:
1902754fe60SDimitry Andric       if (Reg == FramePtr)
1912754fe60SDimitry Andric         FramePtrSpillFI = FI;
192dff0c46cSDimitry Andric       if (STI.isTargetIOS()) {
1932754fe60SDimitry Andric         AFI->addGPRCalleeSavedArea2Frame(FI);
1942754fe60SDimitry Andric         GPRCS2Size += 4;
1952754fe60SDimitry Andric       } else {
1962754fe60SDimitry Andric         AFI->addGPRCalleeSavedArea1Frame(FI);
1972754fe60SDimitry Andric         GPRCS1Size += 4;
1982754fe60SDimitry Andric       }
1992754fe60SDimitry Andric       break;
2002754fe60SDimitry Andric     default:
201dff0c46cSDimitry Andric       // This is a DPR. Exclude the aligned DPRCS2 spills.
202dff0c46cSDimitry Andric       if (Reg == ARM::D8)
203dff0c46cSDimitry Andric         D8SpillFI = FI;
204dff0c46cSDimitry Andric       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) {
2052754fe60SDimitry Andric         AFI->addDPRCalleeSavedAreaFrame(FI);
2062754fe60SDimitry Andric         DPRCSSize += 8;
2072754fe60SDimitry Andric       }
2082754fe60SDimitry Andric     }
209dff0c46cSDimitry Andric   }
2102754fe60SDimitry Andric 
2112754fe60SDimitry Andric   // Move past area 1.
2122754fe60SDimitry Andric   if (GPRCS1Size > 0) MBBI++;
2132754fe60SDimitry Andric 
2142754fe60SDimitry Andric   // Set FP to point to the stack slot that contains the previous FP.
215dff0c46cSDimitry Andric   // For iOS, FP is R7, which has now been stored in spill area 1.
216dff0c46cSDimitry Andric   // Otherwise, if this is not iOS, all the callee-saved registers go
2172754fe60SDimitry Andric   // into spill area 1, including the FP in R11.  In either case, it is
2182754fe60SDimitry Andric   // now safe to emit this assignment.
2192754fe60SDimitry Andric   bool HasFP = hasFP(MF);
2202754fe60SDimitry Andric   if (HasFP) {
2212754fe60SDimitry Andric     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
2222754fe60SDimitry Andric     MachineInstrBuilder MIB =
2232754fe60SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
2243b0f4066SDimitry Andric       .addFrameIndex(FramePtrSpillFI).addImm(0)
2253b0f4066SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
2262754fe60SDimitry Andric     AddDefaultCC(AddDefaultPred(MIB));
2272754fe60SDimitry Andric   }
2282754fe60SDimitry Andric 
2292754fe60SDimitry Andric   // Move past area 2.
2302754fe60SDimitry Andric   if (GPRCS2Size > 0) MBBI++;
2312754fe60SDimitry Andric 
2322754fe60SDimitry Andric   // Determine starting offsets of spill areas.
2332754fe60SDimitry Andric   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
2342754fe60SDimitry Andric   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
2352754fe60SDimitry Andric   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
2362754fe60SDimitry Andric   if (HasFP)
2372754fe60SDimitry Andric     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
2382754fe60SDimitry Andric                                 NumBytes);
2392754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
2402754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
2412754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
2422754fe60SDimitry Andric 
2432754fe60SDimitry Andric   // Move past area 3.
244dd6029ffSDimitry Andric   if (DPRCSSize > 0) {
245dd6029ffSDimitry Andric     MBBI++;
246dd6029ffSDimitry Andric     // Since vpush register list cannot have gaps, there may be multiple vpush
247dd6029ffSDimitry Andric     // instructions in the prologue.
248dd6029ffSDimitry Andric     while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
249dd6029ffSDimitry Andric       MBBI++;
250dd6029ffSDimitry Andric   }
2512754fe60SDimitry Andric 
252dff0c46cSDimitry Andric   // Move past the aligned DPRCS2 area.
253dff0c46cSDimitry Andric   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
254dff0c46cSDimitry Andric     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
255dff0c46cSDimitry Andric     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
256dff0c46cSDimitry Andric     // leaves the stack pointer pointing to the DPRCS2 area.
257dff0c46cSDimitry Andric     //
258dff0c46cSDimitry Andric     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
259dff0c46cSDimitry Andric     NumBytes += MFI->getObjectOffset(D8SpillFI);
260dff0c46cSDimitry Andric   } else
2612754fe60SDimitry Andric     NumBytes = DPRCSOffset;
262dff0c46cSDimitry Andric 
2632754fe60SDimitry Andric   if (NumBytes) {
2642754fe60SDimitry Andric     // Adjust SP after all the callee-save spills.
2653b0f4066SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
2663b0f4066SDimitry Andric                  MachineInstr::FrameSetup);
2672754fe60SDimitry Andric     if (HasFP && isARM)
2682754fe60SDimitry Andric       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
2692754fe60SDimitry Andric       // Note it's not safe to do this in Thumb2 mode because it would have
2702754fe60SDimitry Andric       // taken two instructions:
2712754fe60SDimitry Andric       // mov sp, r7
2722754fe60SDimitry Andric       // sub sp, #24
2732754fe60SDimitry Andric       // If an interrupt is taken between the two instructions, then sp is in
2742754fe60SDimitry Andric       // an inconsistent state (pointing to the middle of callee-saved area).
2752754fe60SDimitry Andric       // The interrupt handler can end up clobbering the registers.
2762754fe60SDimitry Andric       AFI->setShouldRestoreSPFromFP(true);
2772754fe60SDimitry Andric   }
2782754fe60SDimitry Andric 
2792754fe60SDimitry Andric   if (STI.isTargetELF() && hasFP(MF))
2802754fe60SDimitry Andric     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
2812754fe60SDimitry Andric                              AFI->getFramePtrSpillOffset());
2822754fe60SDimitry Andric 
2832754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
2842754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
2852754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
2862754fe60SDimitry Andric 
2872754fe60SDimitry Andric   // If we need dynamic stack realignment, do it here. Be paranoid and make
2882754fe60SDimitry Andric   // sure if we also have VLAs, we have a base pointer for frame access.
289dff0c46cSDimitry Andric   // If aligned NEON registers were spilled, the stack has already been
290dff0c46cSDimitry Andric   // realigned.
291dff0c46cSDimitry Andric   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
2922754fe60SDimitry Andric     unsigned MaxAlign = MFI->getMaxAlignment();
2932754fe60SDimitry Andric     assert (!AFI->isThumb1OnlyFunction());
2942754fe60SDimitry Andric     if (!AFI->isThumbFunction()) {
2952754fe60SDimitry Andric       // Emit bic sp, sp, MaxAlign
2962754fe60SDimitry Andric       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
2972754fe60SDimitry Andric                                           TII.get(ARM::BICri), ARM::SP)
2982754fe60SDimitry Andric                                   .addReg(ARM::SP, RegState::Kill)
2992754fe60SDimitry Andric                                   .addImm(MaxAlign-1)));
3002754fe60SDimitry Andric     } else {
3012754fe60SDimitry Andric       // We cannot use sp as source/dest register here, thus we're emitting the
3022754fe60SDimitry Andric       // following sequence:
3032754fe60SDimitry Andric       // mov r4, sp
3042754fe60SDimitry Andric       // bic r4, r4, MaxAlign
3052754fe60SDimitry Andric       // mov sp, r4
3062754fe60SDimitry Andric       // FIXME: It will be better just to find spare register here.
30717a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
30817a519f9SDimitry Andric         .addReg(ARM::SP, RegState::Kill));
3092754fe60SDimitry Andric       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
3102754fe60SDimitry Andric                                           TII.get(ARM::t2BICri), ARM::R4)
3112754fe60SDimitry Andric                                   .addReg(ARM::R4, RegState::Kill)
3122754fe60SDimitry Andric                                   .addImm(MaxAlign-1)));
31317a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
31417a519f9SDimitry Andric         .addReg(ARM::R4, RegState::Kill));
3152754fe60SDimitry Andric     }
3162754fe60SDimitry Andric 
3172754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
3182754fe60SDimitry Andric   }
3192754fe60SDimitry Andric 
3202754fe60SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
3212754fe60SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
3222754fe60SDimitry Andric   // will be allocated after this, so we can still use the base pointer
3232754fe60SDimitry Andric   // to reference locals.
3243b0f4066SDimitry Andric   // FIXME: Clarify FrameSetup flags here.
3252754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF)) {
3262754fe60SDimitry Andric     if (isARM)
3272754fe60SDimitry Andric       BuildMI(MBB, MBBI, dl,
3282754fe60SDimitry Andric               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
3292754fe60SDimitry Andric         .addReg(ARM::SP)
3302754fe60SDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
3312754fe60SDimitry Andric     else
33217a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
33317a519f9SDimitry Andric                              RegInfo->getBaseRegister())
33417a519f9SDimitry Andric         .addReg(ARM::SP));
3352754fe60SDimitry Andric   }
3362754fe60SDimitry Andric 
3372754fe60SDimitry Andric   // If the frame has variable sized objects then the epilogue must restore
3382754fe60SDimitry Andric   // the sp from fp. We can assume there's an FP here since hasFP already
3392754fe60SDimitry Andric   // checks for hasVarSizedObjects.
3402754fe60SDimitry Andric   if (MFI->hasVarSizedObjects())
3412754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
3422754fe60SDimitry Andric }
3432754fe60SDimitry Andric 
3442754fe60SDimitry Andric void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
3452754fe60SDimitry Andric                                     MachineBasicBlock &MBB) const {
3462754fe60SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
347dff0c46cSDimitry Andric   assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
3482754fe60SDimitry Andric   unsigned RetOpcode = MBBI->getOpcode();
3492754fe60SDimitry Andric   DebugLoc dl = MBBI->getDebugLoc();
3502754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
3512754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3522754fe60SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
3532754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
3542754fe60SDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
3552754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
3562754fe60SDimitry Andric          "This emitEpilogue does not support Thumb1!");
3572754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
3582754fe60SDimitry Andric 
3592754fe60SDimitry Andric   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
3602754fe60SDimitry Andric   int NumBytes = (int)MFI->getStackSize();
3612754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
3622754fe60SDimitry Andric 
3637ae0e2c9SDimitry Andric   // All calls are tail calls in GHC calling conv, and functions have no prologue/epilogue.
3647ae0e2c9SDimitry Andric   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
3657ae0e2c9SDimitry Andric     return;
3667ae0e2c9SDimitry Andric 
3672754fe60SDimitry Andric   if (!AFI->hasStackFrame()) {
3682754fe60SDimitry Andric     if (NumBytes != 0)
3692754fe60SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
3702754fe60SDimitry Andric   } else {
3712754fe60SDimitry Andric     // Unwind MBBI to point to first LDR / VLDRD.
372dff0c46cSDimitry Andric     const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
3732754fe60SDimitry Andric     if (MBBI != MBB.begin()) {
3742754fe60SDimitry Andric       do
3752754fe60SDimitry Andric         --MBBI;
3762754fe60SDimitry Andric       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
3772754fe60SDimitry Andric       if (!isCSRestore(MBBI, TII, CSRegs))
3782754fe60SDimitry Andric         ++MBBI;
3792754fe60SDimitry Andric     }
3802754fe60SDimitry Andric 
3812754fe60SDimitry Andric     // Move SP to start of FP callee save spill area.
3822754fe60SDimitry Andric     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
3832754fe60SDimitry Andric                  AFI->getGPRCalleeSavedArea2Size() +
3842754fe60SDimitry Andric                  AFI->getDPRCalleeSavedAreaSize());
3852754fe60SDimitry Andric 
3862754fe60SDimitry Andric     // Reset SP based on frame pointer only if the stack frame extends beyond
3872754fe60SDimitry Andric     // frame pointer stack slot or target is ELF and the function has FP.
3882754fe60SDimitry Andric     if (AFI->shouldRestoreSPFromFP()) {
3892754fe60SDimitry Andric       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
3902754fe60SDimitry Andric       if (NumBytes) {
3912754fe60SDimitry Andric         if (isARM)
3922754fe60SDimitry Andric           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
3932754fe60SDimitry Andric                                   ARMCC::AL, 0, TII);
3942754fe60SDimitry Andric         else {
3952754fe60SDimitry Andric           // It's not possible to restore SP from FP in a single instruction.
396dff0c46cSDimitry Andric           // For iOS, this looks like:
3972754fe60SDimitry Andric           // mov sp, r7
3982754fe60SDimitry Andric           // sub sp, #24
3992754fe60SDimitry Andric           // This is bad, if an interrupt is taken after the mov, sp is in an
4002754fe60SDimitry Andric           // inconsistent state.
4012754fe60SDimitry Andric           // Use the first callee-saved register as a scratch register.
4022754fe60SDimitry Andric           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
4032754fe60SDimitry Andric                  "No scratch register to restore SP from FP!");
4042754fe60SDimitry Andric           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
4052754fe60SDimitry Andric                                  ARMCC::AL, 0, TII);
40617a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
40717a519f9SDimitry Andric                                  ARM::SP)
40817a519f9SDimitry Andric             .addReg(ARM::R4));
4092754fe60SDimitry Andric         }
4102754fe60SDimitry Andric       } else {
4112754fe60SDimitry Andric         // Thumb2 or ARM.
4122754fe60SDimitry Andric         if (isARM)
4132754fe60SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
4142754fe60SDimitry Andric             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
4152754fe60SDimitry Andric         else
41617a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
41717a519f9SDimitry Andric                                  ARM::SP)
41817a519f9SDimitry Andric             .addReg(FramePtr));
4192754fe60SDimitry Andric       }
4202754fe60SDimitry Andric     } else if (NumBytes)
4212754fe60SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
4222754fe60SDimitry Andric 
4232754fe60SDimitry Andric     // Increment past our save areas.
424dd6029ffSDimitry Andric     if (AFI->getDPRCalleeSavedAreaSize()) {
425dd6029ffSDimitry Andric       MBBI++;
426dd6029ffSDimitry Andric       // Since vpop register list cannot have gaps, there may be multiple vpop
427dd6029ffSDimitry Andric       // instructions in the epilogue.
428dd6029ffSDimitry Andric       while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
429dd6029ffSDimitry Andric         MBBI++;
430dd6029ffSDimitry Andric     }
4312754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
4322754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
4332754fe60SDimitry Andric   }
4342754fe60SDimitry Andric 
435dff0c46cSDimitry Andric   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
4362754fe60SDimitry Andric     // Tail call return: adjust the stack pointer and jump to callee.
4372754fe60SDimitry Andric     MBBI = MBB.getLastNonDebugInstr();
4382754fe60SDimitry Andric     MachineOperand &JumpTarget = MBBI->getOperand(0);
4392754fe60SDimitry Andric 
4402754fe60SDimitry Andric     // Jump to label or value in register.
441dff0c46cSDimitry Andric     if (RetOpcode == ARM::TCRETURNdi) {
442dff0c46cSDimitry Andric       unsigned TCOpcode = STI.isThumb() ?
443dff0c46cSDimitry Andric                (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
444dff0c46cSDimitry Andric                ARM::TAILJMPd;
4452754fe60SDimitry Andric       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
4462754fe60SDimitry Andric       if (JumpTarget.isGlobal())
4472754fe60SDimitry Andric         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
4482754fe60SDimitry Andric                              JumpTarget.getTargetFlags());
4492754fe60SDimitry Andric       else {
4502754fe60SDimitry Andric         assert(JumpTarget.isSymbol());
4512754fe60SDimitry Andric         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
4522754fe60SDimitry Andric                               JumpTarget.getTargetFlags());
4532754fe60SDimitry Andric       }
4546122f3e6SDimitry Andric 
4556122f3e6SDimitry Andric       // Add the default predicate in Thumb mode.
4566122f3e6SDimitry Andric       if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
4572754fe60SDimitry Andric     } else if (RetOpcode == ARM::TCRETURNri) {
4583b0f4066SDimitry Andric       BuildMI(MBB, MBBI, dl,
4593b0f4066SDimitry Andric               TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
4602754fe60SDimitry Andric         addReg(JumpTarget.getReg(), RegState::Kill);
4612754fe60SDimitry Andric     }
4622754fe60SDimitry Andric 
4632754fe60SDimitry Andric     MachineInstr *NewMI = prior(MBBI);
4642754fe60SDimitry Andric     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
4652754fe60SDimitry Andric       NewMI->addOperand(MBBI->getOperand(i));
4662754fe60SDimitry Andric 
4672754fe60SDimitry Andric     // Delete the pseudo instruction TCRETURN.
4682754fe60SDimitry Andric     MBB.erase(MBBI);
46917a519f9SDimitry Andric     MBBI = NewMI;
4702754fe60SDimitry Andric   }
4712754fe60SDimitry Andric 
4722754fe60SDimitry Andric   if (VARegSaveSize)
4732754fe60SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
4742754fe60SDimitry Andric }
4752754fe60SDimitry Andric 
4762754fe60SDimitry Andric /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
4772754fe60SDimitry Andric /// debug info.  It's the same as what we use for resolving the code-gen
4782754fe60SDimitry Andric /// references for now.  FIXME: This can go wrong when references are
4792754fe60SDimitry Andric /// SP-relative and simple call frames aren't used.
4802754fe60SDimitry Andric int
4812754fe60SDimitry Andric ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
4822754fe60SDimitry Andric                                          unsigned &FrameReg) const {
4832754fe60SDimitry Andric   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
4842754fe60SDimitry Andric }
4852754fe60SDimitry Andric 
4862754fe60SDimitry Andric int
4872754fe60SDimitry Andric ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
4883b0f4066SDimitry Andric                                              int FI, unsigned &FrameReg,
4892754fe60SDimitry Andric                                              int SPAdj) const {
4902754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
4912754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
4922754fe60SDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
4932754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4942754fe60SDimitry Andric   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
4952754fe60SDimitry Andric   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
4962754fe60SDimitry Andric   bool isFixed = MFI->isFixedObjectIndex(FI);
4972754fe60SDimitry Andric 
4982754fe60SDimitry Andric   FrameReg = ARM::SP;
4992754fe60SDimitry Andric   Offset += SPAdj;
5002754fe60SDimitry Andric   if (AFI->isGPRCalleeSavedArea1Frame(FI))
5012754fe60SDimitry Andric     return Offset - AFI->getGPRCalleeSavedArea1Offset();
5022754fe60SDimitry Andric   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
5032754fe60SDimitry Andric     return Offset - AFI->getGPRCalleeSavedArea2Offset();
5042754fe60SDimitry Andric   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
5052754fe60SDimitry Andric     return Offset - AFI->getDPRCalleeSavedAreaOffset();
5062754fe60SDimitry Andric 
507dff0c46cSDimitry Andric   // SP can move around if there are allocas.  We may also lose track of SP
508dff0c46cSDimitry Andric   // when emergency spilling inside a non-reserved call frame setup.
509dff0c46cSDimitry Andric   bool hasMovingSP = !hasReservedCallFrame(MF);
510dff0c46cSDimitry Andric 
5112754fe60SDimitry Andric   // When dynamically realigning the stack, use the frame pointer for
5122754fe60SDimitry Andric   // parameters, and the stack/base pointer for locals.
5132754fe60SDimitry Andric   if (RegInfo->needsStackRealignment(MF)) {
5142754fe60SDimitry Andric     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
5152754fe60SDimitry Andric     if (isFixed) {
5162754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
5172754fe60SDimitry Andric       Offset = FPOffset;
518dff0c46cSDimitry Andric     } else if (hasMovingSP) {
5192754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) &&
5202754fe60SDimitry Andric              "VLAs and dynamic stack alignment, but missing base pointer!");
5212754fe60SDimitry Andric       FrameReg = RegInfo->getBaseRegister();
5222754fe60SDimitry Andric     }
5232754fe60SDimitry Andric     return Offset;
5242754fe60SDimitry Andric   }
5252754fe60SDimitry Andric 
5262754fe60SDimitry Andric   // If there is a frame pointer, use it when we can.
5272754fe60SDimitry Andric   if (hasFP(MF) && AFI->hasStackFrame()) {
5282754fe60SDimitry Andric     // Use frame pointer to reference fixed objects. Use it for locals if
5292754fe60SDimitry Andric     // there are VLAs (and thus the SP isn't reliable as a base).
530dff0c46cSDimitry Andric     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
5312754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
5322754fe60SDimitry Andric       return FPOffset;
533dff0c46cSDimitry Andric     } else if (hasMovingSP) {
5342754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
5353b0f4066SDimitry Andric       if (AFI->isThumb2Function()) {
5362754fe60SDimitry Andric         // Try to use the frame pointer if we can, else use the base pointer
5372754fe60SDimitry Andric         // since it's available. This is handy for the emergency spill slot, in
5382754fe60SDimitry Andric         // particular.
5392754fe60SDimitry Andric         if (FPOffset >= -255 && FPOffset < 0) {
5402754fe60SDimitry Andric           FrameReg = RegInfo->getFrameRegister(MF);
5412754fe60SDimitry Andric           return FPOffset;
5422754fe60SDimitry Andric         }
5433b0f4066SDimitry Andric       }
5442754fe60SDimitry Andric     } else if (AFI->isThumb2Function()) {
5453b0f4066SDimitry Andric       // Use  add <rd>, sp, #<imm8>
5463b0f4066SDimitry Andric       //      ldr <rd>, [sp, #<imm8>]
5473b0f4066SDimitry Andric       // if at all possible to save space.
5483b0f4066SDimitry Andric       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
5493b0f4066SDimitry Andric         return Offset;
5502754fe60SDimitry Andric       // In Thumb2 mode, the negative offset is very limited. Try to avoid
5513b0f4066SDimitry Andric       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
5522754fe60SDimitry Andric       if (FPOffset >= -255 && FPOffset < 0) {
5532754fe60SDimitry Andric         FrameReg = RegInfo->getFrameRegister(MF);
5542754fe60SDimitry Andric         return FPOffset;
5552754fe60SDimitry Andric       }
5562754fe60SDimitry Andric     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
5572754fe60SDimitry Andric       // Otherwise, use SP or FP, whichever is closer to the stack slot.
5582754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
5592754fe60SDimitry Andric       return FPOffset;
5602754fe60SDimitry Andric     }
5612754fe60SDimitry Andric   }
5622754fe60SDimitry Andric   // Use the base pointer if we have one.
5632754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
5642754fe60SDimitry Andric     FrameReg = RegInfo->getBaseRegister();
5652754fe60SDimitry Andric   return Offset;
5662754fe60SDimitry Andric }
5672754fe60SDimitry Andric 
5682754fe60SDimitry Andric int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
5692754fe60SDimitry Andric                                           int FI) const {
5702754fe60SDimitry Andric   unsigned FrameReg;
5712754fe60SDimitry Andric   return getFrameIndexReference(MF, FI, FrameReg);
5722754fe60SDimitry Andric }
5732754fe60SDimitry Andric 
5742754fe60SDimitry Andric void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
5752754fe60SDimitry Andric                                     MachineBasicBlock::iterator MI,
5762754fe60SDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
5772754fe60SDimitry Andric                                     unsigned StmOpc, unsigned StrOpc,
5782754fe60SDimitry Andric                                     bool NoGap,
5793b0f4066SDimitry Andric                                     bool(*Func)(unsigned, bool),
580dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
5813b0f4066SDimitry Andric                                     unsigned MIFlags) const {
5822754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
5832754fe60SDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
5842754fe60SDimitry Andric 
5852754fe60SDimitry Andric   DebugLoc DL;
5862754fe60SDimitry Andric   if (MI != MBB.end()) DL = MI->getDebugLoc();
5872754fe60SDimitry Andric 
5882754fe60SDimitry Andric   SmallVector<std::pair<unsigned,bool>, 4> Regs;
5892754fe60SDimitry Andric   unsigned i = CSI.size();
5902754fe60SDimitry Andric   while (i != 0) {
5912754fe60SDimitry Andric     unsigned LastReg = 0;
5922754fe60SDimitry Andric     for (; i != 0; --i) {
5932754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
594dff0c46cSDimitry Andric       if (!(Func)(Reg, STI.isTargetIOS())) continue;
595dff0c46cSDimitry Andric 
596dff0c46cSDimitry Andric       // D-registers in the aligned area DPRCS2 are NOT spilled here.
597dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
598dff0c46cSDimitry Andric         continue;
5992754fe60SDimitry Andric 
6002754fe60SDimitry Andric       // Add the callee-saved register as live-in unless it's LR and
6012754fe60SDimitry Andric       // @llvm.returnaddress is called. If LR is returned for
6022754fe60SDimitry Andric       // @llvm.returnaddress then it's already added to the function and
6032754fe60SDimitry Andric       // entry block live-in sets.
6042754fe60SDimitry Andric       bool isKill = true;
6052754fe60SDimitry Andric       if (Reg == ARM::LR) {
6062754fe60SDimitry Andric         if (MF.getFrameInfo()->isReturnAddressTaken() &&
6072754fe60SDimitry Andric             MF.getRegInfo().isLiveIn(Reg))
6082754fe60SDimitry Andric           isKill = false;
6092754fe60SDimitry Andric       }
6102754fe60SDimitry Andric 
6112754fe60SDimitry Andric       if (isKill)
6122754fe60SDimitry Andric         MBB.addLiveIn(Reg);
6132754fe60SDimitry Andric 
6142754fe60SDimitry Andric       // If NoGap is true, push consecutive registers and then leave the rest
6152754fe60SDimitry Andric       // for other instructions. e.g.
6162754fe60SDimitry Andric       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
6172754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
6182754fe60SDimitry Andric         break;
6192754fe60SDimitry Andric       LastReg = Reg;
6202754fe60SDimitry Andric       Regs.push_back(std::make_pair(Reg, isKill));
6212754fe60SDimitry Andric     }
6222754fe60SDimitry Andric 
6232754fe60SDimitry Andric     if (Regs.empty())
6242754fe60SDimitry Andric       continue;
6252754fe60SDimitry Andric     if (Regs.size() > 1 || StrOpc== 0) {
6262754fe60SDimitry Andric       MachineInstrBuilder MIB =
6272754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
6283b0f4066SDimitry Andric                        .addReg(ARM::SP).setMIFlags(MIFlags));
6292754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
6302754fe60SDimitry Andric         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
6312754fe60SDimitry Andric     } else if (Regs.size() == 1) {
6322754fe60SDimitry Andric       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
6332754fe60SDimitry Andric                                         ARM::SP)
6342754fe60SDimitry Andric         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
6356122f3e6SDimitry Andric         .addReg(ARM::SP).setMIFlags(MIFlags)
6366122f3e6SDimitry Andric         .addImm(-4);
6372754fe60SDimitry Andric       AddDefaultPred(MIB);
6382754fe60SDimitry Andric     }
6392754fe60SDimitry Andric     Regs.clear();
6402754fe60SDimitry Andric   }
6412754fe60SDimitry Andric }
6422754fe60SDimitry Andric 
6432754fe60SDimitry Andric void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
6442754fe60SDimitry Andric                                    MachineBasicBlock::iterator MI,
6452754fe60SDimitry Andric                                    const std::vector<CalleeSavedInfo> &CSI,
6462754fe60SDimitry Andric                                    unsigned LdmOpc, unsigned LdrOpc,
6472754fe60SDimitry Andric                                    bool isVarArg, bool NoGap,
648dff0c46cSDimitry Andric                                    bool(*Func)(unsigned, bool),
649dff0c46cSDimitry Andric                                    unsigned NumAlignedDPRCS2Regs) const {
6502754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
6512754fe60SDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
6522754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
6532754fe60SDimitry Andric   DebugLoc DL = MI->getDebugLoc();
6542754fe60SDimitry Andric   unsigned RetOpcode = MI->getOpcode();
6552754fe60SDimitry Andric   bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
656dff0c46cSDimitry Andric                      RetOpcode == ARM::TCRETURNri);
6572754fe60SDimitry Andric 
6582754fe60SDimitry Andric   SmallVector<unsigned, 4> Regs;
6592754fe60SDimitry Andric   unsigned i = CSI.size();
6602754fe60SDimitry Andric   while (i != 0) {
6612754fe60SDimitry Andric     unsigned LastReg = 0;
6622754fe60SDimitry Andric     bool DeleteRet = false;
6632754fe60SDimitry Andric     for (; i != 0; --i) {
6642754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
665dff0c46cSDimitry Andric       if (!(Func)(Reg, STI.isTargetIOS())) continue;
666dff0c46cSDimitry Andric 
667dff0c46cSDimitry Andric       // The aligned reloads from area DPRCS2 are not inserted here.
668dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
669dff0c46cSDimitry Andric         continue;
6702754fe60SDimitry Andric 
6712754fe60SDimitry Andric       if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
6722754fe60SDimitry Andric         Reg = ARM::PC;
6732754fe60SDimitry Andric         LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
6742754fe60SDimitry Andric         // Fold the return instruction into the LDM.
6752754fe60SDimitry Andric         DeleteRet = true;
6762754fe60SDimitry Andric       }
6772754fe60SDimitry Andric 
6782754fe60SDimitry Andric       // If NoGap is true, pop consecutive registers and then leave the rest
6792754fe60SDimitry Andric       // for other instructions. e.g.
6802754fe60SDimitry Andric       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
6812754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
6822754fe60SDimitry Andric         break;
6832754fe60SDimitry Andric 
6842754fe60SDimitry Andric       LastReg = Reg;
6852754fe60SDimitry Andric       Regs.push_back(Reg);
6862754fe60SDimitry Andric     }
6872754fe60SDimitry Andric 
6882754fe60SDimitry Andric     if (Regs.empty())
6892754fe60SDimitry Andric       continue;
6902754fe60SDimitry Andric     if (Regs.size() > 1 || LdrOpc == 0) {
6912754fe60SDimitry Andric       MachineInstrBuilder MIB =
6922754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
6932754fe60SDimitry Andric                        .addReg(ARM::SP));
6942754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
6952754fe60SDimitry Andric         MIB.addReg(Regs[i], getDefRegState(true));
6966122f3e6SDimitry Andric       if (DeleteRet) {
6976122f3e6SDimitry Andric         MIB->copyImplicitOps(&*MI);
6982754fe60SDimitry Andric         MI->eraseFromParent();
6996122f3e6SDimitry Andric       }
7002754fe60SDimitry Andric       MI = MIB;
7012754fe60SDimitry Andric     } else if (Regs.size() == 1) {
7022754fe60SDimitry Andric       // If we adjusted the reg to PC from LR above, switch it back here. We
7032754fe60SDimitry Andric       // only do that for LDM.
7042754fe60SDimitry Andric       if (Regs[0] == ARM::PC)
7052754fe60SDimitry Andric         Regs[0] = ARM::LR;
7062754fe60SDimitry Andric       MachineInstrBuilder MIB =
7072754fe60SDimitry Andric         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
7082754fe60SDimitry Andric           .addReg(ARM::SP, RegState::Define)
7092754fe60SDimitry Andric           .addReg(ARM::SP);
7102754fe60SDimitry Andric       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
7112754fe60SDimitry Andric       // that refactoring is complete (eventually).
7126122f3e6SDimitry Andric       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
7132754fe60SDimitry Andric         MIB.addReg(0);
7142754fe60SDimitry Andric         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
7152754fe60SDimitry Andric       } else
7162754fe60SDimitry Andric         MIB.addImm(4);
7172754fe60SDimitry Andric       AddDefaultPred(MIB);
7182754fe60SDimitry Andric     }
7192754fe60SDimitry Andric     Regs.clear();
7202754fe60SDimitry Andric   }
7212754fe60SDimitry Andric }
7222754fe60SDimitry Andric 
723dff0c46cSDimitry Andric /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
724dff0c46cSDimitry Andric /// starting from d8.  Also insert stack realignment code and leave the stack
725dff0c46cSDimitry Andric /// pointer pointing to the d8 spill slot.
726dff0c46cSDimitry Andric static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
727dff0c46cSDimitry Andric                                     MachineBasicBlock::iterator MI,
728dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
729dff0c46cSDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
730dff0c46cSDimitry Andric                                     const TargetRegisterInfo *TRI) {
731dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
732dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
733dff0c46cSDimitry Andric   DebugLoc DL = MI->getDebugLoc();
734dff0c46cSDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
735dff0c46cSDimitry Andric   MachineFrameInfo &MFI = *MF.getFrameInfo();
736dff0c46cSDimitry Andric 
737dff0c46cSDimitry Andric   // Mark the D-register spill slots as properly aligned.  Since MFI computes
738dff0c46cSDimitry Andric   // stack slot layout backwards, this can actually mean that the d-reg stack
739dff0c46cSDimitry Andric   // slot offsets can be wrong. The offset for d8 will always be correct.
740dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
741dff0c46cSDimitry Andric     unsigned DNum = CSI[i].getReg() - ARM::D8;
742dff0c46cSDimitry Andric     if (DNum >= 8)
743dff0c46cSDimitry Andric       continue;
744dff0c46cSDimitry Andric     int FI = CSI[i].getFrameIdx();
745dff0c46cSDimitry Andric     // The even-numbered registers will be 16-byte aligned, the odd-numbered
746dff0c46cSDimitry Andric     // registers will be 8-byte aligned.
747dff0c46cSDimitry Andric     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
748dff0c46cSDimitry Andric 
749dff0c46cSDimitry Andric     // The stack slot for D8 needs to be maximally aligned because this is
750dff0c46cSDimitry Andric     // actually the point where we align the stack pointer.  MachineFrameInfo
751dff0c46cSDimitry Andric     // computes all offsets relative to the incoming stack pointer which is a
752dff0c46cSDimitry Andric     // bit weird when realigning the stack.  Any extra padding for this
753dff0c46cSDimitry Andric     // over-alignment is not realized because the code inserted below adjusts
754dff0c46cSDimitry Andric     // the stack pointer by numregs * 8 before aligning the stack pointer.
755dff0c46cSDimitry Andric     if (DNum == 0)
756dff0c46cSDimitry Andric       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
757dff0c46cSDimitry Andric   }
758dff0c46cSDimitry Andric 
759dff0c46cSDimitry Andric   // Move the stack pointer to the d8 spill slot, and align it at the same
760dff0c46cSDimitry Andric   // time. Leave the stack slot address in the scratch register r4.
761dff0c46cSDimitry Andric   //
762dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
763dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
764dff0c46cSDimitry Andric   //   mov sp, r4
765dff0c46cSDimitry Andric   //
766dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
767dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
768dff0c46cSDimitry Andric   AFI->setShouldRestoreSPFromFP(true);
769dff0c46cSDimitry Andric 
770dff0c46cSDimitry Andric   // sub r4, sp, #numregs * 8
771dff0c46cSDimitry Andric   // The immediate is <= 64, so it doesn't need any special encoding.
772dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
773dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
774dff0c46cSDimitry Andric                               .addReg(ARM::SP)
775dff0c46cSDimitry Andric                               .addImm(8 * NumAlignedDPRCS2Regs)));
776dff0c46cSDimitry Andric 
777dff0c46cSDimitry Andric   // bic r4, r4, #align-1
778dff0c46cSDimitry Andric   Opc = isThumb ? ARM::t2BICri : ARM::BICri;
779dff0c46cSDimitry Andric   unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
780dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
781dff0c46cSDimitry Andric                               .addReg(ARM::R4, RegState::Kill)
782dff0c46cSDimitry Andric                               .addImm(MaxAlign - 1)));
783dff0c46cSDimitry Andric 
784dff0c46cSDimitry Andric   // mov sp, r4
785dff0c46cSDimitry Andric   // The stack pointer must be adjusted before spilling anything, otherwise
786dff0c46cSDimitry Andric   // the stack slots could be clobbered by an interrupt handler.
787dff0c46cSDimitry Andric   // Leave r4 live, it is used below.
788dff0c46cSDimitry Andric   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
789dff0c46cSDimitry Andric   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
790dff0c46cSDimitry Andric                             .addReg(ARM::R4);
791dff0c46cSDimitry Andric   MIB = AddDefaultPred(MIB);
792dff0c46cSDimitry Andric   if (!isThumb)
793dff0c46cSDimitry Andric     AddDefaultCC(MIB);
794dff0c46cSDimitry Andric 
795dff0c46cSDimitry Andric   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
796dff0c46cSDimitry Andric   // r4 holds the stack slot address.
797dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
798dff0c46cSDimitry Andric 
799dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
800dff0c46cSDimitry Andric   // The writeback is only needed when emitting two vst1.64 instructions.
801dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
802dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
8037ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
804dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
805dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
806dff0c46cSDimitry Andric                            ARM::R4)
807dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
808dff0c46cSDimitry Andric                    .addReg(NextReg)
809dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
810dff0c46cSDimitry Andric     NextReg += 4;
811dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
812dff0c46cSDimitry Andric   }
813dff0c46cSDimitry Andric 
814dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
815dff0c46cSDimitry Andric   // register to be spilled.
816dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
817dff0c46cSDimitry Andric 
818dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
819dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
820dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
8217ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
822dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
823dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
824dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(NextReg)
825dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
826dff0c46cSDimitry Andric     NextReg += 4;
827dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
828dff0c46cSDimitry Andric   }
829dff0c46cSDimitry Andric 
830dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 2 d-regs.
831dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
832dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
8337ae0e2c9SDimitry Andric                                                &ARM::QPRRegClass);
834dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
835dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
836dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(SupReg));
837dff0c46cSDimitry Andric     NextReg += 2;
838dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
839dff0c46cSDimitry Andric   }
840dff0c46cSDimitry Andric 
841dff0c46cSDimitry Andric   // Finally, use a vanilla vstr.64 for the odd last register.
842dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs) {
843dff0c46cSDimitry Andric     MBB.addLiveIn(NextReg);
844dff0c46cSDimitry Andric     // vstr.64 uses addrmode5 which has an offset scale of 4.
845dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
846dff0c46cSDimitry Andric                    .addReg(NextReg)
847dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
848dff0c46cSDimitry Andric   }
849dff0c46cSDimitry Andric 
850dff0c46cSDimitry Andric   // The last spill instruction inserted should kill the scratch register r4.
851dff0c46cSDimitry Andric   llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
852dff0c46cSDimitry Andric }
853dff0c46cSDimitry Andric 
854dff0c46cSDimitry Andric /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
855dff0c46cSDimitry Andric /// iterator to the following instruction.
856dff0c46cSDimitry Andric static MachineBasicBlock::iterator
857dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
858dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs) {
859dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
860dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
861dff0c46cSDimitry Andric   //   mov sp, r4
862dff0c46cSDimitry Andric   ++MI; ++MI; ++MI;
863dff0c46cSDimitry Andric   assert(MI->mayStore() && "Expecting spill instruction");
864dff0c46cSDimitry Andric 
865dff0c46cSDimitry Andric   // These switches all fall through.
866dff0c46cSDimitry Andric   switch(NumAlignedDPRCS2Regs) {
867dff0c46cSDimitry Andric   case 7:
868dff0c46cSDimitry Andric     ++MI;
869dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
870dff0c46cSDimitry Andric   default:
871dff0c46cSDimitry Andric     ++MI;
872dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
873dff0c46cSDimitry Andric   case 1:
874dff0c46cSDimitry Andric   case 2:
875dff0c46cSDimitry Andric   case 4:
876dff0c46cSDimitry Andric     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
877dff0c46cSDimitry Andric     ++MI;
878dff0c46cSDimitry Andric   }
879dff0c46cSDimitry Andric   return MI;
880dff0c46cSDimitry Andric }
881dff0c46cSDimitry Andric 
882dff0c46cSDimitry Andric /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
883dff0c46cSDimitry Andric /// starting from d8.  These instructions are assumed to execute while the
884dff0c46cSDimitry Andric /// stack is still aligned, unlike the code inserted by emitPopInst.
885dff0c46cSDimitry Andric static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
886dff0c46cSDimitry Andric                                       MachineBasicBlock::iterator MI,
887dff0c46cSDimitry Andric                                       unsigned NumAlignedDPRCS2Regs,
888dff0c46cSDimitry Andric                                       const std::vector<CalleeSavedInfo> &CSI,
889dff0c46cSDimitry Andric                                       const TargetRegisterInfo *TRI) {
890dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
891dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
892dff0c46cSDimitry Andric   DebugLoc DL = MI->getDebugLoc();
893dff0c46cSDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
894dff0c46cSDimitry Andric 
895dff0c46cSDimitry Andric   // Find the frame index assigned to d8.
896dff0c46cSDimitry Andric   int D8SpillFI = 0;
897dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
898dff0c46cSDimitry Andric     if (CSI[i].getReg() == ARM::D8) {
899dff0c46cSDimitry Andric       D8SpillFI = CSI[i].getFrameIdx();
900dff0c46cSDimitry Andric       break;
901dff0c46cSDimitry Andric     }
902dff0c46cSDimitry Andric 
903dff0c46cSDimitry Andric   // Materialize the address of the d8 spill slot into the scratch register r4.
904dff0c46cSDimitry Andric   // This can be fairly complicated if the stack frame is large, so just use
905dff0c46cSDimitry Andric   // the normal frame index elimination mechanism to do it.  This code runs as
906dff0c46cSDimitry Andric   // the initial part of the epilog where the stack and base pointers haven't
907dff0c46cSDimitry Andric   // been changed yet.
908dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
909dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
910dff0c46cSDimitry Andric 
911dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
912dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
913dff0c46cSDimitry Andric                               .addFrameIndex(D8SpillFI).addImm(0)));
914dff0c46cSDimitry Andric 
915dff0c46cSDimitry Andric   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
916dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
917dff0c46cSDimitry Andric 
918dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
919dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
920dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
9217ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
922dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
923dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Define)
924dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
925dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
926dff0c46cSDimitry Andric     NextReg += 4;
927dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
928dff0c46cSDimitry Andric   }
929dff0c46cSDimitry Andric 
930dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
931dff0c46cSDimitry Andric   // register to be spilled.
932dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
933dff0c46cSDimitry Andric 
934dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
935dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
936dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
9377ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
938dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
939dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16)
940dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
941dff0c46cSDimitry Andric     NextReg += 4;
942dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
943dff0c46cSDimitry Andric   }
944dff0c46cSDimitry Andric 
945dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 2 d-regs.
946dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
947dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
9487ae0e2c9SDimitry Andric                                                &ARM::QPRRegClass);
949dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
950dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16));
951dff0c46cSDimitry Andric     NextReg += 2;
952dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
953dff0c46cSDimitry Andric   }
954dff0c46cSDimitry Andric 
955dff0c46cSDimitry Andric   // Finally, use a vanilla vldr.64 for the remaining odd register.
956dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
957dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
958dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
959dff0c46cSDimitry Andric 
960dff0c46cSDimitry Andric   // Last store kills r4.
961dff0c46cSDimitry Andric   llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
962dff0c46cSDimitry Andric }
963dff0c46cSDimitry Andric 
9642754fe60SDimitry Andric bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
9652754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
9662754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
9672754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
9682754fe60SDimitry Andric   if (CSI.empty())
9692754fe60SDimitry Andric     return false;
9702754fe60SDimitry Andric 
9712754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
9722754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
9732754fe60SDimitry Andric 
9742754fe60SDimitry Andric   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
9756122f3e6SDimitry Andric   unsigned PushOneOpc = AFI->isThumbFunction() ?
9766122f3e6SDimitry Andric     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
9772754fe60SDimitry Andric   unsigned FltOpc = ARM::VSTMDDB_UPD;
978dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
979dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
9803b0f4066SDimitry Andric                MachineInstr::FrameSetup);
981dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
9823b0f4066SDimitry Andric                MachineInstr::FrameSetup);
9833b0f4066SDimitry Andric   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
984dff0c46cSDimitry Andric                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
985dff0c46cSDimitry Andric 
986dff0c46cSDimitry Andric   // The code above does not insert spill code for the aligned DPRCS2 registers.
987dff0c46cSDimitry Andric   // The stack realignment code will be inserted between the push instructions
988dff0c46cSDimitry Andric   // and these spills.
989dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
990dff0c46cSDimitry Andric     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
9912754fe60SDimitry Andric 
9922754fe60SDimitry Andric   return true;
9932754fe60SDimitry Andric }
9942754fe60SDimitry Andric 
9952754fe60SDimitry Andric bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
9962754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
9972754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
9982754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
9992754fe60SDimitry Andric   if (CSI.empty())
10002754fe60SDimitry Andric     return false;
10012754fe60SDimitry Andric 
10022754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
10032754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
10042754fe60SDimitry Andric   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
1005dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1006dff0c46cSDimitry Andric 
1007dff0c46cSDimitry Andric   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1008dff0c46cSDimitry Andric   // registers. Do that here instead.
1009dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1010dff0c46cSDimitry Andric     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
10112754fe60SDimitry Andric 
10122754fe60SDimitry Andric   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
10136122f3e6SDimitry Andric   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
10142754fe60SDimitry Andric   unsigned FltOpc = ARM::VLDMDIA_UPD;
1015dff0c46cSDimitry Andric   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1016dff0c46cSDimitry Andric               NumAlignedDPRCS2Regs);
10172754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1018dff0c46cSDimitry Andric               &isARMArea2Register, 0);
10192754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1020dff0c46cSDimitry Andric               &isARMArea1Register, 0);
10212754fe60SDimitry Andric 
10222754fe60SDimitry Andric   return true;
10232754fe60SDimitry Andric }
10242754fe60SDimitry Andric 
10252754fe60SDimitry Andric // FIXME: Make generic?
10262754fe60SDimitry Andric static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
10272754fe60SDimitry Andric                                        const ARMBaseInstrInfo &TII) {
10282754fe60SDimitry Andric   unsigned FnSize = 0;
10292754fe60SDimitry Andric   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
10302754fe60SDimitry Andric        MBBI != E; ++MBBI) {
10312754fe60SDimitry Andric     const MachineBasicBlock &MBB = *MBBI;
10322754fe60SDimitry Andric     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
10332754fe60SDimitry Andric          I != E; ++I)
10342754fe60SDimitry Andric       FnSize += TII.GetInstSizeInBytes(I);
10352754fe60SDimitry Andric   }
10362754fe60SDimitry Andric   return FnSize;
10372754fe60SDimitry Andric }
10382754fe60SDimitry Andric 
10392754fe60SDimitry Andric /// estimateStackSize - Estimate and return the size of the frame.
10402754fe60SDimitry Andric /// FIXME: Make generic?
10412754fe60SDimitry Andric static unsigned estimateStackSize(MachineFunction &MF) {
104217a519f9SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
104317a519f9SDimitry Andric   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
104417a519f9SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
104517a519f9SDimitry Andric   unsigned MaxAlign = MFI->getMaxAlignment();
10462754fe60SDimitry Andric   int Offset = 0;
104717a519f9SDimitry Andric 
104817a519f9SDimitry Andric   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
104917a519f9SDimitry Andric   // It really should be refactored to share code. Until then, changes
105017a519f9SDimitry Andric   // should keep in mind that there's tight coupling between the two.
105117a519f9SDimitry Andric 
105217a519f9SDimitry Andric   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
105317a519f9SDimitry Andric     int FixedOff = -MFI->getObjectOffset(i);
10542754fe60SDimitry Andric     if (FixedOff > Offset) Offset = FixedOff;
10552754fe60SDimitry Andric   }
105617a519f9SDimitry Andric   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
105717a519f9SDimitry Andric     if (MFI->isDeadObjectIndex(i))
10582754fe60SDimitry Andric       continue;
105917a519f9SDimitry Andric     Offset += MFI->getObjectSize(i);
106017a519f9SDimitry Andric     unsigned Align = MFI->getObjectAlignment(i);
10612754fe60SDimitry Andric     // Adjust to alignment boundary
10622754fe60SDimitry Andric     Offset = (Offset+Align-1)/Align*Align;
106317a519f9SDimitry Andric 
106417a519f9SDimitry Andric     MaxAlign = std::max(Align, MaxAlign);
10652754fe60SDimitry Andric   }
106617a519f9SDimitry Andric 
106717a519f9SDimitry Andric   if (MFI->adjustsStack() && TFI->hasReservedCallFrame(MF))
106817a519f9SDimitry Andric     Offset += MFI->getMaxCallFrameSize();
106917a519f9SDimitry Andric 
107017a519f9SDimitry Andric   // Round up the size to a multiple of the alignment.  If the function has
107117a519f9SDimitry Andric   // any calls or alloca's, align to the target's StackAlignment value to
107217a519f9SDimitry Andric   // ensure that the callee's frame or the alloca data is suitably aligned;
107317a519f9SDimitry Andric   // otherwise, for leaf functions, align to the TransientStackAlignment
107417a519f9SDimitry Andric   // value.
107517a519f9SDimitry Andric   unsigned StackAlign;
107617a519f9SDimitry Andric   if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
107717a519f9SDimitry Andric       (RegInfo->needsStackRealignment(MF) && MFI->getObjectIndexEnd() != 0))
107817a519f9SDimitry Andric     StackAlign = TFI->getStackAlignment();
107917a519f9SDimitry Andric   else
108017a519f9SDimitry Andric     StackAlign = TFI->getTransientStackAlignment();
108117a519f9SDimitry Andric 
108217a519f9SDimitry Andric   // If the frame pointer is eliminated, all frame offsets will be relative to
108317a519f9SDimitry Andric   // SP not FP. Align to MaxAlign so this works.
108417a519f9SDimitry Andric   StackAlign = std::max(StackAlign, MaxAlign);
108517a519f9SDimitry Andric   unsigned AlignMask = StackAlign - 1;
108617a519f9SDimitry Andric   Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
108717a519f9SDimitry Andric 
10882754fe60SDimitry Andric   return (unsigned)Offset;
10892754fe60SDimitry Andric }
10902754fe60SDimitry Andric 
10912754fe60SDimitry Andric /// estimateRSStackSizeLimit - Look at each instruction that references stack
10922754fe60SDimitry Andric /// frames and return the stack size limit beyond which some of these
10932754fe60SDimitry Andric /// instructions will require a scratch register during their expansion later.
10942754fe60SDimitry Andric // FIXME: Move to TII?
10952754fe60SDimitry Andric static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
10962754fe60SDimitry Andric                                          const TargetFrameLowering *TFI) {
10972754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
10982754fe60SDimitry Andric   unsigned Limit = (1 << 12) - 1;
10992754fe60SDimitry Andric   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
11002754fe60SDimitry Andric     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
11012754fe60SDimitry Andric          I != E; ++I) {
11022754fe60SDimitry Andric       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
11032754fe60SDimitry Andric         if (!I->getOperand(i).isFI()) continue;
11042754fe60SDimitry Andric 
11052754fe60SDimitry Andric         // When using ADDri to get the address of a stack object, 255 is the
11062754fe60SDimitry Andric         // largest offset guaranteed to fit in the immediate offset.
11072754fe60SDimitry Andric         if (I->getOpcode() == ARM::ADDri) {
11082754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
11092754fe60SDimitry Andric           break;
11102754fe60SDimitry Andric         }
11112754fe60SDimitry Andric 
11122754fe60SDimitry Andric         // Otherwise check the addressing mode.
11132754fe60SDimitry Andric         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
11142754fe60SDimitry Andric         case ARMII::AddrMode3:
11152754fe60SDimitry Andric         case ARMII::AddrModeT2_i8:
11162754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
11172754fe60SDimitry Andric           break;
11182754fe60SDimitry Andric         case ARMII::AddrMode5:
11192754fe60SDimitry Andric         case ARMII::AddrModeT2_i8s4:
11202754fe60SDimitry Andric           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
11212754fe60SDimitry Andric           break;
11222754fe60SDimitry Andric         case ARMII::AddrModeT2_i12:
11232754fe60SDimitry Andric           // i12 supports only positive offset so these will be converted to
11242754fe60SDimitry Andric           // i8 opcodes. See llvm::rewriteT2FrameIndex.
11252754fe60SDimitry Andric           if (TFI->hasFP(MF) && AFI->hasStackFrame())
11262754fe60SDimitry Andric             Limit = std::min(Limit, (1U << 8) - 1);
11272754fe60SDimitry Andric           break;
11282754fe60SDimitry Andric         case ARMII::AddrMode4:
11292754fe60SDimitry Andric         case ARMII::AddrMode6:
11302754fe60SDimitry Andric           // Addressing modes 4 & 6 (load/store) instructions can't encode an
11312754fe60SDimitry Andric           // immediate offset for stack references.
11322754fe60SDimitry Andric           return 0;
11332754fe60SDimitry Andric         default:
11342754fe60SDimitry Andric           break;
11352754fe60SDimitry Andric         }
11362754fe60SDimitry Andric         break; // At most one FI per instruction
11372754fe60SDimitry Andric       }
11382754fe60SDimitry Andric     }
11392754fe60SDimitry Andric   }
11402754fe60SDimitry Andric 
11412754fe60SDimitry Andric   return Limit;
11422754fe60SDimitry Andric }
11432754fe60SDimitry Andric 
1144dff0c46cSDimitry Andric // In functions that realign the stack, it can be an advantage to spill the
1145dff0c46cSDimitry Andric // callee-saved vector registers after realigning the stack. The vst1 and vld1
1146dff0c46cSDimitry Andric // instructions take alignment hints that can improve performance.
1147dff0c46cSDimitry Andric //
1148dff0c46cSDimitry Andric static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1149dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1150dff0c46cSDimitry Andric   if (!SpillAlignedNEONRegs)
1151dff0c46cSDimitry Andric     return;
1152dff0c46cSDimitry Andric 
1153dff0c46cSDimitry Andric   // Naked functions don't spill callee-saved registers.
1154dff0c46cSDimitry Andric   if (MF.getFunction()->hasFnAttr(Attribute::Naked))
1155dff0c46cSDimitry Andric     return;
1156dff0c46cSDimitry Andric 
1157dff0c46cSDimitry Andric   // We are planning to use NEON instructions vst1 / vld1.
1158dff0c46cSDimitry Andric   if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1159dff0c46cSDimitry Andric     return;
1160dff0c46cSDimitry Andric 
1161dff0c46cSDimitry Andric   // Don't bother if the default stack alignment is sufficiently high.
1162dff0c46cSDimitry Andric   if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1163dff0c46cSDimitry Andric     return;
1164dff0c46cSDimitry Andric 
1165dff0c46cSDimitry Andric   // Aligned spills require stack realignment.
1166dff0c46cSDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
1167dff0c46cSDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1168dff0c46cSDimitry Andric   if (!RegInfo->canRealignStack(MF))
1169dff0c46cSDimitry Andric     return;
1170dff0c46cSDimitry Andric 
1171dff0c46cSDimitry Andric   // We always spill contiguous d-registers starting from d8. Count how many
1172dff0c46cSDimitry Andric   // needs spilling.  The register allocator will almost always use the
1173dff0c46cSDimitry Andric   // callee-saved registers in order, but it can happen that there are holes in
1174dff0c46cSDimitry Andric   // the range.  Registers above the hole will be spilled to the standard DPRCS
1175dff0c46cSDimitry Andric   // area.
1176dff0c46cSDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
1177dff0c46cSDimitry Andric   unsigned NumSpills = 0;
1178dff0c46cSDimitry Andric   for (; NumSpills < 8; ++NumSpills)
1179dff0c46cSDimitry Andric     if (!MRI.isPhysRegOrOverlapUsed(ARM::D8 + NumSpills))
1180dff0c46cSDimitry Andric       break;
1181dff0c46cSDimitry Andric 
1182dff0c46cSDimitry Andric   // Don't do this for just one d-register. It's not worth it.
1183dff0c46cSDimitry Andric   if (NumSpills < 2)
1184dff0c46cSDimitry Andric     return;
1185dff0c46cSDimitry Andric 
1186dff0c46cSDimitry Andric   // Spill the first NumSpills D-registers after realigning the stack.
1187dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1188dff0c46cSDimitry Andric 
1189dff0c46cSDimitry Andric   // A scratch register is required for the vst1 / vld1 instructions.
1190dff0c46cSDimitry Andric   MF.getRegInfo().setPhysRegUsed(ARM::R4);
1191dff0c46cSDimitry Andric }
1192dff0c46cSDimitry Andric 
11932754fe60SDimitry Andric void
11942754fe60SDimitry Andric ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
11952754fe60SDimitry Andric                                                        RegScavenger *RS) const {
11962754fe60SDimitry Andric   // This tells PEI to spill the FP as if it is any other callee-save register
11972754fe60SDimitry Andric   // to take advantage the eliminateFrameIndex machinery. This also ensures it
11982754fe60SDimitry Andric   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
11992754fe60SDimitry Andric   // to combine multiple loads / stores.
12002754fe60SDimitry Andric   bool CanEliminateFrame = true;
12012754fe60SDimitry Andric   bool CS1Spilled = false;
12022754fe60SDimitry Andric   bool LRSpilled = false;
12032754fe60SDimitry Andric   unsigned NumGPRSpills = 0;
12042754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS1GPRs;
12052754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS2GPRs;
12062754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
12072754fe60SDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
12082754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
12092754fe60SDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
12102754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
12112754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
12122754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
12132754fe60SDimitry Andric 
12142754fe60SDimitry Andric   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
12152754fe60SDimitry Andric   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
12162754fe60SDimitry Andric   // since it's not always possible to restore sp from fp in a single
12172754fe60SDimitry Andric   // instruction.
12182754fe60SDimitry Andric   // FIXME: It will be better just to find spare register here.
12192754fe60SDimitry Andric   if (AFI->isThumb2Function() &&
12202754fe60SDimitry Andric       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
12212754fe60SDimitry Andric     MF.getRegInfo().setPhysRegUsed(ARM::R4);
12222754fe60SDimitry Andric 
12232754fe60SDimitry Andric   if (AFI->isThumb1OnlyFunction()) {
12242754fe60SDimitry Andric     // Spill LR if Thumb1 function uses variable length argument lists.
12252754fe60SDimitry Andric     if (AFI->getVarArgsRegSaveSize() > 0)
12262754fe60SDimitry Andric       MF.getRegInfo().setPhysRegUsed(ARM::LR);
12272754fe60SDimitry Andric 
122817a519f9SDimitry Andric     // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
122917a519f9SDimitry Andric     // for sure what the stack size will be, but for this, an estimate is good
123017a519f9SDimitry Andric     // enough. If there anything changes it, it'll be a spill, which implies
123117a519f9SDimitry Andric     // we've used all the registers and so R4 is already used, so not marking
123217a519f9SDimitry Andric     // it here will be OK.
12332754fe60SDimitry Andric     // FIXME: It will be better just to find spare register here.
123417a519f9SDimitry Andric     unsigned StackSize = estimateStackSize(MF);
123517a519f9SDimitry Andric     if (MFI->hasVarSizedObjects() || StackSize > 508)
12362754fe60SDimitry Andric       MF.getRegInfo().setPhysRegUsed(ARM::R4);
12372754fe60SDimitry Andric   }
12382754fe60SDimitry Andric 
1239dff0c46cSDimitry Andric   // See if we can spill vector registers to aligned stack.
1240dff0c46cSDimitry Andric   checkNumAlignedDPRCS2Regs(MF);
1241dff0c46cSDimitry Andric 
12422754fe60SDimitry Andric   // Spill the BasePtr if it's used.
12432754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
12442754fe60SDimitry Andric     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
12452754fe60SDimitry Andric 
12462754fe60SDimitry Andric   // Don't spill FP if the frame can be eliminated. This is determined
12472754fe60SDimitry Andric   // by scanning the callee-save registers to see if any is used.
1248dff0c46cSDimitry Andric   const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
12492754fe60SDimitry Andric   for (unsigned i = 0; CSRegs[i]; ++i) {
12502754fe60SDimitry Andric     unsigned Reg = CSRegs[i];
12512754fe60SDimitry Andric     bool Spilled = false;
1252dff0c46cSDimitry Andric     if (MF.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
12532754fe60SDimitry Andric       Spilled = true;
12542754fe60SDimitry Andric       CanEliminateFrame = false;
12552754fe60SDimitry Andric     }
12562754fe60SDimitry Andric 
12577ae0e2c9SDimitry Andric     if (!ARM::GPRRegClass.contains(Reg))
12582754fe60SDimitry Andric       continue;
12592754fe60SDimitry Andric 
12602754fe60SDimitry Andric     if (Spilled) {
12612754fe60SDimitry Andric       NumGPRSpills++;
12622754fe60SDimitry Andric 
1263dff0c46cSDimitry Andric       if (!STI.isTargetIOS()) {
12642754fe60SDimitry Andric         if (Reg == ARM::LR)
12652754fe60SDimitry Andric           LRSpilled = true;
12662754fe60SDimitry Andric         CS1Spilled = true;
12672754fe60SDimitry Andric         continue;
12682754fe60SDimitry Andric       }
12692754fe60SDimitry Andric 
12702754fe60SDimitry Andric       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
12712754fe60SDimitry Andric       switch (Reg) {
12722754fe60SDimitry Andric       case ARM::LR:
12732754fe60SDimitry Andric         LRSpilled = true;
12742754fe60SDimitry Andric         // Fallthrough
12752754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
12762754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
12772754fe60SDimitry Andric         CS1Spilled = true;
12782754fe60SDimitry Andric         break;
12792754fe60SDimitry Andric       default:
12802754fe60SDimitry Andric         break;
12812754fe60SDimitry Andric       }
12822754fe60SDimitry Andric     } else {
1283dff0c46cSDimitry Andric       if (!STI.isTargetIOS()) {
12842754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
12852754fe60SDimitry Andric         continue;
12862754fe60SDimitry Andric       }
12872754fe60SDimitry Andric 
12882754fe60SDimitry Andric       switch (Reg) {
12892754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
12902754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
12912754fe60SDimitry Andric       case ARM::LR:
12922754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
12932754fe60SDimitry Andric         break;
12942754fe60SDimitry Andric       default:
12952754fe60SDimitry Andric         UnspilledCS2GPRs.push_back(Reg);
12962754fe60SDimitry Andric         break;
12972754fe60SDimitry Andric       }
12982754fe60SDimitry Andric     }
12992754fe60SDimitry Andric   }
13002754fe60SDimitry Andric 
13012754fe60SDimitry Andric   bool ForceLRSpill = false;
13022754fe60SDimitry Andric   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
13032754fe60SDimitry Andric     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
13042754fe60SDimitry Andric     // Force LR to be spilled if the Thumb function size is > 2048. This enables
13052754fe60SDimitry Andric     // use of BL to implement far jump. If it turns out that it's not needed
13062754fe60SDimitry Andric     // then the branch fix up path will undo it.
13072754fe60SDimitry Andric     if (FnSize >= (1 << 11)) {
13082754fe60SDimitry Andric       CanEliminateFrame = false;
13092754fe60SDimitry Andric       ForceLRSpill = true;
13102754fe60SDimitry Andric     }
13112754fe60SDimitry Andric   }
13122754fe60SDimitry Andric 
13132754fe60SDimitry Andric   // If any of the stack slot references may be out of range of an immediate
13142754fe60SDimitry Andric   // offset, make sure a register (or a spill slot) is available for the
13152754fe60SDimitry Andric   // register scavenger. Note that if we're indexing off the frame pointer, the
13162754fe60SDimitry Andric   // effective stack size is 4 bytes larger since the FP points to the stack
13172754fe60SDimitry Andric   // slot of the previous FP. Also, if we have variable sized objects in the
13182754fe60SDimitry Andric   // function, stack slot references will often be negative, and some of
13192754fe60SDimitry Andric   // our instructions are positive-offset only, so conservatively consider
13202754fe60SDimitry Andric   // that case to want a spill slot (or register) as well. Similarly, if
13212754fe60SDimitry Andric   // the function adjusts the stack pointer during execution and the
13222754fe60SDimitry Andric   // adjustments aren't already part of our stack size estimate, our offset
13232754fe60SDimitry Andric   // calculations may be off, so be conservative.
13242754fe60SDimitry Andric   // FIXME: We could add logic to be more precise about negative offsets
13252754fe60SDimitry Andric   //        and which instructions will need a scratch register for them. Is it
13262754fe60SDimitry Andric   //        worth the effort and added fragility?
13272754fe60SDimitry Andric   bool BigStack =
13282754fe60SDimitry Andric     (RS &&
13292754fe60SDimitry Andric      (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
13302754fe60SDimitry Andric       estimateRSStackSizeLimit(MF, this)))
13312754fe60SDimitry Andric     || MFI->hasVarSizedObjects()
13322754fe60SDimitry Andric     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
13332754fe60SDimitry Andric 
13342754fe60SDimitry Andric   bool ExtraCSSpill = false;
13352754fe60SDimitry Andric   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
13362754fe60SDimitry Andric     AFI->setHasStackFrame(true);
13372754fe60SDimitry Andric 
13382754fe60SDimitry Andric     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
13392754fe60SDimitry Andric     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
13402754fe60SDimitry Andric     if (!LRSpilled && CS1Spilled) {
13412754fe60SDimitry Andric       MF.getRegInfo().setPhysRegUsed(ARM::LR);
13422754fe60SDimitry Andric       NumGPRSpills++;
13432754fe60SDimitry Andric       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
13442754fe60SDimitry Andric                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
13452754fe60SDimitry Andric       ForceLRSpill = false;
13462754fe60SDimitry Andric       ExtraCSSpill = true;
13472754fe60SDimitry Andric     }
13482754fe60SDimitry Andric 
13492754fe60SDimitry Andric     if (hasFP(MF)) {
13502754fe60SDimitry Andric       MF.getRegInfo().setPhysRegUsed(FramePtr);
13512754fe60SDimitry Andric       NumGPRSpills++;
13522754fe60SDimitry Andric     }
13532754fe60SDimitry Andric 
13542754fe60SDimitry Andric     // If stack and double are 8-byte aligned and we are spilling an odd number
13552754fe60SDimitry Andric     // of GPRs, spill one extra callee save GPR so we won't have to pad between
13562754fe60SDimitry Andric     // the integer and double callee save areas.
13572754fe60SDimitry Andric     unsigned TargetAlign = getStackAlignment();
13582754fe60SDimitry Andric     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
13592754fe60SDimitry Andric       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
13602754fe60SDimitry Andric         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
13612754fe60SDimitry Andric           unsigned Reg = UnspilledCS1GPRs[i];
13622754fe60SDimitry Andric           // Don't spill high register if the function is thumb1
13632754fe60SDimitry Andric           if (!AFI->isThumb1OnlyFunction() ||
13642754fe60SDimitry Andric               isARMLowRegister(Reg) || Reg == ARM::LR) {
13652754fe60SDimitry Andric             MF.getRegInfo().setPhysRegUsed(Reg);
13662754fe60SDimitry Andric             if (!RegInfo->isReservedReg(MF, Reg))
13672754fe60SDimitry Andric               ExtraCSSpill = true;
13682754fe60SDimitry Andric             break;
13692754fe60SDimitry Andric           }
13702754fe60SDimitry Andric         }
13712754fe60SDimitry Andric       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
13722754fe60SDimitry Andric         unsigned Reg = UnspilledCS2GPRs.front();
13732754fe60SDimitry Andric         MF.getRegInfo().setPhysRegUsed(Reg);
13742754fe60SDimitry Andric         if (!RegInfo->isReservedReg(MF, Reg))
13752754fe60SDimitry Andric           ExtraCSSpill = true;
13762754fe60SDimitry Andric       }
13772754fe60SDimitry Andric     }
13782754fe60SDimitry Andric 
13792754fe60SDimitry Andric     // Estimate if we might need to scavenge a register at some point in order
13802754fe60SDimitry Andric     // to materialize a stack offset. If so, either spill one additional
13812754fe60SDimitry Andric     // callee-saved register or reserve a special spill slot to facilitate
13822754fe60SDimitry Andric     // register scavenging. Thumb1 needs a spill slot for stack pointer
13832754fe60SDimitry Andric     // adjustments also, even when the frame itself is small.
13842754fe60SDimitry Andric     if (BigStack && !ExtraCSSpill) {
13852754fe60SDimitry Andric       // If any non-reserved CS register isn't spilled, just spill one or two
13862754fe60SDimitry Andric       // extra. That should take care of it!
13872754fe60SDimitry Andric       unsigned NumExtras = TargetAlign / 4;
13882754fe60SDimitry Andric       SmallVector<unsigned, 2> Extras;
13892754fe60SDimitry Andric       while (NumExtras && !UnspilledCS1GPRs.empty()) {
13902754fe60SDimitry Andric         unsigned Reg = UnspilledCS1GPRs.back();
13912754fe60SDimitry Andric         UnspilledCS1GPRs.pop_back();
13922754fe60SDimitry Andric         if (!RegInfo->isReservedReg(MF, Reg) &&
13932754fe60SDimitry Andric             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
13942754fe60SDimitry Andric              Reg == ARM::LR)) {
13952754fe60SDimitry Andric           Extras.push_back(Reg);
13962754fe60SDimitry Andric           NumExtras--;
13972754fe60SDimitry Andric         }
13982754fe60SDimitry Andric       }
13992754fe60SDimitry Andric       // For non-Thumb1 functions, also check for hi-reg CS registers
14002754fe60SDimitry Andric       if (!AFI->isThumb1OnlyFunction()) {
14012754fe60SDimitry Andric         while (NumExtras && !UnspilledCS2GPRs.empty()) {
14022754fe60SDimitry Andric           unsigned Reg = UnspilledCS2GPRs.back();
14032754fe60SDimitry Andric           UnspilledCS2GPRs.pop_back();
14042754fe60SDimitry Andric           if (!RegInfo->isReservedReg(MF, Reg)) {
14052754fe60SDimitry Andric             Extras.push_back(Reg);
14062754fe60SDimitry Andric             NumExtras--;
14072754fe60SDimitry Andric           }
14082754fe60SDimitry Andric         }
14092754fe60SDimitry Andric       }
14102754fe60SDimitry Andric       if (Extras.size() && NumExtras == 0) {
14112754fe60SDimitry Andric         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
14122754fe60SDimitry Andric           MF.getRegInfo().setPhysRegUsed(Extras[i]);
14132754fe60SDimitry Andric         }
14142754fe60SDimitry Andric       } else if (!AFI->isThumb1OnlyFunction()) {
14152754fe60SDimitry Andric         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
14162754fe60SDimitry Andric         // closest to SP or frame pointer.
14177ae0e2c9SDimitry Andric         const TargetRegisterClass *RC = &ARM::GPRRegClass;
14182754fe60SDimitry Andric         RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
14192754fe60SDimitry Andric                                                            RC->getAlignment(),
14202754fe60SDimitry Andric                                                            false));
14212754fe60SDimitry Andric       }
14222754fe60SDimitry Andric     }
14232754fe60SDimitry Andric   }
14242754fe60SDimitry Andric 
14252754fe60SDimitry Andric   if (ForceLRSpill) {
14262754fe60SDimitry Andric     MF.getRegInfo().setPhysRegUsed(ARM::LR);
14272754fe60SDimitry Andric     AFI->setLRIsSpilledForFarJump(true);
14282754fe60SDimitry Andric   }
14292754fe60SDimitry Andric }
1430