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