Home | History | Annotate | Download | only in ARM
      1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file contains the ARM implementation of TargetFrameLowering class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "ARMFrameLowering.h"
     15 #include "ARMBaseInstrInfo.h"
     16 #include "ARMBaseRegisterInfo.h"
     17 #include "ARMMachineFunctionInfo.h"
     18 #include "MCTargetDesc/ARMAddressingModes.h"
     19 #include "llvm/CodeGen/MachineFrameInfo.h"
     20 #include "llvm/CodeGen/MachineFunction.h"
     21 #include "llvm/CodeGen/MachineInstrBuilder.h"
     22 #include "llvm/CodeGen/MachineRegisterInfo.h"
     23 #include "llvm/CodeGen/RegisterScavenging.h"
     24 #include "llvm/IR/CallingConv.h"
     25 #include "llvm/IR/Function.h"
     26 #include "llvm/Support/CommandLine.h"
     27 #include "llvm/Target/TargetOptions.h"
     28 
     29 using namespace llvm;
     30 
     31 static cl::opt<bool>
     32 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
     33                      cl::desc("Align ARM NEON spills in prolog and epilog"));
     34 
     35 static MachineBasicBlock::iterator
     36 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
     37                         unsigned NumAlignedDPRCS2Regs);
     38 
     39 /// hasFP - Return true if the specified function should have a dedicated frame
     40 /// pointer register.  This is true if the function has variable sized allocas
     41 /// or if frame pointer elimination is disabled.
     42 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
     43   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
     44 
     45   // iOS requires FP not to be clobbered for backtracing purpose.
     46   if (STI.isTargetIOS())
     47     return true;
     48 
     49   const MachineFrameInfo *MFI = MF.getFrameInfo();
     50   // Always eliminate non-leaf frame pointers.
     51   return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
     52            MFI->hasCalls()) ||
     53           RegInfo->needsStackRealignment(MF) ||
     54           MFI->hasVarSizedObjects() ||
     55           MFI->isFrameAddressTaken());
     56 }
     57 
     58 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
     59 /// not required, we reserve argument space for call sites in the function
     60 /// immediately on entry to the current function.  This eliminates the need for
     61 /// add/sub sp brackets around call sites.  Returns true if the call frame is
     62 /// included as part of the stack frame.
     63 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
     64   const MachineFrameInfo *FFI = MF.getFrameInfo();
     65   unsigned CFSize = FFI->getMaxCallFrameSize();
     66   // It's not always a good idea to include the call frame as part of the
     67   // stack frame. ARM (especially Thumb) has small immediate offset to
     68   // address the stack frame. So a large call frame can cause poor codegen
     69   // and may even makes it impossible to scavenge a register.
     70   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
     71     return false;
     72 
     73   return !MF.getFrameInfo()->hasVarSizedObjects();
     74 }
     75 
     76 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
     77 /// call frame pseudos can be simplified.  Unlike most targets, having a FP
     78 /// is not sufficient here since we still may reference some objects via SP
     79 /// even when FP is available in Thumb2 mode.
     80 bool
     81 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
     82   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
     83 }
     84 
     85 static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
     86   for (unsigned i = 0; CSRegs[i]; ++i)
     87     if (Reg == CSRegs[i])
     88       return true;
     89   return false;
     90 }
     91 
     92 static bool isCSRestore(MachineInstr *MI,
     93                         const ARMBaseInstrInfo &TII,
     94                         const uint16_t *CSRegs) {
     95   // Integer spill area is handled with "pop".
     96   if (MI->getOpcode() == ARM::LDMIA_RET ||
     97       MI->getOpcode() == ARM::t2LDMIA_RET ||
     98       MI->getOpcode() == ARM::LDMIA_UPD ||
     99       MI->getOpcode() == ARM::t2LDMIA_UPD ||
    100       MI->getOpcode() == ARM::VLDMDIA_UPD) {
    101     // The first two operands are predicates. The last two are
    102     // imp-def and imp-use of SP. Check everything in between.
    103     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
    104       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
    105         return false;
    106     return true;
    107   }
    108   if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
    109        MI->getOpcode() == ARM::LDR_POST_REG ||
    110        MI->getOpcode() == ARM::t2LDR_POST) &&
    111       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
    112       MI->getOperand(1).getReg() == ARM::SP)
    113     return true;
    114 
    115   return false;
    116 }
    117 
    118 static void
    119 emitSPUpdate(bool isARM,
    120              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
    121              DebugLoc dl, const ARMBaseInstrInfo &TII,
    122              int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
    123              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
    124   if (isARM)
    125     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
    126                             Pred, PredReg, TII, MIFlags);
    127   else
    128     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
    129                            Pred, PredReg, TII, MIFlags);
    130 }
    131 
    132 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
    133   MachineBasicBlock &MBB = MF.front();
    134   MachineBasicBlock::iterator MBBI = MBB.begin();
    135   MachineFrameInfo  *MFI = MF.getFrameInfo();
    136   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    137   const ARMBaseRegisterInfo *RegInfo =
    138     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
    139   const ARMBaseInstrInfo &TII =
    140     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
    141   assert(!AFI->isThumb1OnlyFunction() &&
    142          "This emitPrologue does not support Thumb1!");
    143   bool isARM = !AFI->isThumbFunction();
    144   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
    145   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
    146   unsigned NumBytes = MFI->getStackSize();
    147   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
    148   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
    149   unsigned FramePtr = RegInfo->getFrameRegister(MF);
    150 
    151   // Determine the sizes of each callee-save spill areas and record which frame
    152   // belongs to which callee-save spill areas.
    153   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
    154   int FramePtrSpillFI = 0;
    155   int D8SpillFI = 0;
    156 
    157   // All calls are tail calls in GHC calling conv, and functions have no
    158   // prologue/epilogue.
    159   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
    160     return;
    161 
    162   // Allocate the vararg register save area. This is not counted in NumBytes.
    163   if (ArgRegsSaveSize)
    164     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
    165                  MachineInstr::FrameSetup);
    166 
    167   if (!AFI->hasStackFrame()) {
    168     if (NumBytes != 0)
    169       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
    170                    MachineInstr::FrameSetup);
    171     return;
    172   }
    173 
    174   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
    175     unsigned Reg = CSI[i].getReg();
    176     int FI = CSI[i].getFrameIdx();
    177     switch (Reg) {
    178     case ARM::R4:
    179     case ARM::R5:
    180     case ARM::R6:
    181     case ARM::R7:
    182     case ARM::LR:
    183       if (Reg == FramePtr)
    184         FramePtrSpillFI = FI;
    185       AFI->addGPRCalleeSavedArea1Frame(FI);
    186       GPRCS1Size += 4;
    187       break;
    188     case ARM::R8:
    189     case ARM::R9:
    190     case ARM::R10:
    191     case ARM::R11:
    192       if (Reg == FramePtr)
    193         FramePtrSpillFI = FI;
    194       if (STI.isTargetIOS()) {
    195         AFI->addGPRCalleeSavedArea2Frame(FI);
    196         GPRCS2Size += 4;
    197       } else {
    198         AFI->addGPRCalleeSavedArea1Frame(FI);
    199         GPRCS1Size += 4;
    200       }
    201       break;
    202     default:
    203       // This is a DPR. Exclude the aligned DPRCS2 spills.
    204       if (Reg == ARM::D8)
    205         D8SpillFI = FI;
    206       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) {
    207         AFI->addDPRCalleeSavedAreaFrame(FI);
    208         DPRCSSize += 8;
    209       }
    210     }
    211   }
    212 
    213   // Move past area 1.
    214   if (GPRCS1Size > 0) MBBI++;
    215 
    216   // Set FP to point to the stack slot that contains the previous FP.
    217   // For iOS, FP is R7, which has now been stored in spill area 1.
    218   // Otherwise, if this is not iOS, all the callee-saved registers go
    219   // into spill area 1, including the FP in R11.  In either case, it is
    220   // now safe to emit this assignment.
    221   bool HasFP = hasFP(MF);
    222   if (HasFP) {
    223     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
    224     MachineInstrBuilder MIB =
    225       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
    226       .addFrameIndex(FramePtrSpillFI).addImm(0)
    227       .setMIFlag(MachineInstr::FrameSetup);
    228     AddDefaultCC(AddDefaultPred(MIB));
    229   }
    230 
    231   // Move past area 2.
    232   if (GPRCS2Size > 0) MBBI++;
    233 
    234   // Determine starting offsets of spill areas.
    235   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
    236   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
    237   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
    238   if (HasFP)
    239     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
    240                                 NumBytes);
    241   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
    242   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
    243   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
    244 
    245   // Move past area 3.
    246   if (DPRCSSize > 0) {
    247     MBBI++;
    248     // Since vpush register list cannot have gaps, there may be multiple vpush
    249     // instructions in the prologue.
    250     while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
    251       MBBI++;
    252   }
    253 
    254   // Move past the aligned DPRCS2 area.
    255   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
    256     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
    257     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
    258     // leaves the stack pointer pointing to the DPRCS2 area.
    259     //
    260     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
    261     NumBytes += MFI->getObjectOffset(D8SpillFI);
    262   } else
    263     NumBytes = DPRCSOffset;
    264 
    265   if (NumBytes) {
    266     // Adjust SP after all the callee-save spills.
    267     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
    268                  MachineInstr::FrameSetup);
    269     if (HasFP && isARM)
    270       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
    271       // Note it's not safe to do this in Thumb2 mode because it would have
    272       // taken two instructions:
    273       // mov sp, r7
    274       // sub sp, #24
    275       // If an interrupt is taken between the two instructions, then sp is in
    276       // an inconsistent state (pointing to the middle of callee-saved area).
    277       // The interrupt handler can end up clobbering the registers.
    278       AFI->setShouldRestoreSPFromFP(true);
    279   }
    280 
    281   if (STI.isTargetELF() && hasFP(MF))
    282     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
    283                              AFI->getFramePtrSpillOffset());
    284 
    285   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
    286   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
    287   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
    288 
    289   // If we need dynamic stack realignment, do it here. Be paranoid and make
    290   // sure if we also have VLAs, we have a base pointer for frame access.
    291   // If aligned NEON registers were spilled, the stack has already been
    292   // realigned.
    293   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
    294     unsigned MaxAlign = MFI->getMaxAlignment();
    295     assert (!AFI->isThumb1OnlyFunction());
    296     if (!AFI->isThumbFunction()) {
    297       // Emit bic sp, sp, MaxAlign
    298       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
    299                                           TII.get(ARM::BICri), ARM::SP)
    300                                   .addReg(ARM::SP, RegState::Kill)
    301                                   .addImm(MaxAlign-1)));
    302     } else {
    303       // We cannot use sp as source/dest register here, thus we're emitting the
    304       // following sequence:
    305       // mov r4, sp
    306       // bic r4, r4, MaxAlign
    307       // mov sp, r4
    308       // FIXME: It will be better just to find spare register here.
    309       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
    310         .addReg(ARM::SP, RegState::Kill));
    311       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
    312                                           TII.get(ARM::t2BICri), ARM::R4)
    313                                   .addReg(ARM::R4, RegState::Kill)
    314                                   .addImm(MaxAlign-1)));
    315       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
    316         .addReg(ARM::R4, RegState::Kill));
    317     }
    318 
    319     AFI->setShouldRestoreSPFromFP(true);
    320   }
    321 
    322   // If we need a base pointer, set it up here. It's whatever the value
    323   // of the stack pointer is at this point. Any variable size objects
    324   // will be allocated after this, so we can still use the base pointer
    325   // to reference locals.
    326   // FIXME: Clarify FrameSetup flags here.
    327   if (RegInfo->hasBasePointer(MF)) {
    328     if (isARM)
    329       BuildMI(MBB, MBBI, dl,
    330               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
    331         .addReg(ARM::SP)
    332         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
    333     else
    334       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
    335                              RegInfo->getBaseRegister())
    336         .addReg(ARM::SP));
    337   }
    338 
    339   // If the frame has variable sized objects then the epilogue must restore
    340   // the sp from fp. We can assume there's an FP here since hasFP already
    341   // checks for hasVarSizedObjects.
    342   if (MFI->hasVarSizedObjects())
    343     AFI->setShouldRestoreSPFromFP(true);
    344 }
    345 
    346 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
    347                                     MachineBasicBlock &MBB) const {
    348   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
    349   assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
    350   unsigned RetOpcode = MBBI->getOpcode();
    351   DebugLoc dl = MBBI->getDebugLoc();
    352   MachineFrameInfo *MFI = MF.getFrameInfo();
    353   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    354   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
    355   const ARMBaseInstrInfo &TII =
    356     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
    357   assert(!AFI->isThumb1OnlyFunction() &&
    358          "This emitEpilogue does not support Thumb1!");
    359   bool isARM = !AFI->isThumbFunction();
    360 
    361   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
    362   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
    363   int NumBytes = (int)MFI->getStackSize();
    364   unsigned FramePtr = RegInfo->getFrameRegister(MF);
    365 
    366   // All calls are tail calls in GHC calling conv, and functions have no
    367   // prologue/epilogue.
    368   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
    369     return;
    370 
    371   if (!AFI->hasStackFrame()) {
    372     if (NumBytes != 0)
    373       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
    374   } else {
    375     // Unwind MBBI to point to first LDR / VLDRD.
    376     const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
    377     if (MBBI != MBB.begin()) {
    378       do
    379         --MBBI;
    380       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
    381       if (!isCSRestore(MBBI, TII, CSRegs))
    382         ++MBBI;
    383     }
    384 
    385     // Move SP to start of FP callee save spill area.
    386     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
    387                  AFI->getGPRCalleeSavedArea2Size() +
    388                  AFI->getDPRCalleeSavedAreaSize());
    389 
    390     // Reset SP based on frame pointer only if the stack frame extends beyond
    391     // frame pointer stack slot or target is ELF and the function has FP.
    392     if (AFI->shouldRestoreSPFromFP()) {
    393       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
    394       if (NumBytes) {
    395         if (isARM)
    396           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
    397                                   ARMCC::AL, 0, TII);
    398         else {
    399           // It's not possible to restore SP from FP in a single instruction.
    400           // For iOS, this looks like:
    401           // mov sp, r7
    402           // sub sp, #24
    403           // This is bad, if an interrupt is taken after the mov, sp is in an
    404           // inconsistent state.
    405           // Use the first callee-saved register as a scratch register.
    406           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
    407                  "No scratch register to restore SP from FP!");
    408           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
    409                                  ARMCC::AL, 0, TII);
    410           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
    411                                  ARM::SP)
    412             .addReg(ARM::R4));
    413         }
    414       } else {
    415         // Thumb2 or ARM.
    416         if (isARM)
    417           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
    418             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
    419         else
    420           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
    421                                  ARM::SP)
    422             .addReg(FramePtr));
    423       }
    424     } else if (NumBytes)
    425       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
    426 
    427     // Increment past our save areas.
    428     if (AFI->getDPRCalleeSavedAreaSize()) {
    429       MBBI++;
    430       // Since vpop register list cannot have gaps, there may be multiple vpop
    431       // instructions in the epilogue.
    432       while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
    433         MBBI++;
    434     }
    435     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
    436     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
    437   }
    438 
    439   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
    440     // Tail call return: adjust the stack pointer and jump to callee.
    441     MBBI = MBB.getLastNonDebugInstr();
    442     MachineOperand &JumpTarget = MBBI->getOperand(0);
    443 
    444     // Jump to label or value in register.
    445     if (RetOpcode == ARM::TCRETURNdi) {
    446       unsigned TCOpcode = STI.isThumb() ?
    447                (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
    448                ARM::TAILJMPd;
    449       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
    450       if (JumpTarget.isGlobal())
    451         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
    452                              JumpTarget.getTargetFlags());
    453       else {
    454         assert(JumpTarget.isSymbol());
    455         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
    456                               JumpTarget.getTargetFlags());
    457       }
    458 
    459       // Add the default predicate in Thumb mode.
    460       if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
    461     } else if (RetOpcode == ARM::TCRETURNri) {
    462       BuildMI(MBB, MBBI, dl,
    463               TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
    464         addReg(JumpTarget.getReg(), RegState::Kill);
    465     }
    466 
    467     MachineInstr *NewMI = prior(MBBI);
    468     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
    469       NewMI->addOperand(MBBI->getOperand(i));
    470 
    471     // Delete the pseudo instruction TCRETURN.
    472     MBB.erase(MBBI);
    473     MBBI = NewMI;
    474   }
    475 
    476   if (ArgRegsSaveSize)
    477     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
    478 }
    479 
    480 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
    481 /// debug info.  It's the same as what we use for resolving the code-gen
    482 /// references for now.  FIXME: This can go wrong when references are
    483 /// SP-relative and simple call frames aren't used.
    484 int
    485 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
    486                                          unsigned &FrameReg) const {
    487   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
    488 }
    489 
    490 int
    491 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
    492                                              int FI, unsigned &FrameReg,
    493                                              int SPAdj) const {
    494   const MachineFrameInfo *MFI = MF.getFrameInfo();
    495   const ARMBaseRegisterInfo *RegInfo =
    496     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
    497   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    498   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
    499   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
    500   bool isFixed = MFI->isFixedObjectIndex(FI);
    501 
    502   FrameReg = ARM::SP;
    503   Offset += SPAdj;
    504   if (AFI->isGPRCalleeSavedArea1Frame(FI))
    505     return Offset - AFI->getGPRCalleeSavedArea1Offset();
    506   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
    507     return Offset - AFI->getGPRCalleeSavedArea2Offset();
    508   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
    509     return Offset - AFI->getDPRCalleeSavedAreaOffset();
    510 
    511   // SP can move around if there are allocas.  We may also lose track of SP
    512   // when emergency spilling inside a non-reserved call frame setup.
    513   bool hasMovingSP = !hasReservedCallFrame(MF);
    514 
    515   // When dynamically realigning the stack, use the frame pointer for
    516   // parameters, and the stack/base pointer for locals.
    517   if (RegInfo->needsStackRealignment(MF)) {
    518     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
    519     if (isFixed) {
    520       FrameReg = RegInfo->getFrameRegister(MF);
    521       Offset = FPOffset;
    522     } else if (hasMovingSP) {
    523       assert(RegInfo->hasBasePointer(MF) &&
    524              "VLAs and dynamic stack alignment, but missing base pointer!");
    525       FrameReg = RegInfo->getBaseRegister();
    526     }
    527     return Offset;
    528   }
    529 
    530   // If there is a frame pointer, use it when we can.
    531   if (hasFP(MF) && AFI->hasStackFrame()) {
    532     // Use frame pointer to reference fixed objects. Use it for locals if
    533     // there are VLAs (and thus the SP isn't reliable as a base).
    534     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
    535       FrameReg = RegInfo->getFrameRegister(MF);
    536       return FPOffset;
    537     } else if (hasMovingSP) {
    538       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
    539       if (AFI->isThumb2Function()) {
    540         // Try to use the frame pointer if we can, else use the base pointer
    541         // since it's available. This is handy for the emergency spill slot, in
    542         // particular.
    543         if (FPOffset >= -255 && FPOffset < 0) {
    544           FrameReg = RegInfo->getFrameRegister(MF);
    545           return FPOffset;
    546         }
    547       }
    548     } else if (AFI->isThumb2Function()) {
    549       // Use  add <rd>, sp, #<imm8>
    550       //      ldr <rd>, [sp, #<imm8>]
    551       // if at all possible to save space.
    552       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
    553         return Offset;
    554       // In Thumb2 mode, the negative offset is very limited. Try to avoid
    555       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
    556       if (FPOffset >= -255 && FPOffset < 0) {
    557         FrameReg = RegInfo->getFrameRegister(MF);
    558         return FPOffset;
    559       }
    560     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
    561       // Otherwise, use SP or FP, whichever is closer to the stack slot.
    562       FrameReg = RegInfo->getFrameRegister(MF);
    563       return FPOffset;
    564     }
    565   }
    566   // Use the base pointer if we have one.
    567   if (RegInfo->hasBasePointer(MF))
    568     FrameReg = RegInfo->getBaseRegister();
    569   return Offset;
    570 }
    571 
    572 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
    573                                           int FI) const {
    574   unsigned FrameReg;
    575   return getFrameIndexReference(MF, FI, FrameReg);
    576 }
    577 
    578 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
    579                                     MachineBasicBlock::iterator MI,
    580                                     const std::vector<CalleeSavedInfo> &CSI,
    581                                     unsigned StmOpc, unsigned StrOpc,
    582                                     bool NoGap,
    583                                     bool(*Func)(unsigned, bool),
    584                                     unsigned NumAlignedDPRCS2Regs,
    585                                     unsigned MIFlags) const {
    586   MachineFunction &MF = *MBB.getParent();
    587   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
    588 
    589   DebugLoc DL;
    590   if (MI != MBB.end()) DL = MI->getDebugLoc();
    591 
    592   SmallVector<std::pair<unsigned,bool>, 4> Regs;
    593   unsigned i = CSI.size();
    594   while (i != 0) {
    595     unsigned LastReg = 0;
    596     for (; i != 0; --i) {
    597       unsigned Reg = CSI[i-1].getReg();
    598       if (!(Func)(Reg, STI.isTargetIOS())) continue;
    599 
    600       // D-registers in the aligned area DPRCS2 are NOT spilled here.
    601       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
    602         continue;
    603 
    604       // Add the callee-saved register as live-in unless it's LR and
    605       // @llvm.returnaddress is called. If LR is returned for
    606       // @llvm.returnaddress then it's already added to the function and
    607       // entry block live-in sets.
    608       bool isKill = true;
    609       if (Reg == ARM::LR) {
    610         if (MF.getFrameInfo()->isReturnAddressTaken() &&
    611             MF.getRegInfo().isLiveIn(Reg))
    612           isKill = false;
    613       }
    614 
    615       if (isKill)
    616         MBB.addLiveIn(Reg);
    617 
    618       // If NoGap is true, push consecutive registers and then leave the rest
    619       // for other instructions. e.g.
    620       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
    621       if (NoGap && LastReg && LastReg != Reg-1)
    622         break;
    623       LastReg = Reg;
    624       Regs.push_back(std::make_pair(Reg, isKill));
    625     }
    626 
    627     if (Regs.empty())
    628       continue;
    629     if (Regs.size() > 1 || StrOpc== 0) {
    630       MachineInstrBuilder MIB =
    631         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
    632                        .addReg(ARM::SP).setMIFlags(MIFlags));
    633       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
    634         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
    635     } else if (Regs.size() == 1) {
    636       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
    637                                         ARM::SP)
    638         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
    639         .addReg(ARM::SP).setMIFlags(MIFlags)
    640         .addImm(-4);
    641       AddDefaultPred(MIB);
    642     }
    643     Regs.clear();
    644   }
    645 }
    646 
    647 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
    648                                    MachineBasicBlock::iterator MI,
    649                                    const std::vector<CalleeSavedInfo> &CSI,
    650                                    unsigned LdmOpc, unsigned LdrOpc,
    651                                    bool isVarArg, bool NoGap,
    652                                    bool(*Func)(unsigned, bool),
    653                                    unsigned NumAlignedDPRCS2Regs) const {
    654   MachineFunction &MF = *MBB.getParent();
    655   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
    656   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    657   DebugLoc DL = MI->getDebugLoc();
    658   unsigned RetOpcode = MI->getOpcode();
    659   bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
    660                      RetOpcode == ARM::TCRETURNri);
    661 
    662   SmallVector<unsigned, 4> Regs;
    663   unsigned i = CSI.size();
    664   while (i != 0) {
    665     unsigned LastReg = 0;
    666     bool DeleteRet = false;
    667     for (; i != 0; --i) {
    668       unsigned Reg = CSI[i-1].getReg();
    669       if (!(Func)(Reg, STI.isTargetIOS())) continue;
    670 
    671       // The aligned reloads from area DPRCS2 are not inserted here.
    672       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
    673         continue;
    674 
    675       if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
    676         Reg = ARM::PC;
    677         LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
    678         // Fold the return instruction into the LDM.
    679         DeleteRet = true;
    680       }
    681 
    682       // If NoGap is true, pop consecutive registers and then leave the rest
    683       // for other instructions. e.g.
    684       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
    685       if (NoGap && LastReg && LastReg != Reg-1)
    686         break;
    687 
    688       LastReg = Reg;
    689       Regs.push_back(Reg);
    690     }
    691 
    692     if (Regs.empty())
    693       continue;
    694     if (Regs.size() > 1 || LdrOpc == 0) {
    695       MachineInstrBuilder MIB =
    696         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
    697                        .addReg(ARM::SP));
    698       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
    699         MIB.addReg(Regs[i], getDefRegState(true));
    700       if (DeleteRet) {
    701         MIB.copyImplicitOps(&*MI);
    702         MI->eraseFromParent();
    703       }
    704       MI = MIB;
    705     } else if (Regs.size() == 1) {
    706       // If we adjusted the reg to PC from LR above, switch it back here. We
    707       // only do that for LDM.
    708       if (Regs[0] == ARM::PC)
    709         Regs[0] = ARM::LR;
    710       MachineInstrBuilder MIB =
    711         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
    712           .addReg(ARM::SP, RegState::Define)
    713           .addReg(ARM::SP);
    714       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
    715       // that refactoring is complete (eventually).
    716       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
    717         MIB.addReg(0);
    718         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
    719       } else
    720         MIB.addImm(4);
    721       AddDefaultPred(MIB);
    722     }
    723     Regs.clear();
    724   }
    725 }
    726 
    727 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
    728 /// starting from d8.  Also insert stack realignment code and leave the stack
    729 /// pointer pointing to the d8 spill slot.
    730 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
    731                                     MachineBasicBlock::iterator MI,
    732                                     unsigned NumAlignedDPRCS2Regs,
    733                                     const std::vector<CalleeSavedInfo> &CSI,
    734                                     const TargetRegisterInfo *TRI) {
    735   MachineFunction &MF = *MBB.getParent();
    736   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    737   DebugLoc DL = MI->getDebugLoc();
    738   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
    739   MachineFrameInfo &MFI = *MF.getFrameInfo();
    740 
    741   // Mark the D-register spill slots as properly aligned.  Since MFI computes
    742   // stack slot layout backwards, this can actually mean that the d-reg stack
    743   // slot offsets can be wrong. The offset for d8 will always be correct.
    744   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
    745     unsigned DNum = CSI[i].getReg() - ARM::D8;
    746     if (DNum >= 8)
    747       continue;
    748     int FI = CSI[i].getFrameIdx();
    749     // The even-numbered registers will be 16-byte aligned, the odd-numbered
    750     // registers will be 8-byte aligned.
    751     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
    752 
    753     // The stack slot for D8 needs to be maximally aligned because this is
    754     // actually the point where we align the stack pointer.  MachineFrameInfo
    755     // computes all offsets relative to the incoming stack pointer which is a
    756     // bit weird when realigning the stack.  Any extra padding for this
    757     // over-alignment is not realized because the code inserted below adjusts
    758     // the stack pointer by numregs * 8 before aligning the stack pointer.
    759     if (DNum == 0)
    760       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
    761   }
    762 
    763   // Move the stack pointer to the d8 spill slot, and align it at the same
    764   // time. Leave the stack slot address in the scratch register r4.
    765   //
    766   //   sub r4, sp, #numregs * 8
    767   //   bic r4, r4, #align - 1
    768   //   mov sp, r4
    769   //
    770   bool isThumb = AFI->isThumbFunction();
    771   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
    772   AFI->setShouldRestoreSPFromFP(true);
    773 
    774   // sub r4, sp, #numregs * 8
    775   // The immediate is <= 64, so it doesn't need any special encoding.
    776   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
    777   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
    778                               .addReg(ARM::SP)
    779                               .addImm(8 * NumAlignedDPRCS2Regs)));
    780 
    781   // bic r4, r4, #align-1
    782   Opc = isThumb ? ARM::t2BICri : ARM::BICri;
    783   unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
    784   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
    785                               .addReg(ARM::R4, RegState::Kill)
    786                               .addImm(MaxAlign - 1)));
    787 
    788   // mov sp, r4
    789   // The stack pointer must be adjusted before spilling anything, otherwise
    790   // the stack slots could be clobbered by an interrupt handler.
    791   // Leave r4 live, it is used below.
    792   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
    793   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
    794                             .addReg(ARM::R4);
    795   MIB = AddDefaultPred(MIB);
    796   if (!isThumb)
    797     AddDefaultCC(MIB);
    798 
    799   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
    800   // r4 holds the stack slot address.
    801   unsigned NextReg = ARM::D8;
    802 
    803   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
    804   // The writeback is only needed when emitting two vst1.64 instructions.
    805   if (NumAlignedDPRCS2Regs >= 6) {
    806     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
    807                                                &ARM::QQPRRegClass);
    808     MBB.addLiveIn(SupReg);
    809     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
    810                            ARM::R4)
    811                    .addReg(ARM::R4, RegState::Kill).addImm(16)
    812                    .addReg(NextReg)
    813                    .addReg(SupReg, RegState::ImplicitKill));
    814     NextReg += 4;
    815     NumAlignedDPRCS2Regs -= 4;
    816   }
    817 
    818   // We won't modify r4 beyond this point.  It currently points to the next
    819   // register to be spilled.
    820   unsigned R4BaseReg = NextReg;
    821 
    822   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
    823   if (NumAlignedDPRCS2Regs >= 4) {
    824     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
    825                                                &ARM::QQPRRegClass);
    826     MBB.addLiveIn(SupReg);
    827     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
    828                    .addReg(ARM::R4).addImm(16).addReg(NextReg)
    829                    .addReg(SupReg, RegState::ImplicitKill));
    830     NextReg += 4;
    831     NumAlignedDPRCS2Regs -= 4;
    832   }
    833 
    834   // 16-byte aligned vst1.64 with 2 d-regs.
    835   if (NumAlignedDPRCS2Regs >= 2) {
    836     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
    837                                                &ARM::QPRRegClass);
    838     MBB.addLiveIn(SupReg);
    839     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
    840                    .addReg(ARM::R4).addImm(16).addReg(SupReg));
    841     NextReg += 2;
    842     NumAlignedDPRCS2Regs -= 2;
    843   }
    844 
    845   // Finally, use a vanilla vstr.64 for the odd last register.
    846   if (NumAlignedDPRCS2Regs) {
    847     MBB.addLiveIn(NextReg);
    848     // vstr.64 uses addrmode5 which has an offset scale of 4.
    849     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
    850                    .addReg(NextReg)
    851                    .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
    852   }
    853 
    854   // The last spill instruction inserted should kill the scratch register r4.
    855   llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
    856 }
    857 
    858 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
    859 /// iterator to the following instruction.
    860 static MachineBasicBlock::iterator
    861 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
    862                         unsigned NumAlignedDPRCS2Regs) {
    863   //   sub r4, sp, #numregs * 8
    864   //   bic r4, r4, #align - 1
    865   //   mov sp, r4
    866   ++MI; ++MI; ++MI;
    867   assert(MI->mayStore() && "Expecting spill instruction");
    868 
    869   // These switches all fall through.
    870   switch(NumAlignedDPRCS2Regs) {
    871   case 7:
    872     ++MI;
    873     assert(MI->mayStore() && "Expecting spill instruction");
    874   default:
    875     ++MI;
    876     assert(MI->mayStore() && "Expecting spill instruction");
    877   case 1:
    878   case 2:
    879   case 4:
    880     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
    881     ++MI;
    882   }
    883   return MI;
    884 }
    885 
    886 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
    887 /// starting from d8.  These instructions are assumed to execute while the
    888 /// stack is still aligned, unlike the code inserted by emitPopInst.
    889 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
    890                                       MachineBasicBlock::iterator MI,
    891                                       unsigned NumAlignedDPRCS2Regs,
    892                                       const std::vector<CalleeSavedInfo> &CSI,
    893                                       const TargetRegisterInfo *TRI) {
    894   MachineFunction &MF = *MBB.getParent();
    895   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    896   DebugLoc DL = MI->getDebugLoc();
    897   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
    898 
    899   // Find the frame index assigned to d8.
    900   int D8SpillFI = 0;
    901   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
    902     if (CSI[i].getReg() == ARM::D8) {
    903       D8SpillFI = CSI[i].getFrameIdx();
    904       break;
    905     }
    906 
    907   // Materialize the address of the d8 spill slot into the scratch register r4.
    908   // This can be fairly complicated if the stack frame is large, so just use
    909   // the normal frame index elimination mechanism to do it.  This code runs as
    910   // the initial part of the epilog where the stack and base pointers haven't
    911   // been changed yet.
    912   bool isThumb = AFI->isThumbFunction();
    913   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
    914 
    915   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
    916   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
    917                               .addFrameIndex(D8SpillFI).addImm(0)));
    918 
    919   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
    920   unsigned NextReg = ARM::D8;
    921 
    922   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
    923   if (NumAlignedDPRCS2Regs >= 6) {
    924     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
    925                                                &ARM::QQPRRegClass);
    926     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
    927                    .addReg(ARM::R4, RegState::Define)
    928                    .addReg(ARM::R4, RegState::Kill).addImm(16)
    929                    .addReg(SupReg, RegState::ImplicitDefine));
    930     NextReg += 4;
    931     NumAlignedDPRCS2Regs -= 4;
    932   }
    933 
    934   // We won't modify r4 beyond this point.  It currently points to the next
    935   // register to be spilled.
    936   unsigned R4BaseReg = NextReg;
    937 
    938   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
    939   if (NumAlignedDPRCS2Regs >= 4) {
    940     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
    941                                                &ARM::QQPRRegClass);
    942     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
    943                    .addReg(ARM::R4).addImm(16)
    944                    .addReg(SupReg, RegState::ImplicitDefine));
    945     NextReg += 4;
    946     NumAlignedDPRCS2Regs -= 4;
    947   }
    948 
    949   // 16-byte aligned vld1.64 with 2 d-regs.
    950   if (NumAlignedDPRCS2Regs >= 2) {
    951     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
    952                                                &ARM::QPRRegClass);
    953     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
    954                    .addReg(ARM::R4).addImm(16));
    955     NextReg += 2;
    956     NumAlignedDPRCS2Regs -= 2;
    957   }
    958 
    959   // Finally, use a vanilla vldr.64 for the remaining odd register.
    960   if (NumAlignedDPRCS2Regs)
    961     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
    962                    .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
    963 
    964   // Last store kills r4.
    965   llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
    966 }
    967 
    968 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
    969                                         MachineBasicBlock::iterator MI,
    970                                         const std::vector<CalleeSavedInfo> &CSI,
    971                                         const TargetRegisterInfo *TRI) const {
    972   if (CSI.empty())
    973     return false;
    974 
    975   MachineFunction &MF = *MBB.getParent();
    976   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
    977 
    978   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
    979   unsigned PushOneOpc = AFI->isThumbFunction() ?
    980     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
    981   unsigned FltOpc = ARM::VSTMDDB_UPD;
    982   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
    983   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
    984                MachineInstr::FrameSetup);
    985   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
    986                MachineInstr::FrameSetup);
    987   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
    988                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
    989 
    990   // The code above does not insert spill code for the aligned DPRCS2 registers.
    991   // The stack realignment code will be inserted between the push instructions
    992   // and these spills.
    993   if (NumAlignedDPRCS2Regs)
    994     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
    995 
    996   return true;
    997 }
    998 
    999 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
   1000                                         MachineBasicBlock::iterator MI,
   1001                                         const std::vector<CalleeSavedInfo> &CSI,
   1002                                         const TargetRegisterInfo *TRI) const {
   1003   if (CSI.empty())
   1004     return false;
   1005 
   1006   MachineFunction &MF = *MBB.getParent();
   1007   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   1008   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
   1009   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
   1010 
   1011   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
   1012   // registers. Do that here instead.
   1013   if (NumAlignedDPRCS2Regs)
   1014     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
   1015 
   1016   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
   1017   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
   1018   unsigned FltOpc = ARM::VLDMDIA_UPD;
   1019   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
   1020               NumAlignedDPRCS2Regs);
   1021   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
   1022               &isARMArea2Register, 0);
   1023   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
   1024               &isARMArea1Register, 0);
   1025 
   1026   return true;
   1027 }
   1028 
   1029 // FIXME: Make generic?
   1030 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
   1031                                        const ARMBaseInstrInfo &TII) {
   1032   unsigned FnSize = 0;
   1033   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
   1034        MBBI != E; ++MBBI) {
   1035     const MachineBasicBlock &MBB = *MBBI;
   1036     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
   1037          I != E; ++I)
   1038       FnSize += TII.GetInstSizeInBytes(I);
   1039   }
   1040   return FnSize;
   1041 }
   1042 
   1043 /// estimateRSStackSizeLimit - Look at each instruction that references stack
   1044 /// frames and return the stack size limit beyond which some of these
   1045 /// instructions will require a scratch register during their expansion later.
   1046 // FIXME: Move to TII?
   1047 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
   1048                                          const TargetFrameLowering *TFI) {
   1049   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   1050   unsigned Limit = (1 << 12) - 1;
   1051   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
   1052     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
   1053          I != E; ++I) {
   1054       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
   1055         if (!I->getOperand(i).isFI()) continue;
   1056 
   1057         // When using ADDri to get the address of a stack object, 255 is the
   1058         // largest offset guaranteed to fit in the immediate offset.
   1059         if (I->getOpcode() == ARM::ADDri) {
   1060           Limit = std::min(Limit, (1U << 8) - 1);
   1061           break;
   1062         }
   1063 
   1064         // Otherwise check the addressing mode.
   1065         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
   1066         case ARMII::AddrMode3:
   1067         case ARMII::AddrModeT2_i8:
   1068           Limit = std::min(Limit, (1U << 8) - 1);
   1069           break;
   1070         case ARMII::AddrMode5:
   1071         case ARMII::AddrModeT2_i8s4:
   1072           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
   1073           break;
   1074         case ARMII::AddrModeT2_i12:
   1075           // i12 supports only positive offset so these will be converted to
   1076           // i8 opcodes. See llvm::rewriteT2FrameIndex.
   1077           if (TFI->hasFP(MF) && AFI->hasStackFrame())
   1078             Limit = std::min(Limit, (1U << 8) - 1);
   1079           break;
   1080         case ARMII::AddrMode4:
   1081         case ARMII::AddrMode6:
   1082           // Addressing modes 4 & 6 (load/store) instructions can't encode an
   1083           // immediate offset for stack references.
   1084           return 0;
   1085         default:
   1086           break;
   1087         }
   1088         break; // At most one FI per instruction
   1089       }
   1090     }
   1091   }
   1092 
   1093   return Limit;
   1094 }
   1095 
   1096 // In functions that realign the stack, it can be an advantage to spill the
   1097 // callee-saved vector registers after realigning the stack. The vst1 and vld1
   1098 // instructions take alignment hints that can improve performance.
   1099 //
   1100 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
   1101   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
   1102   if (!SpillAlignedNEONRegs)
   1103     return;
   1104 
   1105   // Naked functions don't spill callee-saved registers.
   1106   if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
   1107                                                      Attribute::Naked))
   1108     return;
   1109 
   1110   // We are planning to use NEON instructions vst1 / vld1.
   1111   if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
   1112     return;
   1113 
   1114   // Don't bother if the default stack alignment is sufficiently high.
   1115   if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
   1116     return;
   1117 
   1118   // Aligned spills require stack realignment.
   1119   const ARMBaseRegisterInfo *RegInfo =
   1120     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
   1121   if (!RegInfo->canRealignStack(MF))
   1122     return;
   1123 
   1124   // We always spill contiguous d-registers starting from d8. Count how many
   1125   // needs spilling.  The register allocator will almost always use the
   1126   // callee-saved registers in order, but it can happen that there are holes in
   1127   // the range.  Registers above the hole will be spilled to the standard DPRCS
   1128   // area.
   1129   MachineRegisterInfo &MRI = MF.getRegInfo();
   1130   unsigned NumSpills = 0;
   1131   for (; NumSpills < 8; ++NumSpills)
   1132     if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
   1133       break;
   1134 
   1135   // Don't do this for just one d-register. It's not worth it.
   1136   if (NumSpills < 2)
   1137     return;
   1138 
   1139   // Spill the first NumSpills D-registers after realigning the stack.
   1140   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
   1141 
   1142   // A scratch register is required for the vst1 / vld1 instructions.
   1143   MF.getRegInfo().setPhysRegUsed(ARM::R4);
   1144 }
   1145 
   1146 void
   1147 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
   1148                                                        RegScavenger *RS) const {
   1149   // This tells PEI to spill the FP as if it is any other callee-save register
   1150   // to take advantage the eliminateFrameIndex machinery. This also ensures it
   1151   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
   1152   // to combine multiple loads / stores.
   1153   bool CanEliminateFrame = true;
   1154   bool CS1Spilled = false;
   1155   bool LRSpilled = false;
   1156   unsigned NumGPRSpills = 0;
   1157   SmallVector<unsigned, 4> UnspilledCS1GPRs;
   1158   SmallVector<unsigned, 4> UnspilledCS2GPRs;
   1159   const ARMBaseRegisterInfo *RegInfo =
   1160     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
   1161   const ARMBaseInstrInfo &TII =
   1162     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
   1163   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   1164   MachineFrameInfo *MFI = MF.getFrameInfo();
   1165   MachineRegisterInfo &MRI = MF.getRegInfo();
   1166   unsigned FramePtr = RegInfo->getFrameRegister(MF);
   1167 
   1168   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
   1169   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
   1170   // since it's not always possible to restore sp from fp in a single
   1171   // instruction.
   1172   // FIXME: It will be better just to find spare register here.
   1173   if (AFI->isThumb2Function() &&
   1174       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
   1175     MRI.setPhysRegUsed(ARM::R4);
   1176 
   1177   if (AFI->isThumb1OnlyFunction()) {
   1178     // Spill LR if Thumb1 function uses variable length argument lists.
   1179     if (AFI->getArgRegsSaveSize() > 0)
   1180       MRI.setPhysRegUsed(ARM::LR);
   1181 
   1182     // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
   1183     // for sure what the stack size will be, but for this, an estimate is good
   1184     // enough. If there anything changes it, it'll be a spill, which implies
   1185     // we've used all the registers and so R4 is already used, so not marking
   1186     // it here will be OK.
   1187     // FIXME: It will be better just to find spare register here.
   1188     unsigned StackSize = MFI->estimateStackSize(MF);
   1189     if (MFI->hasVarSizedObjects() || StackSize > 508)
   1190       MRI.setPhysRegUsed(ARM::R4);
   1191   }
   1192 
   1193   // See if we can spill vector registers to aligned stack.
   1194   checkNumAlignedDPRCS2Regs(MF);
   1195 
   1196   // Spill the BasePtr if it's used.
   1197   if (RegInfo->hasBasePointer(MF))
   1198     MRI.setPhysRegUsed(RegInfo->getBaseRegister());
   1199 
   1200   // Don't spill FP if the frame can be eliminated. This is determined
   1201   // by scanning the callee-save registers to see if any is used.
   1202   const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
   1203   for (unsigned i = 0; CSRegs[i]; ++i) {
   1204     unsigned Reg = CSRegs[i];
   1205     bool Spilled = false;
   1206     if (MRI.isPhysRegUsed(Reg)) {
   1207       Spilled = true;
   1208       CanEliminateFrame = false;
   1209     }
   1210 
   1211     if (!ARM::GPRRegClass.contains(Reg))
   1212       continue;
   1213 
   1214     if (Spilled) {
   1215       NumGPRSpills++;
   1216 
   1217       if (!STI.isTargetIOS()) {
   1218         if (Reg == ARM::LR)
   1219           LRSpilled = true;
   1220         CS1Spilled = true;
   1221         continue;
   1222       }
   1223 
   1224       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
   1225       switch (Reg) {
   1226       case ARM::LR:
   1227         LRSpilled = true;
   1228         // Fallthrough
   1229       case ARM::R4: case ARM::R5:
   1230       case ARM::R6: case ARM::R7:
   1231         CS1Spilled = true;
   1232         break;
   1233       default:
   1234         break;
   1235       }
   1236     } else {
   1237       if (!STI.isTargetIOS()) {
   1238         UnspilledCS1GPRs.push_back(Reg);
   1239         continue;
   1240       }
   1241 
   1242       switch (Reg) {
   1243       case ARM::R4: case ARM::R5:
   1244       case ARM::R6: case ARM::R7:
   1245       case ARM::LR:
   1246         UnspilledCS1GPRs.push_back(Reg);
   1247         break;
   1248       default:
   1249         UnspilledCS2GPRs.push_back(Reg);
   1250         break;
   1251       }
   1252     }
   1253   }
   1254 
   1255   bool ForceLRSpill = false;
   1256   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
   1257     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
   1258     // Force LR to be spilled if the Thumb function size is > 2048. This enables
   1259     // use of BL to implement far jump. If it turns out that it's not needed
   1260     // then the branch fix up path will undo it.
   1261     if (FnSize >= (1 << 11)) {
   1262       CanEliminateFrame = false;
   1263       ForceLRSpill = true;
   1264     }
   1265   }
   1266 
   1267   // If any of the stack slot references may be out of range of an immediate
   1268   // offset, make sure a register (or a spill slot) is available for the
   1269   // register scavenger. Note that if we're indexing off the frame pointer, the
   1270   // effective stack size is 4 bytes larger since the FP points to the stack
   1271   // slot of the previous FP. Also, if we have variable sized objects in the
   1272   // function, stack slot references will often be negative, and some of
   1273   // our instructions are positive-offset only, so conservatively consider
   1274   // that case to want a spill slot (or register) as well. Similarly, if
   1275   // the function adjusts the stack pointer during execution and the
   1276   // adjustments aren't already part of our stack size estimate, our offset
   1277   // calculations may be off, so be conservative.
   1278   // FIXME: We could add logic to be more precise about negative offsets
   1279   //        and which instructions will need a scratch register for them. Is it
   1280   //        worth the effort and added fragility?
   1281   bool BigStack =
   1282     (RS &&
   1283      (MFI->estimateStackSize(MF) +
   1284       ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
   1285       estimateRSStackSizeLimit(MF, this)))
   1286     || MFI->hasVarSizedObjects()
   1287     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
   1288 
   1289   bool ExtraCSSpill = false;
   1290   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
   1291     AFI->setHasStackFrame(true);
   1292 
   1293     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
   1294     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
   1295     if (!LRSpilled && CS1Spilled) {
   1296       MRI.setPhysRegUsed(ARM::LR);
   1297       NumGPRSpills++;
   1298       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
   1299                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
   1300       ForceLRSpill = false;
   1301       ExtraCSSpill = true;
   1302     }
   1303 
   1304     if (hasFP(MF)) {
   1305       MRI.setPhysRegUsed(FramePtr);
   1306       NumGPRSpills++;
   1307     }
   1308 
   1309     // If stack and double are 8-byte aligned and we are spilling an odd number
   1310     // of GPRs, spill one extra callee save GPR so we won't have to pad between
   1311     // the integer and double callee save areas.
   1312     unsigned TargetAlign = getStackAlignment();
   1313     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
   1314       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
   1315         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
   1316           unsigned Reg = UnspilledCS1GPRs[i];
   1317           // Don't spill high register if the function is thumb1
   1318           if (!AFI->isThumb1OnlyFunction() ||
   1319               isARMLowRegister(Reg) || Reg == ARM::LR) {
   1320             MRI.setPhysRegUsed(Reg);
   1321             if (!MRI.isReserved(Reg))
   1322               ExtraCSSpill = true;
   1323             break;
   1324           }
   1325         }
   1326       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
   1327         unsigned Reg = UnspilledCS2GPRs.front();
   1328         MRI.setPhysRegUsed(Reg);
   1329         if (!MRI.isReserved(Reg))
   1330           ExtraCSSpill = true;
   1331       }
   1332     }
   1333 
   1334     // Estimate if we might need to scavenge a register at some point in order
   1335     // to materialize a stack offset. If so, either spill one additional
   1336     // callee-saved register or reserve a special spill slot to facilitate
   1337     // register scavenging. Thumb1 needs a spill slot for stack pointer
   1338     // adjustments also, even when the frame itself is small.
   1339     if (BigStack && !ExtraCSSpill) {
   1340       // If any non-reserved CS register isn't spilled, just spill one or two
   1341       // extra. That should take care of it!
   1342       unsigned NumExtras = TargetAlign / 4;
   1343       SmallVector<unsigned, 2> Extras;
   1344       while (NumExtras && !UnspilledCS1GPRs.empty()) {
   1345         unsigned Reg = UnspilledCS1GPRs.back();
   1346         UnspilledCS1GPRs.pop_back();
   1347         if (!MRI.isReserved(Reg) &&
   1348             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
   1349              Reg == ARM::LR)) {
   1350           Extras.push_back(Reg);
   1351           NumExtras--;
   1352         }
   1353       }
   1354       // For non-Thumb1 functions, also check for hi-reg CS registers
   1355       if (!AFI->isThumb1OnlyFunction()) {
   1356         while (NumExtras && !UnspilledCS2GPRs.empty()) {
   1357           unsigned Reg = UnspilledCS2GPRs.back();
   1358           UnspilledCS2GPRs.pop_back();
   1359           if (!MRI.isReserved(Reg)) {
   1360             Extras.push_back(Reg);
   1361             NumExtras--;
   1362           }
   1363         }
   1364       }
   1365       if (Extras.size() && NumExtras == 0) {
   1366         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
   1367           MRI.setPhysRegUsed(Extras[i]);
   1368         }
   1369       } else if (!AFI->isThumb1OnlyFunction()) {
   1370         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
   1371         // closest to SP or frame pointer.
   1372         const TargetRegisterClass *RC = &ARM::GPRRegClass;
   1373         RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
   1374                                                            RC->getAlignment(),
   1375                                                            false));
   1376       }
   1377     }
   1378   }
   1379 
   1380   if (ForceLRSpill) {
   1381     MRI.setPhysRegUsed(ARM::LR);
   1382     AFI->setLRIsSpilledForFarJump(true);
   1383   }
   1384 }
   1385 
   1386 
   1387 void ARMFrameLowering::
   1388 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
   1389                               MachineBasicBlock::iterator I) const {
   1390   const ARMBaseInstrInfo &TII =
   1391     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
   1392   if (!hasReservedCallFrame(MF)) {
   1393     // If we have alloca, convert as follows:
   1394     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
   1395     // ADJCALLSTACKUP   -> add, sp, sp, amount
   1396     MachineInstr *Old = I;
   1397     DebugLoc dl = Old->getDebugLoc();
   1398     unsigned Amount = Old->getOperand(0).getImm();
   1399     if (Amount != 0) {
   1400       // We need to keep the stack aligned properly.  To do this, we round the
   1401       // amount of space needed for the outgoing arguments up to the next
   1402       // alignment boundary.
   1403       unsigned Align = getStackAlignment();
   1404       Amount = (Amount+Align-1)/Align*Align;
   1405 
   1406       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
   1407       assert(!AFI->isThumb1OnlyFunction() &&
   1408              "This eliminateCallFramePseudoInstr does not support Thumb1!");
   1409       bool isARM = !AFI->isThumbFunction();
   1410 
   1411       // Replace the pseudo instruction with a new instruction...
   1412       unsigned Opc = Old->getOpcode();
   1413       int PIdx = Old->findFirstPredOperandIdx();
   1414       ARMCC::CondCodes Pred = (PIdx == -1)
   1415         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
   1416       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
   1417         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
   1418         unsigned PredReg = Old->getOperand(2).getReg();
   1419         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
   1420                      Pred, PredReg);
   1421       } else {
   1422         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
   1423         unsigned PredReg = Old->getOperand(3).getReg();
   1424         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
   1425         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
   1426                      Pred, PredReg);
   1427       }
   1428     }
   1429   }
   1430   MBB.erase(I);
   1431 }
   1432 
   1433