Don't merge restore with tail call instruction.
[oota-llvm.git] / lib / Target / ARM / ARMFrameLowering.cpp
1 //=======- ARMFrameLowering.cpp - ARM Frame Information --------*- C++ -*-====//
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 "ARMAddressingModes.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMMachineFunctionInfo.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/Target/TargetOptions.h"
25
26 using namespace llvm;
27
28 /// hasFP - Return true if the specified function should have a dedicated frame
29 /// pointer register.  This is true if the function has variable sized allocas
30 /// or if frame pointer elimination is disabled.
31 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
32   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
33
34   // Mac OS X requires FP not to be clobbered for backtracing purpose.
35   if (STI.isTargetDarwin())
36     return true;
37
38   const MachineFrameInfo *MFI = MF.getFrameInfo();
39   // Always eliminate non-leaf frame pointers.
40   return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
41           RegInfo->needsStackRealignment(MF) ||
42           MFI->hasVarSizedObjects() ||
43           MFI->isFrameAddressTaken());
44 }
45
46 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
47 /// not required, we reserve argument space for call sites in the function
48 /// immediately on entry to the current function.  This eliminates the need for
49 /// add/sub sp brackets around call sites.  Returns true if the call frame is
50 /// included as part of the stack frame.
51 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
52   const MachineFrameInfo *FFI = MF.getFrameInfo();
53   unsigned CFSize = FFI->getMaxCallFrameSize();
54   // It's not always a good idea to include the call frame as part of the
55   // stack frame. ARM (especially Thumb) has small immediate offset to
56   // address the stack frame. So a large call frame can cause poor codegen
57   // and may even makes it impossible to scavenge a register.
58   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
59     return false;
60
61   return !MF.getFrameInfo()->hasVarSizedObjects();
62 }
63
64 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
65 /// call frame pseudos can be simplified.  Unlike most targets, having a FP
66 /// is not sufficient here since we still may reference some objects via SP
67 /// even when FP is available in Thumb2 mode.
68 bool
69 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
70   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
71 }
72
73 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
74   for (unsigned i = 0; CSRegs[i]; ++i)
75     if (Reg == CSRegs[i])
76       return true;
77   return false;
78 }
79
80 static bool isCSRestore(MachineInstr *MI,
81                         const ARMBaseInstrInfo &TII,
82                         const unsigned *CSRegs) {
83   // Integer spill area is handled with "pop".
84   if (MI->getOpcode() == ARM::LDMIA_RET ||
85       MI->getOpcode() == ARM::t2LDMIA_RET ||
86       MI->getOpcode() == ARM::LDMIA_UPD ||
87       MI->getOpcode() == ARM::t2LDMIA_UPD ||
88       MI->getOpcode() == ARM::VLDMDIA_UPD) {
89     // The first two operands are predicates. The last two are
90     // imp-def and imp-use of SP. Check everything in between.
91     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
92       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
93         return false;
94     return true;
95   }
96   if ((MI->getOpcode() == ARM::LDR_POST ||
97        MI->getOpcode() == ARM::t2LDR_POST) &&
98       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
99       MI->getOperand(1).getReg() == ARM::SP)
100     return true;
101
102   return false;
103 }
104
105 static void
106 emitSPUpdate(bool isARM,
107              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
108              DebugLoc dl, const ARMBaseInstrInfo &TII,
109              int NumBytes,
110              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
111   if (isARM)
112     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
113                             Pred, PredReg, TII);
114   else
115     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
116                            Pred, PredReg, TII);
117 }
118
119 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
120   MachineBasicBlock &MBB = MF.front();
121   MachineBasicBlock::iterator MBBI = MBB.begin();
122   MachineFrameInfo  *MFI = MF.getFrameInfo();
123   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
124   const ARMBaseRegisterInfo *RegInfo =
125     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
126   const ARMBaseInstrInfo &TII =
127     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
128   assert(!AFI->isThumb1OnlyFunction() &&
129          "This emitPrologue does not support Thumb1!");
130   bool isARM = !AFI->isThumbFunction();
131   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
132   unsigned NumBytes = MFI->getStackSize();
133   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
134   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
135   unsigned FramePtr = RegInfo->getFrameRegister(MF);
136
137   // Determine the sizes of each callee-save spill areas and record which frame
138   // belongs to which callee-save spill areas.
139   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
140   int FramePtrSpillFI = 0;
141
142   // Allocate the vararg register save area. This is not counted in NumBytes.
143   if (VARegSaveSize)
144     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
145
146   if (!AFI->hasStackFrame()) {
147     if (NumBytes != 0)
148       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
149     return;
150   }
151
152   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
153     unsigned Reg = CSI[i].getReg();
154     int FI = CSI[i].getFrameIdx();
155     switch (Reg) {
156     case ARM::R4:
157     case ARM::R5:
158     case ARM::R6:
159     case ARM::R7:
160     case ARM::LR:
161       if (Reg == FramePtr)
162         FramePtrSpillFI = FI;
163       AFI->addGPRCalleeSavedArea1Frame(FI);
164       GPRCS1Size += 4;
165       break;
166     case ARM::R8:
167     case ARM::R9:
168     case ARM::R10:
169     case ARM::R11:
170       if (Reg == FramePtr)
171         FramePtrSpillFI = FI;
172       if (STI.isTargetDarwin()) {
173         AFI->addGPRCalleeSavedArea2Frame(FI);
174         GPRCS2Size += 4;
175       } else {
176         AFI->addGPRCalleeSavedArea1Frame(FI);
177         GPRCS1Size += 4;
178       }
179       break;
180     default:
181       AFI->addDPRCalleeSavedAreaFrame(FI);
182       DPRCSSize += 8;
183     }
184   }
185
186   // Move past area 1.
187   if (GPRCS1Size > 0) MBBI++;
188
189   // Set FP to point to the stack slot that contains the previous FP.
190   // For Darwin, FP is R7, which has now been stored in spill area 1.
191   // Otherwise, if this is not Darwin, all the callee-saved registers go
192   // into spill area 1, including the FP in R11.  In either case, it is
193   // now safe to emit this assignment.
194   bool HasFP = hasFP(MF);
195   if (HasFP) {
196     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
197     MachineInstrBuilder MIB =
198       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
199       .addFrameIndex(FramePtrSpillFI).addImm(0);
200     AddDefaultCC(AddDefaultPred(MIB));
201   }
202
203   // Move past area 2.
204   if (GPRCS2Size > 0) MBBI++;
205
206   // Determine starting offsets of spill areas.
207   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
208   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
209   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
210   if (HasFP)
211     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
212                                 NumBytes);
213   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
214   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
215   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
216
217   // Move past area 3.
218   if (DPRCSSize > 0) MBBI++;
219
220   NumBytes = DPRCSOffset;
221   if (NumBytes) {
222     // Adjust SP after all the callee-save spills.
223     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
224     if (HasFP && isARM)
225       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
226       // Note it's not safe to do this in Thumb2 mode because it would have
227       // taken two instructions:
228       // mov sp, r7
229       // sub sp, #24
230       // If an interrupt is taken between the two instructions, then sp is in
231       // an inconsistent state (pointing to the middle of callee-saved area).
232       // The interrupt handler can end up clobbering the registers.
233       AFI->setShouldRestoreSPFromFP(true);
234   }
235
236   if (STI.isTargetELF() && hasFP(MF))
237     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
238                              AFI->getFramePtrSpillOffset());
239
240   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
241   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
242   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
243
244   // If we need dynamic stack realignment, do it here. Be paranoid and make
245   // sure if we also have VLAs, we have a base pointer for frame access.
246   if (RegInfo->needsStackRealignment(MF)) {
247     unsigned MaxAlign = MFI->getMaxAlignment();
248     assert (!AFI->isThumb1OnlyFunction());
249     if (!AFI->isThumbFunction()) {
250       // Emit bic sp, sp, MaxAlign
251       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
252                                           TII.get(ARM::BICri), ARM::SP)
253                                   .addReg(ARM::SP, RegState::Kill)
254                                   .addImm(MaxAlign-1)));
255     } else {
256       // We cannot use sp as source/dest register here, thus we're emitting the
257       // following sequence:
258       // mov r4, sp
259       // bic r4, r4, MaxAlign
260       // mov sp, r4
261       // FIXME: It will be better just to find spare register here.
262       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
263         .addReg(ARM::SP, RegState::Kill);
264       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
265                                           TII.get(ARM::t2BICri), ARM::R4)
266                                   .addReg(ARM::R4, RegState::Kill)
267                                   .addImm(MaxAlign-1)));
268       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
269         .addReg(ARM::R4, RegState::Kill);
270     }
271
272     AFI->setShouldRestoreSPFromFP(true);
273   }
274
275   // If we need a base pointer, set it up here. It's whatever the value
276   // of the stack pointer is at this point. Any variable size objects
277   // will be allocated after this, so we can still use the base pointer
278   // to reference locals.
279   if (RegInfo->hasBasePointer(MF)) {
280     if (isARM)
281       BuildMI(MBB, MBBI, dl,
282               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
283         .addReg(ARM::SP)
284         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
285     else
286       BuildMI(MBB, MBBI, dl,
287               TII.get(ARM::tMOVgpr2gpr), RegInfo->getBaseRegister())
288         .addReg(ARM::SP);
289   }
290
291   // If the frame has variable sized objects then the epilogue must restore
292   // the sp from fp. We can assume there's an FP here since hasFP already
293   // checks for hasVarSizedObjects.
294   if (MFI->hasVarSizedObjects())
295     AFI->setShouldRestoreSPFromFP(true);
296 }
297
298 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
299                                     MachineBasicBlock &MBB) const {
300   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
301   assert(MBBI->getDesc().isReturn() &&
302          "Can only insert epilog into returning blocks");
303   unsigned RetOpcode = MBBI->getOpcode();
304   DebugLoc dl = MBBI->getDebugLoc();
305   MachineFrameInfo *MFI = MF.getFrameInfo();
306   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
307   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
308   const ARMBaseInstrInfo &TII =
309     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
310   assert(!AFI->isThumb1OnlyFunction() &&
311          "This emitEpilogue does not support Thumb1!");
312   bool isARM = !AFI->isThumbFunction();
313
314   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
315   int NumBytes = (int)MFI->getStackSize();
316   unsigned FramePtr = RegInfo->getFrameRegister(MF);
317
318   if (!AFI->hasStackFrame()) {
319     if (NumBytes != 0)
320       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
321   } else {
322     // Unwind MBBI to point to first LDR / VLDRD.
323     const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
324     if (MBBI != MBB.begin()) {
325       do
326         --MBBI;
327       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
328       if (!isCSRestore(MBBI, TII, CSRegs))
329         ++MBBI;
330     }
331
332     // Move SP to start of FP callee save spill area.
333     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
334                  AFI->getGPRCalleeSavedArea2Size() +
335                  AFI->getDPRCalleeSavedAreaSize());
336
337     // Reset SP based on frame pointer only if the stack frame extends beyond
338     // frame pointer stack slot or target is ELF and the function has FP.
339     if (AFI->shouldRestoreSPFromFP()) {
340       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
341       if (NumBytes) {
342         if (isARM)
343           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
344                                   ARMCC::AL, 0, TII);
345         else {
346           // It's not possible to restore SP from FP in a single instruction.
347           // For Darwin, this looks like:
348           // mov sp, r7
349           // sub sp, #24
350           // This is bad, if an interrupt is taken after the mov, sp is in an
351           // inconsistent state.
352           // Use the first callee-saved register as a scratch register.
353           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
354                  "No scratch register to restore SP from FP!");
355           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
356                                  ARMCC::AL, 0, TII);
357           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
358             .addReg(ARM::R4);
359         }
360       } else {
361         // Thumb2 or ARM.
362         if (isARM)
363           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
364             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
365         else
366           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
367             .addReg(FramePtr);
368       }
369     } else if (NumBytes)
370       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
371
372     // Increment past our save areas.
373     if (AFI->getDPRCalleeSavedAreaSize()) MBBI++;
374     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
375     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
376   }
377
378   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
379       RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
380     // Tail call return: adjust the stack pointer and jump to callee.
381     MBBI = MBB.getLastNonDebugInstr();
382     MachineOperand &JumpTarget = MBBI->getOperand(0);
383
384     // Jump to label or value in register.
385     if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND) {
386       unsigned TCOpcode = (RetOpcode == ARM::TCRETURNdi)
387         ? (STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)
388         : (STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND);
389       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
390       if (JumpTarget.isGlobal())
391         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
392                              JumpTarget.getTargetFlags());
393       else {
394         assert(JumpTarget.isSymbol());
395         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
396                               JumpTarget.getTargetFlags());
397       }
398     } else if (RetOpcode == ARM::TCRETURNri) {
399       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
400         addReg(JumpTarget.getReg(), RegState::Kill);
401     } else if (RetOpcode == ARM::TCRETURNriND) {
402       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
403         addReg(JumpTarget.getReg(), RegState::Kill);
404     }
405
406     MachineInstr *NewMI = prior(MBBI);
407     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
408       NewMI->addOperand(MBBI->getOperand(i));
409
410     // Delete the pseudo instruction TCRETURN.
411     MBB.erase(MBBI);
412   }
413
414   if (VARegSaveSize)
415     emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
416 }
417
418 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
419 /// debug info.  It's the same as what we use for resolving the code-gen
420 /// references for now.  FIXME: This can go wrong when references are
421 /// SP-relative and simple call frames aren't used.
422 int
423 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
424                                          unsigned &FrameReg) const {
425   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
426 }
427
428 int
429 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
430                                              int FI,
431                                              unsigned &FrameReg,
432                                              int SPAdj) const {
433   const MachineFrameInfo *MFI = MF.getFrameInfo();
434   const ARMBaseRegisterInfo *RegInfo =
435     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
436   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
437   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
438   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
439   bool isFixed = MFI->isFixedObjectIndex(FI);
440
441   FrameReg = ARM::SP;
442   Offset += SPAdj;
443   if (AFI->isGPRCalleeSavedArea1Frame(FI))
444     return Offset - AFI->getGPRCalleeSavedArea1Offset();
445   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
446     return Offset - AFI->getGPRCalleeSavedArea2Offset();
447   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
448     return Offset - AFI->getDPRCalleeSavedAreaOffset();
449
450   // When dynamically realigning the stack, use the frame pointer for
451   // parameters, and the stack/base pointer for locals.
452   if (RegInfo->needsStackRealignment(MF)) {
453     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
454     if (isFixed) {
455       FrameReg = RegInfo->getFrameRegister(MF);
456       Offset = FPOffset;
457     } else if (MFI->hasVarSizedObjects()) {
458       assert(RegInfo->hasBasePointer(MF) &&
459              "VLAs and dynamic stack alignment, but missing base pointer!");
460       FrameReg = RegInfo->getBaseRegister();
461     }
462     return Offset;
463   }
464
465   // If there is a frame pointer, use it when we can.
466   if (hasFP(MF) && AFI->hasStackFrame()) {
467     // Use frame pointer to reference fixed objects. Use it for locals if
468     // there are VLAs (and thus the SP isn't reliable as a base).
469     if (isFixed || (MFI->hasVarSizedObjects() &&
470                     !RegInfo->hasBasePointer(MF))) {
471       FrameReg = RegInfo->getFrameRegister(MF);
472       return FPOffset;
473     } else if (MFI->hasVarSizedObjects()) {
474       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
475       // Try to use the frame pointer if we can, else use the base pointer
476       // since it's available. This is handy for the emergency spill slot, in
477       // particular.
478       if (AFI->isThumb2Function()) {
479         if (FPOffset >= -255 && FPOffset < 0) {
480           FrameReg = RegInfo->getFrameRegister(MF);
481           return FPOffset;
482         }
483       } else
484         FrameReg = RegInfo->getBaseRegister();
485     } else if (AFI->isThumb2Function()) {
486       // In Thumb2 mode, the negative offset is very limited. Try to avoid
487       // out of range references.
488       if (FPOffset >= -255 && FPOffset < 0) {
489         FrameReg = RegInfo->getFrameRegister(MF);
490         return FPOffset;
491       }
492     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
493       // Otherwise, use SP or FP, whichever is closer to the stack slot.
494       FrameReg = RegInfo->getFrameRegister(MF);
495       return FPOffset;
496     }
497   }
498   // Use the base pointer if we have one.
499   if (RegInfo->hasBasePointer(MF))
500     FrameReg = RegInfo->getBaseRegister();
501   return Offset;
502 }
503
504 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
505                                           int FI) const {
506   unsigned FrameReg;
507   return getFrameIndexReference(MF, FI, FrameReg);
508 }
509
510 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
511                                     MachineBasicBlock::iterator MI,
512                                     const std::vector<CalleeSavedInfo> &CSI,
513                                     unsigned StmOpc, unsigned StrOpc,
514                                     bool NoGap,
515                                     bool(*Func)(unsigned, bool)) const {
516   MachineFunction &MF = *MBB.getParent();
517   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
518
519   DebugLoc DL;
520   if (MI != MBB.end()) DL = MI->getDebugLoc();
521
522   SmallVector<std::pair<unsigned,bool>, 4> Regs;
523   unsigned i = CSI.size();
524   while (i != 0) {
525     unsigned LastReg = 0;
526     for (; i != 0; --i) {
527       unsigned Reg = CSI[i-1].getReg();
528       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
529
530       // Add the callee-saved register as live-in unless it's LR and
531       // @llvm.returnaddress is called. If LR is returned for
532       // @llvm.returnaddress then it's already added to the function and
533       // entry block live-in sets.
534       bool isKill = true;
535       if (Reg == ARM::LR) {
536         if (MF.getFrameInfo()->isReturnAddressTaken() &&
537             MF.getRegInfo().isLiveIn(Reg))
538           isKill = false;
539       }
540
541       if (isKill)
542         MBB.addLiveIn(Reg);
543
544       // If NoGap is true, push consecutive registers and then leave the rest
545       // for other instructions. e.g.
546       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
547       if (NoGap && LastReg && LastReg != Reg-1)
548         break;
549       LastReg = Reg;
550       Regs.push_back(std::make_pair(Reg, isKill));
551     }
552
553     if (Regs.empty())
554       continue;
555     if (Regs.size() > 1 || StrOpc== 0) {
556       MachineInstrBuilder MIB =
557         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
558                        .addReg(ARM::SP));
559       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
560         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
561     } else if (Regs.size() == 1) {
562       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
563                                         ARM::SP)
564         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
565         .addReg(ARM::SP);
566       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
567       // that refactoring is complete (eventually).
568       if (StrOpc == ARM::STR_PRE) {
569         MIB.addReg(0);
570         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::sub, 4, ARM_AM::no_shift));
571       } else
572         MIB.addImm(-4);
573       AddDefaultPred(MIB);
574     }
575     Regs.clear();
576   }
577 }
578
579 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
580                                    MachineBasicBlock::iterator MI,
581                                    const std::vector<CalleeSavedInfo> &CSI,
582                                    unsigned LdmOpc, unsigned LdrOpc,
583                                    bool isVarArg, bool NoGap,
584                                    bool(*Func)(unsigned, bool)) const {
585   MachineFunction &MF = *MBB.getParent();
586   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
587   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
588   DebugLoc DL = MI->getDebugLoc();
589   unsigned RetOpcode = MI->getOpcode();
590   bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
591                      RetOpcode == ARM::TCRETURNdiND ||
592                      RetOpcode == ARM::TCRETURNri ||
593                      RetOpcode == ARM::TCRETURNriND);
594
595   SmallVector<unsigned, 4> Regs;
596   unsigned i = CSI.size();
597   while (i != 0) {
598     unsigned LastReg = 0;
599     bool DeleteRet = false;
600     for (; i != 0; --i) {
601       unsigned Reg = CSI[i-1].getReg();
602       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
603
604       if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
605         Reg = ARM::PC;
606         LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
607         // Fold the return instruction into the LDM.
608         DeleteRet = true;
609       }
610
611       // If NoGap is true, pop consecutive registers and then leave the rest
612       // for other instructions. e.g.
613       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
614       if (NoGap && LastReg && LastReg != Reg-1)
615         break;
616
617       LastReg = Reg;
618       Regs.push_back(Reg);
619     }
620
621     if (Regs.empty())
622       continue;
623     if (Regs.size() > 1 || LdrOpc == 0) {
624       MachineInstrBuilder MIB =
625         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
626                        .addReg(ARM::SP));
627       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
628         MIB.addReg(Regs[i], getDefRegState(true));
629       if (DeleteRet)
630         MI->eraseFromParent();
631       MI = MIB;
632     } else if (Regs.size() == 1) {
633       // If we adjusted the reg to PC from LR above, switch it back here. We
634       // only do that for LDM.
635       if (Regs[0] == ARM::PC)
636         Regs[0] = ARM::LR;
637       MachineInstrBuilder MIB =
638         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
639           .addReg(ARM::SP, RegState::Define)
640           .addReg(ARM::SP);
641       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
642       // that refactoring is complete (eventually).
643       if (LdrOpc == ARM::LDR_POST) {
644         MIB.addReg(0);
645         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
646       } else
647         MIB.addImm(4);
648       AddDefaultPred(MIB);
649     }
650     Regs.clear();
651   }
652 }
653
654 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
655                                         MachineBasicBlock::iterator MI,
656                                         const std::vector<CalleeSavedInfo> &CSI,
657                                         const TargetRegisterInfo *TRI) const {
658   if (CSI.empty())
659     return false;
660
661   MachineFunction &MF = *MBB.getParent();
662   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
663
664   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
665   unsigned PushOneOpc = AFI->isThumbFunction() ? ARM::t2STR_PRE : ARM::STR_PRE;
666   unsigned FltOpc = ARM::VSTMDDB_UPD;
667   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register);
668   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register);
669   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register);
670
671   return true;
672 }
673
674 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
675                                         MachineBasicBlock::iterator MI,
676                                         const std::vector<CalleeSavedInfo> &CSI,
677                                         const TargetRegisterInfo *TRI) const {
678   if (CSI.empty())
679     return false;
680
681   MachineFunction &MF = *MBB.getParent();
682   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
683   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
684
685   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
686   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST;
687   unsigned FltOpc = ARM::VLDMDIA_UPD;
688   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register);
689   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
690               &isARMArea2Register);
691   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
692               &isARMArea1Register);
693
694   return true;
695 }
696
697 // FIXME: Make generic?
698 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
699                                        const ARMBaseInstrInfo &TII) {
700   unsigned FnSize = 0;
701   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
702        MBBI != E; ++MBBI) {
703     const MachineBasicBlock &MBB = *MBBI;
704     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
705          I != E; ++I)
706       FnSize += TII.GetInstSizeInBytes(I);
707   }
708   return FnSize;
709 }
710
711 /// estimateStackSize - Estimate and return the size of the frame.
712 /// FIXME: Make generic?
713 static unsigned estimateStackSize(MachineFunction &MF) {
714   const MachineFrameInfo *FFI = MF.getFrameInfo();
715   int Offset = 0;
716   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
717     int FixedOff = -FFI->getObjectOffset(i);
718     if (FixedOff > Offset) Offset = FixedOff;
719   }
720   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
721     if (FFI->isDeadObjectIndex(i))
722       continue;
723     Offset += FFI->getObjectSize(i);
724     unsigned Align = FFI->getObjectAlignment(i);
725     // Adjust to alignment boundary
726     Offset = (Offset+Align-1)/Align*Align;
727   }
728   return (unsigned)Offset;
729 }
730
731 /// estimateRSStackSizeLimit - Look at each instruction that references stack
732 /// frames and return the stack size limit beyond which some of these
733 /// instructions will require a scratch register during their expansion later.
734 // FIXME: Move to TII?
735 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
736                                          const TargetFrameLowering *TFI) {
737   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
738   unsigned Limit = (1 << 12) - 1;
739   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
740     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
741          I != E; ++I) {
742       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
743         if (!I->getOperand(i).isFI()) continue;
744
745         // When using ADDri to get the address of a stack object, 255 is the
746         // largest offset guaranteed to fit in the immediate offset.
747         if (I->getOpcode() == ARM::ADDri) {
748           Limit = std::min(Limit, (1U << 8) - 1);
749           break;
750         }
751
752         // Otherwise check the addressing mode.
753         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
754         case ARMII::AddrMode3:
755         case ARMII::AddrModeT2_i8:
756           Limit = std::min(Limit, (1U << 8) - 1);
757           break;
758         case ARMII::AddrMode5:
759         case ARMII::AddrModeT2_i8s4:
760           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
761           break;
762         case ARMII::AddrModeT2_i12:
763           // i12 supports only positive offset so these will be converted to
764           // i8 opcodes. See llvm::rewriteT2FrameIndex.
765           if (TFI->hasFP(MF) && AFI->hasStackFrame())
766             Limit = std::min(Limit, (1U << 8) - 1);
767           break;
768         case ARMII::AddrMode4:
769         case ARMII::AddrMode6:
770           // Addressing modes 4 & 6 (load/store) instructions can't encode an
771           // immediate offset for stack references.
772           return 0;
773         default:
774           break;
775         }
776         break; // At most one FI per instruction
777       }
778     }
779   }
780
781   return Limit;
782 }
783
784 void
785 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
786                                                        RegScavenger *RS) const {
787   // This tells PEI to spill the FP as if it is any other callee-save register
788   // to take advantage the eliminateFrameIndex machinery. This also ensures it
789   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
790   // to combine multiple loads / stores.
791   bool CanEliminateFrame = true;
792   bool CS1Spilled = false;
793   bool LRSpilled = false;
794   unsigned NumGPRSpills = 0;
795   SmallVector<unsigned, 4> UnspilledCS1GPRs;
796   SmallVector<unsigned, 4> UnspilledCS2GPRs;
797   const ARMBaseRegisterInfo *RegInfo =
798     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
799   const ARMBaseInstrInfo &TII =
800     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
801   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
802   MachineFrameInfo *MFI = MF.getFrameInfo();
803   unsigned FramePtr = RegInfo->getFrameRegister(MF);
804
805   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
806   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
807   // since it's not always possible to restore sp from fp in a single
808   // instruction.
809   // FIXME: It will be better just to find spare register here.
810   if (AFI->isThumb2Function() &&
811       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
812     MF.getRegInfo().setPhysRegUsed(ARM::R4);
813
814   if (AFI->isThumb1OnlyFunction()) {
815     // Spill LR if Thumb1 function uses variable length argument lists.
816     if (AFI->getVarArgsRegSaveSize() > 0)
817       MF.getRegInfo().setPhysRegUsed(ARM::LR);
818
819     // Spill R4 if Thumb1 epilogue has to restore SP from FP since 
820     // FIXME: It will be better just to find spare register here.
821     if (MFI->hasVarSizedObjects())
822       MF.getRegInfo().setPhysRegUsed(ARM::R4);
823   }
824
825   // Spill the BasePtr if it's used.
826   if (RegInfo->hasBasePointer(MF))
827     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
828
829   // Don't spill FP if the frame can be eliminated. This is determined
830   // by scanning the callee-save registers to see if any is used.
831   const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
832   for (unsigned i = 0; CSRegs[i]; ++i) {
833     unsigned Reg = CSRegs[i];
834     bool Spilled = false;
835     if (MF.getRegInfo().isPhysRegUsed(Reg)) {
836       AFI->setCSRegisterIsSpilled(Reg);
837       Spilled = true;
838       CanEliminateFrame = false;
839     } else {
840       // Check alias registers too.
841       for (const unsigned *Aliases =
842              RegInfo->getAliasSet(Reg); *Aliases; ++Aliases) {
843         if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
844           Spilled = true;
845           CanEliminateFrame = false;
846         }
847       }
848     }
849
850     if (!ARM::GPRRegisterClass->contains(Reg))
851       continue;
852
853     if (Spilled) {
854       NumGPRSpills++;
855
856       if (!STI.isTargetDarwin()) {
857         if (Reg == ARM::LR)
858           LRSpilled = true;
859         CS1Spilled = true;
860         continue;
861       }
862
863       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
864       switch (Reg) {
865       case ARM::LR:
866         LRSpilled = true;
867         // Fallthrough
868       case ARM::R4: case ARM::R5:
869       case ARM::R6: case ARM::R7:
870         CS1Spilled = true;
871         break;
872       default:
873         break;
874       }
875     } else {
876       if (!STI.isTargetDarwin()) {
877         UnspilledCS1GPRs.push_back(Reg);
878         continue;
879       }
880
881       switch (Reg) {
882       case ARM::R4: case ARM::R5:
883       case ARM::R6: case ARM::R7:
884       case ARM::LR:
885         UnspilledCS1GPRs.push_back(Reg);
886         break;
887       default:
888         UnspilledCS2GPRs.push_back(Reg);
889         break;
890       }
891     }
892   }
893
894   bool ForceLRSpill = false;
895   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
896     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
897     // Force LR to be spilled if the Thumb function size is > 2048. This enables
898     // use of BL to implement far jump. If it turns out that it's not needed
899     // then the branch fix up path will undo it.
900     if (FnSize >= (1 << 11)) {
901       CanEliminateFrame = false;
902       ForceLRSpill = true;
903     }
904   }
905
906   // If any of the stack slot references may be out of range of an immediate
907   // offset, make sure a register (or a spill slot) is available for the
908   // register scavenger. Note that if we're indexing off the frame pointer, the
909   // effective stack size is 4 bytes larger since the FP points to the stack
910   // slot of the previous FP. Also, if we have variable sized objects in the
911   // function, stack slot references will often be negative, and some of
912   // our instructions are positive-offset only, so conservatively consider
913   // that case to want a spill slot (or register) as well. Similarly, if
914   // the function adjusts the stack pointer during execution and the
915   // adjustments aren't already part of our stack size estimate, our offset
916   // calculations may be off, so be conservative.
917   // FIXME: We could add logic to be more precise about negative offsets
918   //        and which instructions will need a scratch register for them. Is it
919   //        worth the effort and added fragility?
920   bool BigStack =
921     (RS &&
922      (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
923       estimateRSStackSizeLimit(MF, this)))
924     || MFI->hasVarSizedObjects()
925     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
926
927   bool ExtraCSSpill = false;
928   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
929     AFI->setHasStackFrame(true);
930
931     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
932     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
933     if (!LRSpilled && CS1Spilled) {
934       MF.getRegInfo().setPhysRegUsed(ARM::LR);
935       AFI->setCSRegisterIsSpilled(ARM::LR);
936       NumGPRSpills++;
937       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
938                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
939       ForceLRSpill = false;
940       ExtraCSSpill = true;
941     }
942
943     if (hasFP(MF)) {
944       MF.getRegInfo().setPhysRegUsed(FramePtr);
945       NumGPRSpills++;
946     }
947
948     // If stack and double are 8-byte aligned and we are spilling an odd number
949     // of GPRs, spill one extra callee save GPR so we won't have to pad between
950     // the integer and double callee save areas.
951     unsigned TargetAlign = getStackAlignment();
952     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
953       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
954         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
955           unsigned Reg = UnspilledCS1GPRs[i];
956           // Don't spill high register if the function is thumb1
957           if (!AFI->isThumb1OnlyFunction() ||
958               isARMLowRegister(Reg) || Reg == ARM::LR) {
959             MF.getRegInfo().setPhysRegUsed(Reg);
960             AFI->setCSRegisterIsSpilled(Reg);
961             if (!RegInfo->isReservedReg(MF, Reg))
962               ExtraCSSpill = true;
963             break;
964           }
965         }
966       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
967         unsigned Reg = UnspilledCS2GPRs.front();
968         MF.getRegInfo().setPhysRegUsed(Reg);
969         AFI->setCSRegisterIsSpilled(Reg);
970         if (!RegInfo->isReservedReg(MF, Reg))
971           ExtraCSSpill = true;
972       }
973     }
974
975     // Estimate if we might need to scavenge a register at some point in order
976     // to materialize a stack offset. If so, either spill one additional
977     // callee-saved register or reserve a special spill slot to facilitate
978     // register scavenging. Thumb1 needs a spill slot for stack pointer
979     // adjustments also, even when the frame itself is small.
980     if (BigStack && !ExtraCSSpill) {
981       // If any non-reserved CS register isn't spilled, just spill one or two
982       // extra. That should take care of it!
983       unsigned NumExtras = TargetAlign / 4;
984       SmallVector<unsigned, 2> Extras;
985       while (NumExtras && !UnspilledCS1GPRs.empty()) {
986         unsigned Reg = UnspilledCS1GPRs.back();
987         UnspilledCS1GPRs.pop_back();
988         if (!RegInfo->isReservedReg(MF, Reg) &&
989             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
990              Reg == ARM::LR)) {
991           Extras.push_back(Reg);
992           NumExtras--;
993         }
994       }
995       // For non-Thumb1 functions, also check for hi-reg CS registers
996       if (!AFI->isThumb1OnlyFunction()) {
997         while (NumExtras && !UnspilledCS2GPRs.empty()) {
998           unsigned Reg = UnspilledCS2GPRs.back();
999           UnspilledCS2GPRs.pop_back();
1000           if (!RegInfo->isReservedReg(MF, Reg)) {
1001             Extras.push_back(Reg);
1002             NumExtras--;
1003           }
1004         }
1005       }
1006       if (Extras.size() && NumExtras == 0) {
1007         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1008           MF.getRegInfo().setPhysRegUsed(Extras[i]);
1009           AFI->setCSRegisterIsSpilled(Extras[i]);
1010         }
1011       } else if (!AFI->isThumb1OnlyFunction()) {
1012         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
1013         // closest to SP or frame pointer.
1014         const TargetRegisterClass *RC = ARM::GPRRegisterClass;
1015         RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1016                                                            RC->getAlignment(),
1017                                                            false));
1018       }
1019     }
1020   }
1021
1022   if (ForceLRSpill) {
1023     MF.getRegInfo().setPhysRegUsed(ARM::LR);
1024     AFI->setCSRegisterIsSpilled(ARM::LR);
1025     AFI->setLRIsSpilledForFarJump(true);
1026   }
1027 }